baychat 0.52.0 → 0.53.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "baychat",
3
- "version": "0.52.0",
3
+ "version": "0.53.0",
4
4
  "displayName": "BayChat",
5
5
  "description": "Wakes this Claude Code session the moment a BayChat message arrives: no Monitor, no 30-minute deadline. Uses the baychat CLI already on this computer (npm install -g baychat, then baychat login).",
6
6
  "author": {
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ // THE CLI NEVER STARTS A SECOND AGENT (plan 2, 19 Nov 2026 — the 03:28 newcomer).
3
+ //
4
+ // BayChat's old onboarding sentence told a coding agent to "run npx -y baychat". Bare `baychat` signs the
5
+ // computer in with a QR code (it waits for an approval nobody inside the agent can give) and then STARTS A
6
+ // SESSION — a second Claude Code or Codex inside the first one. Run by an agent, both halves are wrong. So
7
+ // bare `baychat` and `baychat start` stop when there is no terminal, or when they are run inside an agent,
8
+ // and print the one next step instead. A person who really means it says so: `baychat --here`
9
+ // (`baychat setup` still sets up without starting anything).
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.NODE_TOO_OLD = exports.AGENT_HOST_ENV = void 0;
12
+ exports.agentHostOf = agentHostOf;
13
+ exports.startGuard = startGuard;
14
+ exports.nodeTooOld = nodeTooOld;
15
+ /**
16
+ * The variables an agent puts in the environment of the commands it runs, one per entry with where it comes
17
+ * from. Only markers that a person's own terminal never has: Cursor's `CURSOR_TRACE_ID` is left out on
18
+ * purpose, because Cursor sets it in its integrated terminal too, where a person types.
19
+ */
20
+ exports.AGENT_HOST_ENV = [
21
+ // Claude Code sets CLAUDECODE=1 in every Bash tool call (and in `!` commands typed into it).
22
+ { name: "CLAUDECODE", agent: "Claude Code", note: "set to 1 in the shell of every Bash tool call" },
23
+ // Codex CLI marks the commands it runs in its sandbox (seatbelt on macOS, landlock on Linux).
24
+ { name: "CODEX_SANDBOX", agent: "Codex", note: "set when Codex runs a command in its sandbox" },
25
+ // Codex gives every command its thread id (BayChat's own join instructions read it: `$CODEX_THREAD_ID`).
26
+ { name: "CODEX_THREAD_ID", agent: "Codex", note: "the Codex thread a command was run from" },
27
+ // Cursor's agent marks the terminal commands it runs itself.
28
+ { name: "CURSOR_AGENT", agent: "Cursor", note: "set in commands Cursor's agent runs" },
29
+ // Gemini CLI marks the shell commands it runs.
30
+ { name: "GEMINI_CLI", agent: "Gemini CLI", note: "set to 1 in commands Gemini CLI runs" },
31
+ ];
32
+ /** The agent this command runs inside, from its environment; undefined when none is named. */
33
+ function agentHostOf(env) {
34
+ return exports.AGENT_HOST_ENV.find((m) => (env[m.name] ?? "") !== "")?.agent;
35
+ }
36
+ /**
37
+ * Whether bare `baychat` / `baychat start` may go on. When not, the lines to print instead: what happened, and
38
+ * the one thing to do (the sentence from BayChat, which runs `baychat connect <link>`).
39
+ */
40
+ function startGuard(ctx) {
41
+ if (ctx.here)
42
+ return { ok: true };
43
+ const host = agentHostOf(ctx.env);
44
+ if (!host && ctx.atTerminal)
45
+ return { ok: true };
46
+ return {
47
+ ok: false,
48
+ lines: [
49
+ host
50
+ ? `This is running inside ${host}, so BayChat won't sign in here or start another agent.`
51
+ : "There is no terminal here to sign in from, so BayChat won't sign in or start an agent.",
52
+ "To connect this agent: in BayChat open Add agent (or BayBrain's card), copy the sentence, and paste it into the agent.",
53
+ "It runs: npx -y baychat@latest connect \"<link>\" — one command that connects and says hello.",
54
+ "Starting a session yourself in a terminal? Run: npx baychat --here",
55
+ ],
56
+ };
57
+ }
58
+ /** The Node this runs on is older than the package needs (engines: >=20). */
59
+ function nodeTooOld(version = process.versions.node) {
60
+ const major = Number(version.split(".")[0]);
61
+ return Number.isFinite(major) && major < 20;
62
+ }
63
+ exports.NODE_TOO_OLD = "BayChat needs Node 20 or newer. Install it from nodejs.org, then run the same command again.";
package/dist/api.js CHANGED
@@ -224,11 +224,10 @@ async function pollDeviceLink(baseUrl, id, pollSecret) {
224
224
  * Spend a connect link (`baychat connect <link>`, docs/features/CONNECT_MY_AGENT.md). Single use:
225
225
  * a 404 covers unknown, expired, already used and tried too often alike.
226
226
  */
227
- async function redeemConnectLink(baseUrl, token, deviceName,
228
- /** The agent's own name, for a link the person left unnamed. */
229
- ownName) {
227
+ async function redeemConnectLink(baseUrl, token, deviceName, ownName, // the agent's own name, for a link the person left unnamed
228
+ signal) {
230
229
  const res = await fetch(`${baseUrl}/api/device-links/connect/redeem`, {
231
- signal: AbortSignal.timeout(DEVICE_AUTH_TIMEOUT_MS),
230
+ signal: signal ?? AbortSignal.timeout(DEVICE_AUTH_TIMEOUT_MS),
232
231
  method: "POST",
233
232
  headers: { "Content-Type": "application/json" },
234
233
  body: JSON.stringify({ token, ...(deviceName ? { deviceName } : {}), ...(ownName ? { agentName: ownName } : {}) }),
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.DEV_CHANNELS_FLAG = exports.PLUGIN_FLAG_VALUE = exports.PLUGIN_ID = exports.CHANNEL_FLAG_VALUE = exports.CHANNEL_MCP_ENTRY = void 0;
37
37
  exports.isOurChannelValue = isOurChannelValue;
38
38
  exports.argsEnableChannel = argsEnableChannel;
39
+ exports.isClaudeCodeProcess = isClaudeCodeProcess;
39
40
  exports.realProcessReader = realProcessReader;
40
41
  exports.detectChannel = detectChannel;
41
42
  /**
@@ -101,6 +102,17 @@ function argsEnableChannel(args) {
101
102
  }
102
103
  return false;
103
104
  }
105
+ /**
106
+ * Is this process Claude Code itself? The native binary (`claude`, `claude.exe`, or a
107
+ * `claude/versions/<v>` file), or Node running its CLI (`…/claude/cli.js`, `@anthropic-ai/claude-code`).
108
+ */
109
+ function isClaudeCodeProcess(args) {
110
+ const first = args[0] ?? "";
111
+ if (/(^|[\\/])claude(\.exe)?$/i.test(first) || /[\\/]claude[\\/]versions[\\/][^\\/]+$/i.test(first))
112
+ return true;
113
+ const script = args[1] ?? "";
114
+ return /(^|[\\/])node(\.exe)?$/i.test(first) && /([\\/]claude[\\/]cli\.js|@anthropic-ai[\\/]claude-code)/i.test(script);
115
+ }
104
116
  /** Linux: /proc, exact argv. Elsewhere: `ps`, whose argument text is split on spaces. */
105
117
  function realProcessReader(platform = process.platform) {
106
118
  return (pid) => {
@@ -147,6 +159,11 @@ function detectChannel(opts = {}) {
147
159
  break;
148
160
  if (info.args && argsEnableChannel(info.args))
149
161
  return { active: true, how: "process" };
162
+ // Only Claude Code's own flags register this server. Above it sit a shell or a tmux server
163
+ // whose command line can carry ANOTHER Claude's flag (the Mac mini, 19 Nov: a plain `claude`
164
+ // inside the tmux `baychat claude` had started answered active and heard nothing).
165
+ if (info.args && isClaudeCodeProcess(info.args))
166
+ break;
150
167
  pid = info.ppid;
151
168
  }
152
169
  return { active: false, how: "none" };
package/dist/cli-help.js CHANGED
@@ -25,10 +25,11 @@ Usage:
25
25
  Desktop, Codex, Cursor — then starts a session if you
26
26
  are in a project folder. After that it just starts a
27
27
  session, somewhere BayChat can reach, so /clear and
28
- /new from the app work
28
+ /new from the app work. Inside an agent, or with no
29
+ terminal, it only says the next step (--here: anyway)
29
30
  baychat setup Look again and set up any agent app installed since;
30
31
  starts nothing
31
- baychat start [name] [--runtime <runtime>]
32
+ baychat start [name] [--runtime <runtime>] [--here]
32
33
  Start a NEW session (what bare \`baychat\` does),
33
34
  with a name for it; never returns to an old one
34
35
  baychat attach [name] Go back to a BayChat session open on this computer:
@@ -7,6 +7,7 @@ const config_1 = require("./config");
7
7
  const bay_mcp_1 = require("./bay-mcp");
8
8
  const client_paths_1 = require("./client-paths");
9
9
  const runtime_install_1 = require("./runtime-install");
10
+ const connect_link_budget_1 = require("./connect-link-budget");
10
11
  const bay_mcp_2 = require("./bay-mcp");
11
12
  const context_hooks_command_1 = require("./context-hooks-command");
12
13
  const launch_1 = require("./channel/launch");
@@ -26,6 +27,12 @@ async function cmdConnectClaude(opts = {}) {
26
27
  existing.baseUrl.replace(/\/$/, "") !== base ||
27
28
  !Number.isFinite(expires) ||
28
29
  expires <= Date.now()) {
30
+ // Run by a connect link: never a QR to wait on (nobody inside an agent can approve it).
31
+ const forbidden = (0, connect_link_budget_1.loginForbiddenLine)();
32
+ if (forbidden) {
33
+ console.log(forbidden);
34
+ return 2;
35
+ }
29
36
  if (!(await (0, commands_1.cmdLogin)({
30
37
  base: opts.mode === "finish" ? opts.base : base,
31
38
  registerClaude: false,
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ // Writing a client's MCP config file for `baychat connect <client>` (moved out of connect.ts, 19 Nov 2026,
3
+ // so the one-paste link path can name the very files it touches and their backups).
4
+ //
5
+ // FILE SAFETY. This edits config a user already has, so the merge is a splice rather than a rewrite, it is
6
+ // idempotent, unparseable JSON is refused rather than overwritten, the previous file is backed up first
7
+ // (`backupPathFor`, beside it), and the result is 0600 because it holds a bearer token. See
8
+ // client-config-writer.ts.
9
+ var __importDefault = (this && this.__importDefault) || function (mod) {
10
+ return (mod && mod.__esModule) ? mod : { "default": mod };
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.realIo = void 0;
14
+ exports.writeClientConfig = writeClientConfig;
15
+ exports.describeWrittenConfigs = describeWrittenConfigs;
16
+ exports.activeBinaryPath = activeBinaryPath;
17
+ exports.clientConfigTargets = clientConfigTargets;
18
+ const node_fs_1 = __importDefault(require("node:fs"));
19
+ const client_config_writer_1 = require("./client-config-writer");
20
+ const client_paths_1 = require("./client-paths");
21
+ const mcp_dialects_1 = require("./mcp-dialects");
22
+ const runtime_binary_1 = require("./runtime-binary");
23
+ /** Write the client config, backing up whatever was there first. */
24
+ function writeClientConfig(client, endpoint, io, env = (0, client_paths_1.currentPathEnv)()) {
25
+ // EVERY location this client may read, not just the canonical one. A snap
26
+ // install reads under its own confined HOME, so writing only to
27
+ // ~/.codex/config.toml produced a connect that reported success and left the
28
+ // runtime with no BayChat at all. Both are written when both apply: a machine
29
+ // can genuinely have a snap and an npm install, and guessing which one the
30
+ // user will open next is exactly the guess that failed.
31
+ const targets = (0, client_paths_1.configPathsFor)(client, env);
32
+ if (targets.length === 0) {
33
+ throw new Error(`Could not work out where ${mcp_dialects_1.CLIENT_LABELS[client]} keeps its config on this platform. ` +
34
+ "Run `npx baychat mcp-config --client " +
35
+ client +
36
+ "` and paste it yourself.");
37
+ }
38
+ const config = (0, mcp_dialects_1.buildClientConfig)(client, endpoint);
39
+ const written = targets.map((target) => {
40
+ const existing = io.readFile(target);
41
+ const merged = (0, client_config_writer_1.mergeClientConfig)(config, existing);
42
+ // Back up BEFORE writing, and only when there was something to lose. A user
43
+ // who discovers a surprise in their config later needs a way back that does
44
+ // not depend on them having made one.
45
+ // The OLDEST copy is kept (vps, 19 Nov): running connect again never replaces the original with our own version.
46
+ if (existing !== null && existing.trim() !== "" && io.readFile((0, client_config_writer_1.backupPathFor)(target)) === null) {
47
+ io.copyFile(target, (0, client_config_writer_1.backupPathFor)(target));
48
+ }
49
+ io.mkdirp((0, client_paths_1.configDirOf)(target));
50
+ io.writeFile(target, merged.content);
51
+ return { path: target, action: merged.action };
52
+ });
53
+ const [primary, ...rest] = written;
54
+ return { ...primary, alsoWritten: rest.map((r) => r.path), written };
55
+ }
56
+ /**
57
+ * What `connect` prints about the files it wrote: every one, by full path.
58
+ *
59
+ * Every file is named, not just the first: a user who later edits one needs to
60
+ * know the others exist, or they change a setting and see no effect. And a
61
+ * Microsoft Store copy of Claude Desktop is SAID to be one, because its path
62
+ * (`…\Packages\Claude_…\LocalCache\…`) is not where anyone would look, and
63
+ * being able to open the file Claude actually reads is the whole verification.
64
+ */
65
+ function describeWrittenConfigs(written) {
66
+ const lines = [];
67
+ for (const [i, file] of written.entries()) {
68
+ const verb = file.action === "created" ? "Created" : file.action === "updated" ? "Updated" : "Added to";
69
+ const store = (0, client_paths_1.isClaudeStoreConfigPath)(file.path) ? " (Microsoft Store Claude)" : "";
70
+ lines.push(i === 0 ? `✓ ${verb} ${file.path}${store}` : `✓ Also ${verb.toLowerCase()} ${file.path}${store}`);
71
+ if (file.action !== "created") {
72
+ lines.push(` Your file as it was before BayChat first changed it is at ${(0, client_config_writer_1.backupPathFor)(file.path)}`);
73
+ }
74
+ }
75
+ return lines;
76
+ }
77
+ /**
78
+ * Where this client's executable actually is, when it has one.
79
+ *
80
+ * Only the CLI clients can be located this way; Cursor and Claude Desktop are
81
+ * GUI applications with no command to resolve, and returning undefined for them
82
+ * simply means no snap redirection is applied — which is correct, because there
83
+ * is no evidence of one.
84
+ */
85
+ function activeBinaryPath(client) {
86
+ if (client !== "codex")
87
+ return undefined;
88
+ const resolved = (0, runtime_binary_1.resolveRuntimeBinary)(client, (0, runtime_binary_1.currentBinaryEnv)(process.env.BAYCHAT_CODEX_BIN));
89
+ return resolved.ok ? resolved.path : undefined;
90
+ }
91
+ /** Real filesystem IO for `writeClientConfig`. */
92
+ exports.realIo = {
93
+ readFile: (p) => {
94
+ try {
95
+ return node_fs_1.default.readFileSync(p, "utf8");
96
+ }
97
+ catch (err) {
98
+ // ENOENT is the ordinary "first run" case. Anything else — a permission
99
+ // problem, a directory where a file should be — must not be silently read
100
+ // as "no config", because that would overwrite a file we simply could not
101
+ // open.
102
+ if (err.code === "ENOENT")
103
+ return null;
104
+ throw err;
105
+ }
106
+ },
107
+ writeFile: (p, content) => {
108
+ // 0600: the file holds a bearer token.
109
+ node_fs_1.default.writeFileSync(p, content, { mode: 0o600 });
110
+ },
111
+ copyFile: (from, to) => node_fs_1.default.copyFileSync(from, to),
112
+ mkdirp: (dir) => {
113
+ node_fs_1.default.mkdirSync(dir, { recursive: true, mode: 0o700 });
114
+ },
115
+ };
116
+ /** Every file `writeClientConfig` writes for this client on this computer, as `connect` would. */
117
+ function clientConfigTargets(client) {
118
+ return (0, client_paths_1.configPathsFor)(client, { ...(0, client_paths_1.currentPathEnv)(), binaryPath: activeBinaryPath(client) });
119
+ }
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ // The clock of `baychat connect <link>` (docs/features/CONNECT_MY_AGENT.md, 19 Nov 2026).
3
+ //
4
+ // The command is run by an AGENT for a person who is watching a chat, not a terminal. A newcomer at 03:28
5
+ // waited on a QR login nobody inside the agent could approve. So the link path never waits for a person,
6
+ // and it never takes longer than a minute: every awaited step has a cap, all of them share one budget, and
7
+ // a step past its cap ends the command with what is done and ONE next step.
8
+ //
9
+ // A cap is honest only if the step can really be stopped: the network steps take an AbortSignal, and each
10
+ // app's setup runs in a child process that the signal kills (connect-link-setup.ts) — a `spawnSync` inside
11
+ // the same process would hold the clock still until it returned.
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.OutOfTime = exports.NO_LOGIN_ENV = exports.MIN_STEP_MS = exports.JOIN_RESERVE_MS = exports.CONNECT_LINK_CAPS = exports.CONNECT_LINK_BUDGET_MS = void 0;
14
+ exports.loginForbiddenLine = loginForbiddenLine;
15
+ exports.makeBudget = makeBudget;
16
+ /** The whole command, with room left under a minute for printing and exiting. */
17
+ exports.CONNECT_LINK_BUDGET_MS = 55_000;
18
+ /** Each step's own cap; a step also never gets more than what is left of the budget. */
19
+ exports.CONNECT_LINK_CAPS = {
20
+ /** Spending the link: one POST. */
21
+ redeem: 15_000,
22
+ /** Setting up the agent the link is for (its MCP entry, skill, relay). */
23
+ ownSetup: 25_000,
24
+ /** Each other agent app found on this computer. */
25
+ otherSetup: 15_000,
26
+ /** Joining the Bay and saying hello over MCP. */
27
+ join: 20_000,
28
+ };
29
+ /** Kept back for the join while apps are set up: without the join, nobody sees the hello. */
30
+ exports.JOIN_RESERVE_MS = 15_000;
31
+ /** Below this, a step is not started at all: it could not finish. */
32
+ exports.MIN_STEP_MS = 2_000;
33
+ /** Set on every setup child the link path starts: a login there would be a QR nobody can approve. */
34
+ exports.NO_LOGIN_ENV = "BAYCHAT_CONNECT_NO_LOGIN";
35
+ /** What `connect claude/codex/…` prints instead of a QR login when a connect link runs it. */
36
+ function loginForbiddenLine(env = process.env) {
37
+ return env[exports.NO_LOGIN_ENV]
38
+ ? "This computer is not signed in for this server, so nothing was set up here. Run: npx -y baychat@latest doctor"
39
+ : null;
40
+ }
41
+ /** A step that ran past its cap (or past the budget). */
42
+ class OutOfTime extends Error {
43
+ constructor() {
44
+ super("out of time");
45
+ this.name = "OutOfTime";
46
+ }
47
+ }
48
+ exports.OutOfTime = OutOfTime;
49
+ function makeBudget(totalMs = exports.CONNECT_LINK_BUDGET_MS, now = Date.now) {
50
+ const end = now() + totalMs;
51
+ const left = () => Math.max(0, end - now());
52
+ return {
53
+ left,
54
+ run(cap, step) {
55
+ const ms = Math.min(cap, left());
56
+ if (ms < exports.MIN_STEP_MS)
57
+ return Promise.reject(new OutOfTime());
58
+ const controller = new AbortController();
59
+ return new Promise((resolve, reject) => {
60
+ const timer = setTimeout(() => {
61
+ controller.abort(new OutOfTime());
62
+ reject(new OutOfTime());
63
+ }, ms);
64
+ // A step that rejects after its time was up only rejects a settled promise: nothing is left unhandled.
65
+ step(controller.signal).then((value) => {
66
+ clearTimeout(timer);
67
+ resolve(value);
68
+ }, (err) => {
69
+ clearTimeout(timer);
70
+ reject(controller.signal.aborted ? new OutOfTime() : err);
71
+ });
72
+ });
73
+ },
74
+ };
75
+ }
@@ -0,0 +1,139 @@
1
+ "use strict";
2
+ // What `baychat connect <link>` sets up on this computer, and what it says about it (19 Nov 2026).
3
+ //
4
+ // EVERY AGENT APP FOUND (Karmen's call, 19 Nov): one link sets BayChat up for the agent it is for AND every
5
+ // other agent app on this computer — Claude Code, Claude Desktop, Codex, Cursor — through the very same
6
+ // `connect <app>` paths `npx baychat setup` uses. A fresh Mac showed it doing that silently, so now it is
7
+ // said: one line BEFORE anything changes, naming exactly the other apps it found, and one line per app at
8
+ // the end, naming the file and its backup.
9
+ //
10
+ // BACKUPS. The config files `connect desktop/codex/cursor` write are backed up beside themselves before
11
+ // they change (connect-config-files.ts, `backupPathFor`). Claude Code's own `~/.claude.json` is written by
12
+ // `claude mcp add`, which keeps no copy, so it is copied here first, under the same name.
13
+ //
14
+ // EACH APP IN ITS OWN CHILD, `connect <app> --base <api>`, with the no-login mark (connect-link-budget.ts):
15
+ // the budget's signal kills it, which a `spawnSync` inside this process could not be.
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.APP_LABELS = void 0;
21
+ exports.alsoAddsLine = alsoAddsLine;
22
+ exports.connectAgainCommand = connectAgainCommand;
23
+ exports.appEndLine = appEndLine;
24
+ exports.appsOnThisComputer = appsOnThisComputer;
25
+ exports.configFilesOf = configFilesOf;
26
+ exports.setUpAppInChild = setUpAppInChild;
27
+ const node_child_process_1 = require("node:child_process");
28
+ const node_fs_1 = __importDefault(require("node:fs"));
29
+ const node_os_1 = __importDefault(require("node:os"));
30
+ const client_config_writer_1 = require("./client-config-writer");
31
+ const client_paths_1 = require("./client-paths");
32
+ const connect_config_files_1 = require("./connect-config-files");
33
+ const connect_link_budget_1 = require("./connect-link-budget");
34
+ const claude_trust_1 = require("./launch/claude-trust");
35
+ const machine_name_1 = require("./machine-name");
36
+ const runtime_binary_1 = require("./runtime-binary");
37
+ const setup_facts_1 = require("./setup-facts");
38
+ const setup_plan_1 = require("./setup-plan");
39
+ exports.APP_LABELS = {
40
+ claude: "Claude Code",
41
+ desktop: "Claude Desktop",
42
+ codex: "Codex",
43
+ cursor: "Cursor",
44
+ };
45
+ /** "Claude Desktop", "Claude Desktop and Codex", "Claude Desktop, Codex and Cursor". */
46
+ function listOf(names) {
47
+ return names.length <= 1 ? (names[0] ?? "") : `${names.slice(0, -1).join(", ")} and ${names[names.length - 1]}`;
48
+ }
49
+ /** The line before anything changes: the OTHER apps found, by name. Null when the link's own app is all there is. */
50
+ function alsoAddsLine(others) {
51
+ if (others.length === 0)
52
+ return null;
53
+ return `This also adds BayChat to ${listOf(others.map((a) => exports.APP_LABELS[a]))} (each keeps a backup).`;
54
+ }
55
+ /** The command that sets one app up again by hand. */
56
+ function connectAgainCommand(app) {
57
+ return `npx -y baychat@latest connect ${app}`;
58
+ }
59
+ /** The end line for one app: what was added where, and the backup; or what to run when it did not finish. */
60
+ function appEndLine(outcome) {
61
+ const label = exports.APP_LABELS[outcome.app];
62
+ switch (outcome.kind) {
63
+ case "done": {
64
+ if (outcome.files.length === 0)
65
+ return `✓ ${label}: BayChat added.`;
66
+ const files = outcome.files.map((f) => (f.backup ? `${f.file} (backup: ${f.backup})` : `${f.file} (a new file, nothing to back up)`));
67
+ return `✓ ${label}: BayChat added to ${files.join("; ")}`;
68
+ }
69
+ case "failed":
70
+ return `✗ ${label}: not set up. Run: ${connectAgainCommand(outcome.app)}`;
71
+ case "slow":
72
+ case "late":
73
+ return `– ${label}: not set up yet (out of time). Run: ${connectAgainCommand(outcome.app)}`;
74
+ }
75
+ }
76
+ /** The agent apps on this computer — the same test `npx baychat setup` uses (setup-facts.ts). */
77
+ function appsOnThisComputer() {
78
+ const home = node_os_1.default.homedir();
79
+ const installed = (0, setup_facts_1.installedFrom)({
80
+ home,
81
+ platform: process.platform,
82
+ pathEnv: (0, client_paths_1.currentPathEnv)(),
83
+ resolveBinary: (command) => (0, runtime_binary_1.resolveRuntimeBinary)(command, (0, runtime_binary_1.currentBinaryEnv)(process.env[`BAYCHAT_${command.toUpperCase()}_BIN`])),
84
+ }, (p) => node_fs_1.default.existsSync(p));
85
+ // In WSL, Claude Desktop is a Windows app: its config is not ours to write from here (setup-plan.ts).
86
+ return setup_plan_1.SETUP_CLIENTS.filter((app) => installed[app] && !(app === "desktop" && (0, machine_name_1.isWsl)()));
87
+ }
88
+ const hasContent = (file) => {
89
+ try {
90
+ return node_fs_1.default.readFileSync(file, "utf8").trim() !== "";
91
+ }
92
+ catch {
93
+ // Missing or unreadable: nothing there to keep a copy of.
94
+ return false;
95
+ }
96
+ };
97
+ /** The config files an app's setup writes. */
98
+ function configFilesOf(app) {
99
+ return app === "claude" ? [(0, claude_trust_1.claudeConfigPath)(process.env, node_os_1.default.homedir())] : (0, connect_config_files_1.clientConfigTargets)(app);
100
+ }
101
+ /**
102
+ * Set one app up in a child `connect <app> --base <api>`, killed when `signal` aborts. The child gets the
103
+ * no-login mark, so a missing login ends it with a line instead of a QR.
104
+ */
105
+ async function setUpAppInChild(app, base, signal) {
106
+ const files = configFilesOf(app);
107
+ const existed = new Set(files.filter(hasContent));
108
+ if (app === "claude") {
109
+ // `claude mcp add` keeps no copy of ~/.claude.json: keep one beside it, as the other apps' writes do. The OLDEST
110
+ // copy is kept (vps, 19 Nov): a second run must not replace the person's original with BayChat's own version.
111
+ for (const file of existed)
112
+ if (!node_fs_1.default.existsSync((0, client_config_writer_1.backupPathFor)(file)))
113
+ node_fs_1.default.copyFileSync(file, (0, client_config_writer_1.backupPathFor)(file));
114
+ }
115
+ const script = process.argv[1];
116
+ if (!script)
117
+ throw new Error("Could not find the BayChat CLI to run the setup.");
118
+ const output = [];
119
+ const code = await new Promise((resolve, reject) => {
120
+ const child = (0, node_child_process_1.spawn)(process.execPath, [script, "connect", app, "--base", base], {
121
+ env: { ...process.env, [connect_link_budget_1.NO_LOGIN_ENV]: "1" },
122
+ stdio: ["ignore", "pipe", "pipe"],
123
+ signal,
124
+ killSignal: "SIGKILL",
125
+ windowsHide: true,
126
+ });
127
+ const keep = (chunk) => output.push(...chunk.toString("utf8").split(/\r?\n/));
128
+ child.stdout?.on("data", keep);
129
+ child.stderr?.on("data", keep);
130
+ child.on("error", reject);
131
+ child.on("close", (exit) => resolve(exit ?? 1));
132
+ });
133
+ const tail = output.map((l) => l.trim()).filter(Boolean).slice(-3);
134
+ return {
135
+ code,
136
+ files: files.map((file) => ({ file, backup: existed.has(file) ? (0, client_config_writer_1.backupPathFor)(file) : null })),
137
+ ...(code === 0 ? {} : { tail }),
138
+ };
139
+ }
@@ -4,8 +4,9 @@
4
4
  // The person, signed in to BayChat, makes a one-time link and pastes ONE sentence holding it into
5
5
  // their coding agent. The agent runs `npx -y baychat@latest connect <link>`, and this file does the
6
6
  // rest without a question: spend the link for this computer's login (the same login the QR gives),
7
- // run the ordinary `connect claude` / `connect codex` setup on top of it, join the Bay under the
8
- // name the person chose, and say so in the Bay.
7
+ // run the ordinary `connect <app>` setup on top of it — for the agent the link is for, then every
8
+ // other agent app found, said before and after (connect-link-setup.ts) — join the Bay under the
9
+ // name the person chose, and say so in the Bay. All of it within a minute (connect-link-budget.ts).
9
10
  //
10
11
  // THE LINK IS A SECRET until it is spent, so this never prints it: anything that names it shows the
11
12
  // first four characters only (`maskConnectToken`). The token lives in the link's #fragment, which
@@ -16,6 +17,7 @@ exports.looksLikeConnectLink = looksLikeConnectLink;
16
17
  exports.maskConnectToken = maskConnectToken;
17
18
  exports.parseConnectLink = parseConnectLink;
18
19
  exports.describeRedeemError = describeRedeemError;
20
+ exports.joinLine = joinLine;
19
21
  exports.helloLine = helloLine;
20
22
  exports.cmdConnectLink = cmdConnectLink;
21
23
  exports.joinAndGreetOverMcp = joinAndGreetOverMcp;
@@ -23,10 +25,15 @@ const index_js_1 = require("@modelcontextprotocol/sdk/client/index.js");
23
25
  const streamableHttp_js_1 = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
24
26
  const api_1 = require("./api");
25
27
  const config_1 = require("./config");
28
+ const connect_link_budget_1 = require("./connect-link-budget");
29
+ const connect_link_setup_1 = require("./connect-link-setup");
26
30
  const device_login_1 = require("./device-login");
27
31
  const machine_name_1 = require("./machine-name");
28
- /** The runtimes a link can connect, by the name in its path (`/connect/<client>`). */
29
- exports.CONNECT_LINK_CLIENTS = { "claude-code": "claude", codex: "codex" };
32
+ /**
33
+ * The runtimes a link can connect, by the name in its path (`/connect/<client>`), and the `connect <app>`
34
+ * setup each one runs. Cursor since 19 Nov 2026: `connect cursor`, Cursor's own MCP file.
35
+ */
36
+ exports.CONNECT_LINK_CLIENTS = { "claude-code": "claude", codex: "codex", cursor: "cursor" };
30
37
  /** Whether a `connect` argument is a link rather than a runtime name. */
31
38
  function looksLikeConnectLink(arg) {
32
39
  return /^https?:\/\//i.test(arg.trim()) && /\/connect\//.test(arg);
@@ -104,11 +111,52 @@ function describeRedeemError(error) {
104
111
  }
105
112
  return error instanceof Error ? error.message : String(error);
106
113
  }
114
+ /**
115
+ * What the person says to the agent after its restart (vps, 19 Nov 2026: on a fresh Mac Claude Code came back and did
116
+ * nothing until told). The same words the app's card copies (`joinBayChatLine` in both apps' lib/connect-link.ts).
117
+ */
118
+ function joinLine(name) {
119
+ return `join BayChat as ${name}`;
120
+ }
107
121
  function helloLine(name, runtime, computer) {
108
- const app = runtime === "claude" ? "Claude Code" : "Codex";
109
- return `Connected ✅ I'm ${name}, ${app} on ${computer}. Restart ${app} (or start a session from the BayChat app) and I'll answer here.`;
122
+ const app = connect_link_setup_1.APP_LABELS[runtime];
123
+ return `Connected ✅ I'm ${name}, ${app} on ${computer}. Restart ${app}, then tell it: ${joinLine(name)} (or start a session from the BayChat app), and I'll answer here.`;
124
+ }
125
+ /** Set every app up, the link's own first, inside the budget. Each one's outcome, in that order. */
126
+ async function setUpApps(apps, own, base, deps, budget) {
127
+ const outcomes = [];
128
+ for (const app of apps) {
129
+ // The join's share of the clock is kept back: without the join, nobody sees the hello.
130
+ const room = Math.min(app === own ? connect_link_budget_1.CONNECT_LINK_CAPS.ownSetup : connect_link_budget_1.CONNECT_LINK_CAPS.otherSetup, budget.left() - connect_link_budget_1.JOIN_RESERVE_MS);
131
+ if (room < connect_link_budget_1.MIN_STEP_MS) {
132
+ outcomes.push({ app, kind: "late" });
133
+ continue;
134
+ }
135
+ try {
136
+ const done = await budget.run(room, (signal) => deps.setUp(app, base, signal));
137
+ if (done.code === 0)
138
+ outcomes.push({ app, kind: "done", files: done.files });
139
+ else {
140
+ for (const line of done.tail ?? [])
141
+ deps.log(` (${connect_link_setup_1.APP_LABELS[app]}: ${line})`);
142
+ outcomes.push({ app, kind: "failed" });
143
+ }
144
+ }
145
+ catch (e) {
146
+ if (!(e instanceof connect_link_budget_1.OutOfTime))
147
+ deps.log(` (${connect_link_setup_1.APP_LABELS[app]}: ${e instanceof Error ? e.message : String(e)})`);
148
+ outcomes.push({ app, kind: e instanceof connect_link_budget_1.OutOfTime ? "slow" : "failed" });
149
+ }
150
+ // The agent the link is for comes first; if it did not take, the others wait for `doctor`.
151
+ if (app === own && outcomes[outcomes.length - 1].kind !== "done")
152
+ break;
153
+ }
154
+ return outcomes;
110
155
  }
111
- /** `baychat connect <link>`. 0 = connected, 1 = refused (the reason is printed), 2 = setup failed. */
156
+ /**
157
+ * `baychat connect <link>`. 0 = connected, 1 = refused (the reason is printed), 2 = signed in but not
158
+ * finished (what is done, and one next step, are printed). Never longer than a minute, never a QR.
159
+ */
112
160
  async function cmdConnectLink(raw, deps, opts = {}) {
113
161
  let link;
114
162
  try {
@@ -118,15 +166,19 @@ async function cmdConnectLink(raw, deps, opts = {}) {
118
166
  deps.log(e instanceof Error ? e.message : String(e));
119
167
  return 1;
120
168
  }
169
+ const budget = (0, connect_link_budget_1.makeBudget)();
121
170
  const runtime = exports.CONNECT_LINK_CLIENTS[link.client];
171
+ const app = connect_link_setup_1.APP_LABELS[runtime];
122
172
  const computer = (0, machine_name_1.machineName)();
123
173
  deps.log(`Connecting this computer with link ${maskConnectToken(link.token)}`);
124
174
  let redeemed;
125
175
  try {
126
- redeemed = await deps.redeem(link.apiBase, link.token, computer, opts.name?.trim() || undefined);
176
+ redeemed = await budget.run(connect_link_budget_1.CONNECT_LINK_CAPS.redeem, (signal) => deps.redeem(link.apiBase, link.token, computer, opts.name?.trim() || undefined, signal));
127
177
  }
128
178
  catch (e) {
129
- deps.log(describeRedeemError(e));
179
+ deps.log(e instanceof connect_link_budget_1.OutOfTime
180
+ ? "BayChat did not answer in time, so nothing changed on this computer. Run the same command once more."
181
+ : describeRedeemError(e));
130
182
  return 1;
131
183
  }
132
184
  // The API this link was checked against, never one the answer names: a server cannot move this
@@ -142,9 +194,19 @@ async function cmdConnectLink(raw, deps, opts = {}) {
142
194
  else if (redeemed.agentName !== redeemed.requestedName) {
143
195
  deps.log(` "${redeemed.requestedName}" is somebody else's agent in this Bay, so this one is "${redeemed.agentName}".`);
144
196
  }
145
- const code = await deps.setUp(runtime, base);
146
- if (code !== 0) {
147
- deps.log("The login is saved, but the setup did not finish. Run: npx -y baychat@latest doctor");
197
+ // Every agent app found, the link's own first — said BEFORE anything changes (Karmen, 19 Nov).
198
+ const others = deps.findApps().filter((a) => a !== runtime);
199
+ const also = (0, connect_link_setup_1.alsoAddsLine)(others);
200
+ if (also)
201
+ deps.log(also);
202
+ const outcomes = await setUpApps([runtime, ...others], runtime, base, deps, budget);
203
+ for (const outcome of outcomes)
204
+ deps.log((0, connect_link_setup_1.appEndLine)(outcome));
205
+ const own = outcomes[0];
206
+ if (own.kind !== "done") {
207
+ deps.log(own.kind === "failed"
208
+ ? "The login is saved, but the setup did not finish. Run: npx -y baychat@latest doctor"
209
+ : `The computer is signed in to BayChat, but setting up ${app} took too long. Run: npx -y baychat@latest doctor`);
148
210
  return 2;
149
211
  }
150
212
  // The group comes only from the server's record of the link, never from anything typed here.
@@ -153,11 +215,15 @@ async function cmdConnectLink(raw, deps, opts = {}) {
153
215
  const where = g ? ("id" in g ? (g.title ?? "the group") : g.newTitle) : null;
154
216
  let landed;
155
217
  try {
156
- landed = await deps.joinAndGreet(base, device.token, redeemed.agentName, helloLine(redeemed.agentName, runtime, computer), target);
218
+ landed = await budget.run(connect_link_budget_1.CONNECT_LINK_CAPS.join, (signal) => deps.joinAndGreet(base, device.token, redeemed.agentName, helloLine(redeemed.agentName, runtime, computer), target, signal));
157
219
  }
158
220
  catch (e) {
221
+ if (e instanceof connect_link_budget_1.OutOfTime) {
222
+ deps.log(`The computer is signed in and ${app} is set up, but joining the Bay took too long. Restart ${app}, then tell it: ${joinLine(redeemed.agentName)}`);
223
+ return 2;
224
+ }
159
225
  deps.log(`Joined nothing yet: ${describeRedeemError(e)}`);
160
- deps.log("The computer is connected. After a restart the agent can join with /baychat <name>.");
226
+ deps.log(`The computer is connected. Restart ${app}, then tell it: ${joinLine(redeemed.agentName)}`);
161
227
  return 2;
162
228
  }
163
229
  if (where && !landed.inGroup) {
@@ -166,7 +232,7 @@ async function cmdConnectLink(raw, deps, opts = {}) {
166
232
  else {
167
233
  deps.log(`✓ "${redeemed.agentName}" is in your Bay${where ? ` (group "${where}")` : ""} and said hello.`);
168
234
  }
169
- deps.log(` Tell the person: restart ${runtime === "claude" ? "Claude Code" : "Codex"} (or start a session from the BayChat app) so it can answer there.`);
235
+ deps.log(` Tell the person: restart ${app}, then tell it: ${joinLine(redeemed.agentName)} (or start a session from the BayChat app), so it can answer there.`);
170
236
  return 0;
171
237
  }
172
238
  /** The conversation a join or create answer names: its text says "conversation <id>." either way. */
@@ -216,10 +282,12 @@ async function joinAs(call, name, group) {
216
282
  return id;
217
283
  }
218
284
  /** The real join + hello: the remote MCP's own tools (`create_group`, `join_session`, `send_message`), as the device. */
219
- async function joinAndGreetOverMcp(base, deviceToken, name, hello, target) {
285
+ async function joinAndGreetOverMcp(base, deviceToken, name, hello, target,
286
+ /** The budget's: aborts every request of this connection when the join's time is up. */
287
+ signal) {
220
288
  const client = new index_js_1.Client({ name: "baychat-connect", version: "1" });
221
289
  await client.connect(new streamableHttp_js_1.StreamableHTTPClientTransport(new URL("/api/mcp", base), {
222
- requestInit: { headers: { Authorization: `Bearer ${deviceToken}` }, signal: AbortSignal.timeout(20_000) },
290
+ requestInit: { headers: { Authorization: `Bearer ${deviceToken}` }, signal: signal ?? AbortSignal.timeout(20_000) },
223
291
  }));
224
292
  const call = async (tool, args) => {
225
293
  const res = await client.callTool({ name: tool, arguments: args });
@@ -261,10 +329,11 @@ async function joinAndGreetOverMcp(base, deviceToken, name, hello, target) {
261
329
  await client.close().catch((e) => console.error(`(closing the BayChat connection: ${e instanceof Error ? e.message : String(e)})`));
262
330
  }
263
331
  }
264
- const realConnectLinkDeps = (setUp) => ({
332
+ const realConnectLinkDeps = () => ({
265
333
  redeem: api_1.redeemConnectLink,
266
334
  save: device_login_1.saveApprovedDeviceLogin,
267
- setUp,
335
+ findApps: connect_link_setup_1.appsOnThisComputer,
336
+ setUp: connect_link_setup_1.setUpAppInChild,
268
337
  joinAndGreet: joinAndGreetOverMcp,
269
338
  log: (line) => console.log(line),
270
339
  });
package/dist/connect.js CHANGED
@@ -23,32 +23,26 @@
23
23
  // to configure and no session concept, so `baychat pair <code>` remains their
24
24
  // path. It is not this one.
25
25
  //
26
- // FILE SAFETY. This edits config a user already has, so the merge is a splice
27
- // rather than a rewrite, it is idempotent, unparseable JSON is refused rather
28
- // than overwritten, the previous file is backed up first, and the result is 0600
29
- // because it holds a bearer token. See client-config-writer.ts.
30
- var __importDefault = (this && this.__importDefault) || function (mod) {
31
- return (mod && mod.__esModule) ? mod : { "default": mod };
32
- };
26
+ // FILE SAFETY: connect-config-files.ts (the splice, the backup beside the file, 0600).
33
27
  Object.defineProperty(exports, "__esModule", { value: true });
34
- exports.cmdConnectClaude = void 0;
28
+ exports.cmdConnectClaude = exports.writeClientConfig = exports.describeWrittenConfigs = void 0;
35
29
  exports.renderConnectMenu = renderConnectMenu;
36
30
  exports.isClaudeConnectTarget = isClaudeConnectTarget;
37
31
  exports.parseConnectClient = parseConnectClient;
38
- exports.writeClientConfig = writeClientConfig;
39
- exports.describeWrittenConfigs = describeWrittenConfigs;
40
32
  exports.cmdConnect = cmdConnect;
41
- const node_fs_1 = __importDefault(require("node:fs"));
42
- const client_config_writer_1 = require("./client-config-writer");
43
33
  const client_paths_1 = require("./client-paths");
44
34
  const commands_1 = require("./commands");
35
+ const connect_config_files_1 = require("./connect-config-files");
36
+ var connect_config_files_2 = require("./connect-config-files");
37
+ Object.defineProperty(exports, "describeWrittenConfigs", { enumerable: true, get: function () { return connect_config_files_2.describeWrittenConfigs; } });
38
+ Object.defineProperty(exports, "writeClientConfig", { enumerable: true, get: function () { return connect_config_files_2.writeClientConfig; } });
39
+ const connect_link_budget_1 = require("./connect-link-budget");
45
40
  const config_1 = require("./config");
46
41
  const connect_plan_1 = require("./connect-plan");
47
42
  const mcp_dialects_1 = require("./mcp-dialects");
48
43
  const commands_2 = require("./relay/commands");
49
44
  const runtime_install_1 = require("./runtime-install");
50
45
  const runtimes_1 = require("./runtimes");
51
- const runtime_binary_1 = require("./runtime-binary");
52
46
  const connect_claude_1 = require("./connect-claude");
53
47
  var connect_claude_2 = require("./connect-claude");
54
48
  Object.defineProperty(exports, "cmdConnectClaude", { enumerable: true, get: function () { return connect_claude_2.cmdConnectClaude; } });
@@ -115,98 +109,6 @@ function parseConnectClient(value) {
115
109
  }
116
110
  return match;
117
111
  }
118
- /** Write the client config, backing up whatever was there first. */
119
- function writeClientConfig(client, endpoint, io, env = (0, client_paths_1.currentPathEnv)()) {
120
- // EVERY location this client may read, not just the canonical one. A snap
121
- // install reads under its own confined HOME, so writing only to
122
- // ~/.codex/config.toml produced a connect that reported success and left the
123
- // runtime with no BayChat at all. Both are written when both apply: a machine
124
- // can genuinely have a snap and an npm install, and guessing which one the
125
- // user will open next is exactly the guess that failed.
126
- const targets = (0, client_paths_1.configPathsFor)(client, env);
127
- if (targets.length === 0) {
128
- throw new Error(`Could not work out where ${mcp_dialects_1.CLIENT_LABELS[client]} keeps its config on this platform. ` +
129
- "Run `npx baychat mcp-config --client " +
130
- client +
131
- "` and paste it yourself.");
132
- }
133
- const config = (0, mcp_dialects_1.buildClientConfig)(client, endpoint);
134
- const written = targets.map((target) => {
135
- const existing = io.readFile(target);
136
- const merged = (0, client_config_writer_1.mergeClientConfig)(config, existing);
137
- // Back up BEFORE writing, and only when there was something to lose. A user
138
- // who discovers a surprise in their config later needs a way back that does
139
- // not depend on them having made one.
140
- if (existing !== null && existing.trim() !== "") {
141
- io.copyFile(target, (0, client_config_writer_1.backupPathFor)(target));
142
- }
143
- io.mkdirp((0, client_paths_1.configDirOf)(target));
144
- io.writeFile(target, merged.content);
145
- return { path: target, action: merged.action };
146
- });
147
- const [primary, ...rest] = written;
148
- return { ...primary, alsoWritten: rest.map((r) => r.path), written };
149
- }
150
- /**
151
- * What `connect` prints about the files it wrote: every one, by full path.
152
- *
153
- * Every file is named, not just the first: a user who later edits one needs to
154
- * know the others exist, or they change a setting and see no effect. And a
155
- * Microsoft Store copy of Claude Desktop is SAID to be one, because its path
156
- * (`…\Packages\Claude_…\LocalCache\…`) is not where anyone would look, and
157
- * being able to open the file Claude actually reads is the whole verification.
158
- */
159
- function describeWrittenConfigs(written) {
160
- const lines = [];
161
- for (const [i, file] of written.entries()) {
162
- const verb = file.action === "created" ? "Created" : file.action === "updated" ? "Updated" : "Added to";
163
- const store = (0, client_paths_1.isClaudeStoreConfigPath)(file.path) ? " (Microsoft Store Claude)" : "";
164
- lines.push(i === 0 ? `✓ ${verb} ${file.path}${store}` : `✓ Also ${verb.toLowerCase()} ${file.path}${store}`);
165
- if (file.action !== "created") {
166
- lines.push(` A copy of the previous file is at ${(0, client_config_writer_1.backupPathFor)(file.path)}`);
167
- }
168
- }
169
- return lines;
170
- }
171
- /**
172
- * Where this client's executable actually is, when it has one.
173
- *
174
- * Only the CLI clients can be located this way; Cursor and Claude Desktop are
175
- * GUI applications with no command to resolve, and returning undefined for them
176
- * simply means no snap redirection is applied — which is correct, because there
177
- * is no evidence of one.
178
- */
179
- function activeBinaryPath(client) {
180
- if (client !== "codex")
181
- return undefined;
182
- const resolved = (0, runtime_binary_1.resolveRuntimeBinary)(client, (0, runtime_binary_1.currentBinaryEnv)(process.env.BAYCHAT_CODEX_BIN));
183
- return resolved.ok ? resolved.path : undefined;
184
- }
185
- /** Real filesystem IO for `writeClientConfig`. */
186
- const realIo = {
187
- readFile: (p) => {
188
- try {
189
- return node_fs_1.default.readFileSync(p, "utf8");
190
- }
191
- catch (err) {
192
- // ENOENT is the ordinary "first run" case. Anything else — a permission
193
- // problem, a directory where a file should be — must not be silently read
194
- // as "no config", because that would overwrite a file we simply could not
195
- // open.
196
- if (err.code === "ENOENT")
197
- return null;
198
- throw err;
199
- }
200
- },
201
- writeFile: (p, content) => {
202
- // 0600: the file holds a bearer token.
203
- node_fs_1.default.writeFileSync(p, content, { mode: 0o600 });
204
- },
205
- copyFile: (from, to) => node_fs_1.default.copyFileSync(from, to),
206
- mkdirp: (dir) => {
207
- node_fs_1.default.mkdirSync(dir, { recursive: true, mode: 0o700 });
208
- },
209
- };
210
112
  /**
211
113
  * `baychat connect <client>`.
212
114
  *
@@ -222,7 +124,9 @@ async function cmdConnect(clientArg, opts = {}) {
222
124
  if ((0, connect_link_1.looksLikeConnectLink)(clientArg)) {
223
125
  if (opts.mode)
224
126
  throw new Error("A connect link does not take --start/--finish.");
225
- return (0, connect_link_1.cmdConnectLink)(clientArg, (0, connect_link_1.realConnectLinkDeps)((runtime, base) => runtime === "claude" ? (0, connect_claude_1.cmdConnectClaude)({ base }) : cmdConnect("codex", { base })), opts.name ? { name: opts.name } : {});
127
+ // Each app's setup runs as its own `connect <app>` child (connect-link-setup.ts), so the 60-second
128
+ // budget can stop even a hung `claude mcp add`.
129
+ return (0, connect_link_1.cmdConnectLink)(clientArg, (0, connect_link_1.realConnectLinkDeps)(), opts.name ? { name: opts.name } : {});
226
130
  }
227
131
  // Claude Code first: it is not an MCP-config client, so it must not reach
228
132
  // `parseConnectClient`, which would reject it.
@@ -304,6 +208,10 @@ async function cmdConnect(clientArg, opts = {}) {
304
208
  async function runStep(step, ctx) {
305
209
  switch (step.kind) {
306
210
  case "device-login": {
211
+ // Run by a connect link: never a QR to wait on (nobody inside an agent can approve it).
212
+ const forbidden = (0, connect_link_budget_1.loginForbiddenLine)();
213
+ if (forbidden)
214
+ return console.log(forbidden), { kind: "abort", code: 2 };
307
215
  if (!ctx.mode)
308
216
  console.log(step.reason === "expired"
309
217
  ? "Your login on this computer has expired. Reconnecting this computer…\n"
@@ -345,11 +253,11 @@ async function runStep(step, ctx) {
345
253
  // comment because writing an empty bearer fails silently inside a client.
346
254
  throw new Error("Internal: no device credential to write — login must run first.");
347
255
  }
348
- const { written } = writeClientConfig(step.client, { url: `${ctx.base}/api/mcp`, token: device.token }, realIo,
256
+ const { written } = (0, connect_config_files_1.writeClientConfig)(step.client, { url: `${ctx.base}/api/mcp`, token: device.token }, connect_config_files_1.realIo,
349
257
  // The resolved binary is what reveals a snap install, and a snap install
350
258
  // reads a different file than the one this client "keeps its config" in.
351
- { ...(0, client_paths_1.currentPathEnv)(), binaryPath: activeBinaryPath(step.client) });
352
- for (const line of describeWrittenConfigs(written))
259
+ { ...(0, client_paths_1.currentPathEnv)(), binaryPath: (0, connect_config_files_1.activeBinaryPath)(step.client) });
260
+ for (const line of (0, connect_config_files_1.describeWrittenConfigs)(written))
353
261
  console.log(line);
354
262
  return { kind: "ok" };
355
263
  }
package/dist/main.js CHANGED
@@ -65,9 +65,9 @@ async function main() {
65
65
  // project, never in the home folder. Once set up it starts straight away, as it always did. A usage
66
66
  // dump printed at somebody who typed the product's own name would be "something else"; `--help`
67
67
  // still prints the help.
68
- if (command === undefined) {
68
+ if (command === undefined || command === "--here") {
69
69
  (0, notice_1.printUpdateNotice)(command);
70
- return (0, setup_command_1.runBare)((0, setup_command_1.realSetupDeps)());
70
+ return (0, setup_command_1.runBareGuarded)(command === "--here");
71
71
  }
72
72
  // "BayChat updated itself to …": the relay's one line for the terminal, shown once, on a command
73
73
  // a person typed (never into a hook's or an MCP server's output).
@@ -11,6 +11,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.runSetup = runSetup;
13
13
  exports.runBare = runBare;
14
+ exports.runBareGuarded = runBareGuarded;
14
15
  exports.runSetupCommand = runSetupCommand;
15
16
  exports.setupMarkPath = setupMarkPath;
16
17
  exports.realSetupDeps = realSetupDeps;
@@ -27,6 +28,7 @@ const machine_name_1 = require("./machine-name");
27
28
  const multiplexer_launch_1 = require("./multiplexer-launch");
28
29
  const setup_facts_1 = require("./setup-facts");
29
30
  const start_command_1 = require("./start-command");
31
+ const agent_host_1 = require("./agent-host");
30
32
  const setup_plan_1 = require("./setup-plan");
31
33
  /** Look, set up what is missing, and say what is ready. Returns 2 when the login was not approved. */
32
34
  async function runSetup(deps) {
@@ -72,6 +74,24 @@ async function runBare(deps) {
72
74
  return code;
73
75
  return startOrPoint(deps);
74
76
  }
77
+ /**
78
+ * Bare `baychat` as typed (main.ts): never a sign-in or a second agent from inside an agent or without a terminal
79
+ * (agent-host.ts, 19 Nov) — it prints the next step; `baychat --here` is the person saying they mean it. A Node
80
+ * older than the package needs says so first.
81
+ */
82
+ async function runBareGuarded(here) {
83
+ if ((0, agent_host_1.nodeTooOld)()) {
84
+ console.error(agent_host_1.NODE_TOO_OLD);
85
+ return 1;
86
+ }
87
+ const guard = (0, agent_host_1.startGuard)({ env: process.env, atTerminal: !!process.stdin.isTTY && !!process.stdout.isTTY, here });
88
+ if (!guard.ok) {
89
+ for (const line of guard.lines)
90
+ console.log(line);
91
+ return 0;
92
+ }
93
+ return runBare(realSetupDeps({ here }));
94
+ }
75
95
  /** `baychat setup`: always look again; start only when asked to and in a project. */
76
96
  async function runSetupCommand(deps) {
77
97
  const code = await runSetup(deps);
@@ -102,7 +122,8 @@ function realSetupDeps(over = {}) {
102
122
  },
103
123
  login: () => (0, commands_1.cmdLogin)({ registerClaude: false, hint: false }),
104
124
  connect: (client) => (client === "claude" ? (0, connect_claude_1.cmdConnectClaude)({}) : (0, connect_1.cmdConnect)(client, {})),
105
- start: () => (0, start_command_1.cmdStart)([]),
125
+ // `baychat --here` carries on into the start it asked for (agent-host.ts).
126
+ start: () => (0, start_command_1.cmdStart)(over.here ? ["--here"] : []),
106
127
  inProject: () => (0, setup_plan_1.isProjectDir)(process.cwd(), exists, os_1.default.homedir()),
107
128
  confirm: async (question) => {
108
129
  if (!process.stdin.isTTY)
@@ -43,6 +43,7 @@ const path = __importStar(require("path"));
43
43
  const attach_command_1 = require("./attach-command");
44
44
  const config_1 = require("./config");
45
45
  const multiplexer_launch_1 = require("./multiplexer-launch");
46
+ const agent_host_1 = require("./agent-host");
46
47
  const profiles_1 = require("./relay/profiles");
47
48
  const runtime_binary_1 = require("./runtime-binary");
48
49
  const update_command_1 = require("./update-command");
@@ -96,6 +97,13 @@ function startRefusal(runtime) {
96
97
  return Object.hasOwn(NOT_STARTED, runtime) ? NOT_STARTED[runtime] : undefined;
97
98
  }
98
99
  async function cmdStart(args) {
100
+ // Never a second agent from inside an agent, or with no terminal to run it in (agent-host.ts, 19 Nov).
101
+ const guard = (0, agent_host_1.startGuard)({ env: process.env, atTerminal: !!process.stdin.isTTY && !!process.stdout.isTTY, here: args.includes("--here") });
102
+ if (!guard.ok) {
103
+ for (const line of guard.lines)
104
+ console.log(line);
105
+ return 0;
106
+ }
99
107
  if (!(0, config_1.loadDeviceCredentials)()) {
100
108
  console.error("This machine is not signed in yet. Run `npx baychat` first: it signs in and sets up your agent apps.");
101
109
  return 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "baychat",
3
- "version": "0.52.0",
3
+ "version": "0.53.0",
4
4
  "description": "BayChat connector CLI — pair an agent session (Claude Code, Codex, Cursor) with BayChat, or have the relay run DeepSeek or the Cursor CLI for you",
5
5
  "bin": {
6
6
  "baychat": "dist/index.js"