baychat 0.52.0 → 0.54.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.
@@ -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).
@@ -74,6 +74,7 @@ const fs = __importStar(require("fs"));
74
74
  const path = __importStar(require("path"));
75
75
  const readline = __importStar(require("readline"));
76
76
  const config_1 = require("./config");
77
+ const pane_exit_1 = require("./pane-exit");
77
78
  const terminal_pane_1 = require("./relay/terminal-pane");
78
79
  const runtime_binary_1 = require("./runtime-binary");
79
80
  /** Set in the agent's environment to the tmux session our CLI created for it (read by detectPane). */
@@ -90,12 +91,25 @@ async function launchAgent(program, naming, deps = realLaunchDeps()) {
90
91
  if (!multiplexer)
91
92
  return runHere(program, deps);
92
93
  const argv = multiplexerArgv(multiplexer, naming, program, deps);
94
+ // Keep what the agent showed if it stops inside tmux (pane-exit.ts); never for screen or a detached start.
95
+ const capture = multiplexer === "tmux" && naming.kind !== "detached" && deps.exitWatch?.canWatch() ? deps.exitWatch.create() : undefined;
96
+ if (capture)
97
+ argv.push(...(0, pane_exit_1.tmuxExitWatchArgs)(argv[2], capture));
98
+ const startedAt = deps.now?.() ?? Date.now();
93
99
  const result = deps.run(multiplexer, argv, { ...deps.env, ...program.env });
100
+ const report = capture ? deps.exitWatch.read(capture) : undefined;
101
+ if (capture)
102
+ deps.exitWatch.remove(capture);
94
103
  // Falling back rather than failing: the multiplexer is an enhancement, and refusing to start
95
104
  // somebody's agent because of one would be the tail wagging the dog.
96
105
  if (result.error)
97
106
  return runHere(program, deps);
98
- return result.status ?? 0;
107
+ if (!report)
108
+ return result.status ?? 0;
109
+ const elapsed = (deps.now?.() ?? Date.now()) - startedAt;
110
+ for (const line of (0, pane_exit_1.exitNotice)(path.basename(program.binary), report, elapsed, deps.exitWatch.notice))
111
+ deps.say(line);
112
+ return report.status;
99
113
  }
100
114
  /** Run the agent in this terminal, as it would run without BayChat. On Windows an npm-installed
101
115
  * agent is a `.cmd` shim, which Node will not spawn directly (EINVAL): `spawnPlanFor` starts
@@ -247,6 +261,11 @@ function realLaunchDeps() {
247
261
  return !probe.error && probe.status === 0;
248
262
  },
249
263
  tmuxHasSession: (name) => (0, child_process_1.spawnSync)("tmux", ["has-session", "-t", `=${name}`], { stdio: "ignore" }).status === 0,
264
+ exitWatch: (0, pane_exit_1.realExitWatch)(() => {
265
+ const probe = (0, child_process_1.spawnSync)("tmux", ["-V"], { encoding: "utf8" });
266
+ return probe.error || probe.status !== 0 ? undefined : String(probe.stdout ?? "");
267
+ }),
268
+ now: () => Date.now(),
250
269
  installer: () => tmuxInstallerFor(process.platform, (cmd) => onPath(cmd, process.env), process.getuid?.() === 0),
251
270
  ask: askLine,
252
271
  say: (line) => console.error(line),