baychat 0.49.0 → 0.51.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.49.0",
3
+ "version": "0.51.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": {
package/README.md CHANGED
@@ -177,7 +177,17 @@ you picked could be ignored). `baychat start polish` names the new session `poli
177
177
  when that is taken); with no name it is `<agent>-<pid>`. `baychat attach` lists the BayChat
178
178
  sessions open on this computer — name, agent, how long running — and attaches to the one you pick
179
179
  (`baychat attach polish` goes straight there). Only sessions BayChat started are listed, never
180
- your own tmux or screen sessions.
180
+ your own tmux or screen sessions — with one addition: a session can be found by its **BayChat name**
181
+ (`baychat attach vps_baychat_claude`) in any tmux, your own "main" included, once BayChat has proven
182
+ that pane runs that very session: it registered with this computer's relay from inside that pane,
183
+ the tmux server is yours, the pane is alive and runs the agent, and the process that registered is
184
+ in its foreground. Anything less is refused with the reason; nothing is guessed from a tmux name.
185
+
186
+ **`baychat claude --resume <BayChat name>`** reopens that session's last Claude conversation, in
187
+ its own folder — for after a crash. The channel notes which conversation each session runs
188
+ (`~/.baychat/resume-names.json`: ids, folders and times, nothing else; 10 per name, 30 days).
189
+ `--resume` alone, a Claude session id, or a word that is no BayChat name here go to Claude as they
190
+ are; `baychat claude -- --resume <word>` searches Claude's own list even for a word that is a name.
181
191
 
182
192
  To keep the system Node at 20 for other projects, run only `baychat` on Node 22 (Linux/WSL with
183
193
  systemd; details in [`CLAUDE_CODE_CHANNEL.md`](../../docs/features/CLAUDE_CODE_CHANNEL.md)):
@@ -460,6 +470,7 @@ one where remembering to re-arm falls to the agent.
460
470
  | `baychat relay stop` | Stop the relay and disable it at boot |
461
471
  | `baychat relay log <session> [-f]` | What a Codex session the relay runs did — commands, file changes, answers, approval cards. `-f` keeps following it (works on Windows too) |
462
472
  | `baychat claude [args…]` | Start Claude Code in this terminal with the BayChat channel on (see [No Monitor deadline with the channel](#coding-sessions-one-short-command)). Every argument is passed to Claude Code, `--help` included |
473
+ | `baychat claude --resume <BayChat name>` | Reopen that session's last Claude conversation in its folder. A session id or an unknown word goes to Claude unchanged; `baychat claude -- …` skips the lookup |
463
474
  | `baychat doctor [--json]` | **Run this when something does not work.** Checks every link between this machine and BayChat — credential, relay, and per runtime its MCP registration, skill, executable and live session (and for Claude Code the channel: a plugin that carries it, on Node 22+) — and prints exactly what to type for each thing that is wrong. Exit 0 clear, 1 broken, 2 messages nothing answered. `--json` for pasting into a support thread (see [When something does not work](#when-something-does-not-work)) |
464
475
  | `baychat relay attach --session <name> [--runtime claude\|codex\|cursor\|hermes] [--resume-id <id>] [--conversation <id>] [--timeout <sec>]` | Register this session with the relay and block until it is woken (exit 0) or the wait lapses (exit 2) |
465
476
  | `baychat mcp` | Run a local **stdio MCP server** so MCP-aware clients (Claude Desktop, Claude Code, Cursor) get BayChat as native tools (see below) |
@@ -927,7 +938,7 @@ instruction):
927
938
  | `create_note` | Write a note for the project or the chat; it lands on the shelf (people pin) |
928
939
  | `update_note` | Edit a note from the version you read; if someone saved since, nothing is overwritten and you get theirs to merge |
929
940
  | `list_board_cards` | The to-dos on the boards of the chat's project, by column, with the board's table fields and each to-do's values; `mine` marks the ones you may move or edit |
930
- | `add_board_card` | Add a to-do: yours by default (claim the work you are doing); one for a person or nobody is only a suggestion until a person accepts it |
941
+ | `add_board_card` | Add a to-do: yours by default (claim the work you are doing); one for a person or nobody is only a suggestion until a person accepts it. On a workflow board, `stage` names a stage instead of a column (a person starts it) |
931
942
  | `move_board_card` | Move one of your to-dos to another column (Doing, Done, Blocked) |
932
943
  | `update_board_card` | Edit the title, notes, dates or table values of one of your to-dos (money in integer cents) |
933
944
  | `stage_done` | Say your part of a workflow stage's to-do is done, in one line; a person approves it or asks for a rewrite |
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.realProofDeps = void 0;
37
+ exports.loadRegisteredSessions = loadRegisteredSessions;
38
+ exports.proveNamedPane = proveNamedPane;
39
+ exports.namedAttachSteps = namedAttachSteps;
40
+ const child_process_1 = require("child_process");
41
+ const fs = __importStar(require("fs"));
42
+ const path = __importStar(require("path"));
43
+ const config_1 = require("./config");
44
+ const claude_link_1 = require("./channel/claude-link");
45
+ const transcript_1 = require("./denied/transcript");
46
+ const resume_names_1 = require("./resume-names");
47
+ const bay_relays_1 = require("./relay/bay-relays");
48
+ const terminal_pane_1 = require("./relay/terminal-pane");
49
+ /** Every session this computer's relays registered: the default Bay's, then each other Bay's own relay. */
50
+ function loadRegisteredSessions(readFile = (f) => fs.readFileSync(f, "utf8")) {
51
+ const base = (0, config_1.configDir)();
52
+ const bays = (0, config_1.loadBayLogins)();
53
+ const sources = [];
54
+ const defaultBay = bays.find((b) => b.isDefault) ?? bays[0]; // the same Bay resume-names.ts `bayIdOf` calls the default
55
+ sources.push({ bay: bays.length > 1 ? (defaultBay?.bayName ?? "") : "", bayId: defaultBay?.bayId ?? "", file: path.join(base, "relay-sessions.json") });
56
+ for (const b of bays)
57
+ if (b !== defaultBay)
58
+ sources.push({ bay: b.bayName, bayId: b.bayId, file: path.join((0, bay_relays_1.bayRelayScope)(b.bayId, base, "").configDir, "relay-sessions.json") });
59
+ const out = [];
60
+ for (const { bay, bayId, file } of sources) {
61
+ let raw;
62
+ try {
63
+ raw = JSON.parse(readFile(file));
64
+ }
65
+ catch {
66
+ continue; // no relay for that Bay yet, or nothing registered
67
+ }
68
+ if (!raw || typeof raw !== "object")
69
+ continue;
70
+ for (const [name, v] of Object.entries(raw)) {
71
+ if (!v || typeof v !== "object" || typeof v.runtime !== "string")
72
+ continue;
73
+ out.push({ bay, bayId, name, runtime: v.runtime, ...(v.pane ? { pane: v.pane } : {}), ...(typeof v.ownerPid === "number" ? { ownerPid: v.ownerPid } : {}), ...(typeof v.cwd === "string" ? { cwd: v.cwd } : {}) });
74
+ }
75
+ }
76
+ return out;
77
+ }
78
+ /** Prove that `session`'s registered pane runs it NOW. */
79
+ function proveNamedPane(session, deps, platform = process.platform) {
80
+ const pane = session.pane;
81
+ const where = session.cwd ? ` It runs in ${session.cwd}.` : "";
82
+ if (!pane) {
83
+ const windows = platform === "win32" ? " Attaching needs tmux: on Windows, run your agent inside WSL." : "";
84
+ return { ok: false, reason: `"${session.name}" is not in tmux or screen, so there is no terminal to attach to.${where}${windows}` };
85
+ }
86
+ if (pane.kind === "zellij")
87
+ return { ok: false, reason: `"${session.name}" runs in zellij, which cannot be attached from outside: switch to it in zellij.${where}` };
88
+ if (pane.kind === "tmux") {
89
+ const own = deps.ownSocket(pane.socket);
90
+ if (!own.ok)
91
+ return { ok: false, reason: `"${session.name}" is not attached: ${own.reason}` };
92
+ }
93
+ const live = deps.verify(pane, session.runtime, session.ownerPid);
94
+ if (!live.ok)
95
+ return { ok: false, reason: `"${session.name}" is registered here, but not attached: ${live.reason}` };
96
+ if (pane.kind === "screen")
97
+ return { ok: true, session, pane }; // verifyPane proved its own process (ownerPid) is alive
98
+ const tty = deps.paneTty(pane);
99
+ const front = tty ? deps.foregroundPids(tty) : [];
100
+ const latest = deps.latestConversation(session.name, session.bayId);
101
+ const tied = front.some((pid) => pid === session.ownerPid || deps.linkSession(pid) === session.name || (!!latest && deps.conversationOf(pid) === latest));
102
+ if (!tied) {
103
+ return { ok: false, reason: `"${session.name}" is registered here, but its pane cannot be proven to run that very session now (the process that registered is not in it), so it is not attached.` };
104
+ }
105
+ return { ok: true, session, pane };
106
+ }
107
+ /** The commands that bring this terminal to the proven pane: focus it in its session, then attach or switch. */
108
+ function namedAttachSteps(pane, currentTmux) {
109
+ if (pane.kind === "screen")
110
+ return [{ file: "screen", args: ["-r", pane.session, "-p", pane.window] }];
111
+ const sameServer = !!currentTmux && currentTmux.split(",")[0] === pane.socket;
112
+ return [
113
+ { file: "tmux", args: ["-S", pane.socket, "select-window", "-t", pane.pane] },
114
+ { file: "tmux", args: ["-S", pane.socket, "select-pane", "-t", pane.pane] },
115
+ sameServer
116
+ ? { file: "tmux", args: ["-S", pane.socket, "switch-client", "-t", pane.pane] }
117
+ : // Inside ANOTHER tmux server, tmux refuses to nest unless $TMUX is cleared for the attach.
118
+ { file: "tmux", args: ["-S", pane.socket, "attach", "-t", pane.pane], ...(currentTmux ? { env: { TMUX: "" } } : {}) },
119
+ ];
120
+ }
121
+ const run = (file, args) => (0, child_process_1.execFileSync)(file, args, { encoding: "utf8", timeout: 5_000, stdio: ["ignore", "pipe", "ignore"] });
122
+ /** The real checks, from tmux and ps. */
123
+ exports.realProofDeps = {
124
+ ownSocket: terminal_pane_1.socketIsOurs,
125
+ verify: (pane, runtime, ownerPid) => (0, terminal_pane_1.verifyPane)(pane, runtime, run, ownerPid, terminal_pane_1.socketIsOurs),
126
+ paneTty: (pane) => {
127
+ try {
128
+ return run("tmux", ["-S", pane.socket, "display-message", "-p", "-t", pane.pane, "#{pane_tty}"]).trim() || undefined;
129
+ }
130
+ catch {
131
+ return undefined;
132
+ }
133
+ },
134
+ foregroundPids: (tty) => {
135
+ try {
136
+ const bare = (t) => t.replace(/^\/dev\//, "");
137
+ return run("ps", ["-A", "-o", "pid=,pgid=,tpgid=,tty="])
138
+ .split("\n")
139
+ .map((l) => l.trim().split(/\s+/))
140
+ .filter(([pid, pgid, tpgid, t]) => pid && t && bare(t) === bare(tty) && pgid === tpgid && Number(pgid) > 0)
141
+ .map(([pid]) => Number(pid));
142
+ }
143
+ catch {
144
+ return [];
145
+ }
146
+ },
147
+ linkSession: (pid) => (0, claude_link_1.readClaudeLink)(pid)?.session,
148
+ conversationOf: (pid) => (0, resume_names_1.claudeConversationOf)((0, transcript_1.claudeConfigDir)(), pid)?.sessionId,
149
+ latestConversation: (name, bayId) => (0, resume_names_1.resumeCandidates)(name, { bay: bayId })[0]?.sessionId,
150
+ };
@@ -42,6 +42,7 @@ const child_process_1 = require("child_process");
42
42
  const fs = __importStar(require("fs"));
43
43
  const multiplexer_launch_1 = require("./multiplexer-launch");
44
44
  const started_1 = require("./relay/launcher/started");
45
+ const attach_by_name_1 = require("./attach-by-name");
45
46
  /**
46
47
  * `baychat attach [name]` — back into a BayChat session already open on this computer.
47
48
  *
@@ -61,6 +62,9 @@ const started_1 = require("./relay/launcher/started");
61
62
  * - a session started from the app: the relay launcher's own record (`launch/started.json`).
62
63
  * The variable is read from the agent process's environment (Linux `/proc`, macOS `ps -E`) — on
63
64
  * the pane's process or its child, because a pane may run a shell that started the agent.
65
+ *
66
+ * And by BayChat NAME (17 Nov): a session the relay registered, in any tmux, once its pane is proven to
67
+ * run that very session now (attach-by-name.ts). Still never a guess from a tmux name.
64
68
  */
65
69
  /** Set on the agent by `baychat start`: which agent it is, for `attach`'s list (and screen's proof). */
66
70
  exports.SESSION_AGENT_VAR = "BAYCHAT_SESSION_AGENT";
@@ -128,12 +132,34 @@ function age(seconds) {
128
132
  return `${Math.floor(hours / 24)} days`;
129
133
  }
130
134
  async function cmdAttachWith(args, deps) {
131
- const sessions = deps.sessions();
135
+ const registered = deps.named?.() ?? [];
136
+ const named = args.find((a) => !a.startsWith("-"));
137
+ // A BayChat session name first (attach-by-name.ts): what people type now; a tmux name keeps working after it.
138
+ const byName = named ? registered.filter((r) => r.session.name === named) : [];
139
+ if (byName.length > 0) {
140
+ const proven = byName.flatMap((r) => (r.proof.ok ? [toOpen(r.session, r.proof.pane, deps.currentTmux)] : []));
141
+ if (proven.length === 0) {
142
+ byName.forEach((r) => !r.proof.ok && deps.say(r.proof.reason));
143
+ return 1;
144
+ }
145
+ if (proven.length === 1)
146
+ return attach(proven[0], deps);
147
+ if (!deps.atTerminal) {
148
+ // The same name in more than one Bay, and no terminal to choose in: list them, attach nothing.
149
+ listOnly(proven, deps);
150
+ return 1;
151
+ }
152
+ return pickAndAttach(proven, deps);
153
+ }
154
+ const known = deps.sessions();
155
+ const listed = new Set(known.map((s) => s.name));
156
+ // Proven BayChat sessions in a tmux BayChat did not start (a person's own "main") join the list by their name.
157
+ const extra = registered.flatMap((r) => (r.proof.ok && !(r.proof.pane.kind === "tmux" && r.proof.pane.session && listed.has(r.proof.pane.session)) ? [toOpen(r.session, r.proof.pane, deps.currentTmux)] : []));
158
+ const sessions = [...known, ...extra];
132
159
  if (sessions.length === 0) {
133
160
  deps.say("No BayChat sessions are open on this computer. Start one with `baychat start`.");
134
161
  return 1;
135
162
  }
136
- const named = args.find((a) => !a.startsWith("-"));
137
163
  if (named) {
138
164
  const session = sessions.find((s) => s.name === named || s.name.endsWith(`.${named}`));
139
165
  if (!session) {
@@ -142,17 +168,24 @@ async function cmdAttachWith(args, deps) {
142
168
  }
143
169
  return attach(session, deps);
144
170
  }
145
- const width = Math.max(...sessions.map((s) => s.name.length));
146
- const lines = sessions.map((s, i) => ` ${i + 1}. ${s.name.padEnd(width)} ${s.agent.padEnd(8)} ${age(s.runningSeconds)}`.trimEnd());
147
- if (!deps.atTerminal) {
148
- deps.say("BayChat sessions open on this computer:");
149
- lines.forEach((line) => deps.say(line));
150
- return 0;
151
- }
171
+ if (!deps.atTerminal)
172
+ return listOnly(sessions, deps);
152
173
  if (sessions.length === 1)
153
174
  return attach(sessions[0], deps);
175
+ return pickAndAttach(sessions, deps);
176
+ }
177
+ function listLines(sessions) {
178
+ const width = Math.max(...sessions.map((s) => s.name.length));
179
+ return sessions.map((s, i) => ` ${i + 1}. ${s.name.padEnd(width)} ${s.agent.padEnd(8)} ${age(s.runningSeconds)}`.trimEnd());
180
+ }
181
+ function listOnly(sessions, deps) {
154
182
  deps.say("BayChat sessions open on this computer:");
155
- lines.forEach((line) => deps.say(line));
183
+ listLines(sessions).forEach((line) => deps.say(line));
184
+ return 0;
185
+ }
186
+ async function pickAndAttach(sessions, deps) {
187
+ deps.say("BayChat sessions open on this computer:");
188
+ listLines(sessions).forEach((line) => deps.say(line));
156
189
  const answer = (await deps.ask(`Attach to which one? 1-${sessions.length}: `)).trim();
157
190
  const picked = sessions[Number(answer) - 1] ?? sessions.find((s) => s.name === answer);
158
191
  if (!picked) {
@@ -161,7 +194,27 @@ async function cmdAttachWith(args, deps) {
161
194
  }
162
195
  return attach(picked, deps);
163
196
  }
197
+ /** A proven registered session as a list entry; the Bay is named when it is not the default one. */
198
+ function toOpen(session, pane, currentTmux) {
199
+ return {
200
+ multiplexer: pane.kind,
201
+ name: session.name,
202
+ agent: session.bay ? `${session.runtime} · ${session.bay}` : session.runtime,
203
+ steps: (0, attach_by_name_1.namedAttachSteps)(pane, currentTmux),
204
+ };
205
+ }
164
206
  function attach(session, deps) {
207
+ if (session.steps) {
208
+ let last = { status: 0 };
209
+ for (const step of session.steps) {
210
+ last = (deps.runStep ?? ((st) => deps.run(st.file, st.args)))(step);
211
+ if (last.error) {
212
+ deps.say(`Could not attach to ${session.name}: ${last.error.message}`);
213
+ return 1;
214
+ }
215
+ }
216
+ return last.status ?? 0;
217
+ }
165
218
  const [file, argv] = attachArgv(session, deps.insideTmux);
166
219
  const result = deps.run(file, argv);
167
220
  if (result.error) {
@@ -181,6 +234,8 @@ function cmdAttach(args) {
181
234
  elapsedSecondsOf: processElapsed,
182
235
  now: Date.now(),
183
236
  }),
237
+ named: () => (0, attach_by_name_1.loadRegisteredSessions)().map((session) => ({ session, proof: (0, attach_by_name_1.proveNamedPane)(session, attach_by_name_1.realProofDeps) })),
238
+ currentTmux: process.env.TMUX || undefined,
184
239
  atTerminal: !!process.stdin.isTTY && !!process.stdout.isTTY,
185
240
  insideTmux: !!process.env.TMUX,
186
241
  ask: multiplexer_launch_1.askLine,
@@ -188,6 +243,10 @@ function cmdAttach(args) {
188
243
  const r = (0, child_process_1.spawnSync)(file, args, { stdio: "inherit" });
189
244
  return { status: r.status, ...(r.error ? { error: r.error } : {}) };
190
245
  },
246
+ runStep: (step) => {
247
+ const r = (0, child_process_1.spawnSync)(step.file, step.args, { stdio: "inherit", ...(step.env ? { env: { ...process.env, ...step.env } } : {}) });
248
+ return { status: r.status, ...(r.error ? { error: r.error } : {}) };
249
+ },
191
250
  say: (line) => console.log(line),
192
251
  });
193
252
  }
package/dist/bays.js CHANGED
@@ -109,6 +109,9 @@ function findBayLogin(bays, query) {
109
109
  const tiers = [
110
110
  (b) => b.bayId === q,
111
111
  (b) => b.bayName.trim().toLowerCase() === lower,
112
+ // The default Bay's own MCP entry is plain `baychat` (every other Bay's is `baychat-<slug>`), so that name is
113
+ // the default login — after a Bay's real name, so a Bay that is called "baychat" still wins (vps, 18 Nov).
114
+ (b) => lower === exports.DEFAULT_MCP_ENTRY && b.isDefault,
112
115
  (b) => bayEntryName(b, bays) === lower || bayEntryName(b, bays) === `${exports.DEFAULT_MCP_ENTRY}-${lower}`,
113
116
  (b) => baySlug(b.bayName) === baySlug(q),
114
117
  ];
@@ -33,12 +33,14 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.CONVERSATION_REFRESH_MS = void 0;
36
37
  exports.claudeSessionsDir = claudeSessionsDir;
37
38
  exports.claudeLinkPath = claudeLinkPath;
38
39
  exports.writeClaudeLink = writeClaudeLink;
39
40
  exports.removeClaudeLink = removeClaudeLink;
40
41
  exports.readClaudeLink = readClaudeLink;
41
42
  exports.pidAlive = pidAlive;
43
+ exports.recordConversation = recordConversation;
42
44
  exports.realClaudeLink = realClaudeLink;
43
45
  /**
44
46
  * Which BayChat session a running Claude Code is — written by the channel, read by the hook.
@@ -57,6 +59,8 @@ exports.realClaudeLink = realClaudeLink;
57
59
  const fs = __importStar(require("node:fs"));
58
60
  const path = __importStar(require("node:path"));
59
61
  const config_1 = require("../config");
62
+ const transcript_1 = require("../denied/transcript");
63
+ const resume_names_1 = require("../resume-names");
60
64
  function claudeSessionsDir() {
61
65
  return path.join((0, config_1.configDir)(), "claude-sessions");
62
66
  }
@@ -126,8 +130,33 @@ function pidAlive(pid) {
126
130
  return err.code === "EPERM";
127
131
  }
128
132
  }
133
+ /**
134
+ * Which Claude conversation `session` runs, for `baychat claude --resume <name>` (resume-names.ts): read from
135
+ * Claude Code's own file for `pid`. Never throws — a resume record is never worth a channel failure.
136
+ */
137
+ function recordConversation(session, bay, pid, log, deps = {}) {
138
+ try {
139
+ const conversation = (0, resume_names_1.claudeConversationOf)((0, transcript_1.claudeConfigDir)(deps.claudeDir), pid);
140
+ if (conversation)
141
+ (0, resume_names_1.recordResume)(session, { ...conversation, bay }, { warn: log, ...(deps.file ? { file: deps.file } : {}) });
142
+ }
143
+ catch (err) {
144
+ log(`could not record ${session}'s conversation for resume: ${err instanceof Error ? err.message : String(err)}`);
145
+ }
146
+ }
147
+ /** How often a listening session's conversation is read again: `/clear` gives Claude Code a new id. */
148
+ exports.CONVERSATION_REFRESH_MS = 60_000;
129
149
  /** The real link: keyed by this process's parent — the Claude Code that started the channel server. */
130
150
  function realClaudeLink(log, pid = process.ppid) {
151
+ let current;
152
+ let refresh;
153
+ /** Note `session`'s conversation now, and again every minute while it is the one listening. */
154
+ const follow = (session, bay) => {
155
+ current = { session, bay: (0, resume_names_1.bayIdOf)(bay) };
156
+ recordConversation(current.session, current.bay, pid, log);
157
+ refresh ??= setInterval(() => current && recordConversation(current.session, current.bay, pid, log), exports.CONVERSATION_REFRESH_MS);
158
+ refresh.unref?.();
159
+ };
131
160
  return {
132
161
  write: (session, feed) => {
133
162
  try {
@@ -137,8 +166,13 @@ function realClaudeLink(log, pid = process.ppid) {
137
166
  // Approvals then stay in the terminal for this session: the hook finds no link and says nothing.
138
167
  log(`could not record session ${session} for approvals: ${err instanceof Error ? err.message : String(err)}`);
139
168
  }
169
+ follow(session, undefined); // write() is the default Bay's (server.ts)
140
170
  },
141
- remove: (session) => {
171
+ remove: (session, listeningAs, bay) => {
172
+ if (session === undefined || session === current?.session)
173
+ current = undefined;
174
+ if (listeningAs)
175
+ follow(listeningAs, bay);
142
176
  try {
143
177
  removeClaudeLink(pid, session);
144
178
  }
@@ -0,0 +1,94 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.planResume = planResume;
4
+ exports.resumeWith = resumeWith;
5
+ exports.resolveClaudeArgs = resolveClaudeArgs;
6
+ exports.resumeFlagIndex = resumeFlagIndex;
7
+ exports.pickLines = pickLines;
8
+ exports.seenAgo = seenAgo;
9
+ const resume_names_1 = require("../resume-names");
10
+ const RESUME_FLAGS = new Set(["--resume", "-r"]);
11
+ function planResume(args, candidatesOf = (n) => (0, resume_names_1.resumeCandidates)(n)) {
12
+ if (args[0] === "--")
13
+ return { kind: "as-is", args: args.slice(1) };
14
+ for (let i = 0; i < args.length; i++) {
15
+ const arg = args[i];
16
+ const eq = arg.startsWith("--resume=") ? arg.slice("--resume=".length) : undefined;
17
+ if (!RESUME_FLAGS.has(arg) && eq === undefined)
18
+ continue;
19
+ const value = eq ?? args[i + 1];
20
+ if (value === undefined || value === "" || value.startsWith("-") || (0, resume_names_1.isClaudeSessionId)(value))
21
+ break;
22
+ const candidates = candidatesOf(value);
23
+ if (candidates.length === 0)
24
+ break;
25
+ if (candidates.length > 1)
26
+ return { kind: "pick", name: value, candidates };
27
+ return resumeWith(args, i, eq !== undefined, value, candidates[0]);
28
+ }
29
+ return { kind: "as-is", args: [...args] };
30
+ }
31
+ /** The plan for one picked conversation of `name`. */
32
+ function resumeWith(args, at, joined, name, entry) {
33
+ const out = [...args];
34
+ if (joined)
35
+ out.splice(at, 1, "--resume", entry.sessionId);
36
+ else
37
+ out.splice(at, 2, "--resume", entry.sessionId);
38
+ return {
39
+ kind: "resume",
40
+ args: out,
41
+ cwd: entry.cwd,
42
+ line: `BayChat: resuming the session "${name}" (its last Claude conversation, in ${entry.cwd}, seen ${seenAgo(entry.at)}). ` +
43
+ `To search Claude's own list for "${name}" instead: baychat claude -- --resume ${name}`,
44
+ };
45
+ }
46
+ /**
47
+ * What `baychat claude` runs: the arguments for Claude Code and the folder to start in, or an exit code when
48
+ * nothing should start (an unanswered pick). Exit 1 for "several and no terminal to choose", or a bad pick.
49
+ */
50
+ async function resolveClaudeArgs(args, deps) {
51
+ const plan = planResume(args, deps.candidatesOf);
52
+ if (plan.kind === "as-is")
53
+ return { args: plan.args };
54
+ if (plan.kind === "resume") {
55
+ deps.say(plan.line);
56
+ return { args: plan.args, cwd: plan.cwd };
57
+ }
58
+ deps.say(`BayChat: the session "${plan.name}" ran more than one Claude conversation on this computer:`);
59
+ pickLines(plan.candidates, deps.bayName).forEach((line) => deps.say(line));
60
+ if (!deps.atTerminal) {
61
+ deps.say(`Run it in a terminal to choose one, or pass its id: baychat claude --resume <id>. To search Claude's own list instead: baychat claude -- --resume ${plan.name}`);
62
+ return { exit: 1 };
63
+ }
64
+ const answer = (await deps.ask(`Resume which one? 1-${plan.candidates.length}: `)).trim();
65
+ const picked = plan.candidates[Number(answer) - 1];
66
+ if (!picked) {
67
+ deps.say("Not one of the options.");
68
+ return { exit: 1 };
69
+ }
70
+ const at = resumeFlagIndex(args);
71
+ const chosen = resumeWith(args, at, args[at].startsWith("--resume="), plan.name, picked);
72
+ deps.say(chosen.line);
73
+ return { args: chosen.args, cwd: chosen.cwd };
74
+ }
75
+ /** Where `--resume` (or `--resume=`) sits in these arguments; -1 when absent. */
76
+ function resumeFlagIndex(args) {
77
+ return args.findIndex((a) => RESUME_FLAGS.has(a) || a.startsWith("--resume="));
78
+ }
79
+ /** One line per conversation for the numbered pick: folder and when, and the Bay when they are in more than one. */
80
+ function pickLines(candidates, bayName = (id) => (0, resume_names_1.bayNameOf)(id)) {
81
+ const severalBays = new Set(candidates.map((c) => c.bay)).size > 1;
82
+ return candidates.map((c, i) => ` ${i + 1}. ${c.cwd}${severalBays ? ` · ${bayName(c.bay) || "another Bay"}` : ""} (seen ${seenAgo(c.at)})`);
83
+ }
84
+ function seenAgo(at, now = Date.now()) {
85
+ const minutes = Math.max(0, Math.floor((now - Date.parse(at)) / 60_000));
86
+ if (minutes < 2)
87
+ return "just now";
88
+ if (minutes < 60)
89
+ return `${minutes} min ago`;
90
+ const hours = Math.floor(minutes / 60);
91
+ if (hours < 48)
92
+ return `${hours} h ago`;
93
+ return `${Math.floor(hours / 24)} days ago`;
94
+ }
@@ -57,6 +57,7 @@ const fs = __importStar(require("node:fs"));
57
57
  const os = __importStar(require("node:os"));
58
58
  const path = __importStar(require("node:path"));
59
59
  const multiplexer_launch_1 = require("../multiplexer-launch");
60
+ const claude_resume_1 = require("./claude-resume");
60
61
  const runtime_binary_1 = require("../runtime-binary");
61
62
  const detect_1 = require("./detect");
62
63
  const plugin_1 = require("./plugin");
@@ -128,7 +129,25 @@ function probeVersion(claudePath) {
128
129
  * (multiplexer-launch.ts) — in a NEW multiplexer session each time (`claude-<pid>`), never one
129
130
  * another terminal is already in. Anything else (`-p`, `--bg`, `mcp list`, …) runs right here.
130
131
  */
131
- async function cmdClaude(args) {
132
+ async function cmdClaude(given) {
133
+ // `--resume <BayChat session name>` reopens that session's last conversation in its folder (claude-resume.ts).
134
+ const resolved = await (0, claude_resume_1.resolveClaudeArgs)(given, {
135
+ atTerminal: !!process.stdin.isTTY && !!process.stdout.isTTY,
136
+ ask: multiplexer_launch_1.askLine,
137
+ say: (line) => console.error(line),
138
+ });
139
+ if ("exit" in resolved)
140
+ return resolved.exit;
141
+ const args = resolved.args;
142
+ if (resolved.cwd) {
143
+ try {
144
+ process.chdir(resolved.cwd);
145
+ }
146
+ catch (err) {
147
+ console.error(`BayChat: could not open ${resolved.cwd} (${err instanceof Error ? err.message : String(err)}), so that conversation cannot be resumed here.`);
148
+ return 1;
149
+ }
150
+ }
132
151
  const binary = (0, runtime_binary_1.resolveRuntimeBinary)("claude", (0, runtime_binary_1.currentBinaryEnv)());
133
152
  if (!binary.ok) {
134
153
  console.error(`Could not start Claude Code: ${binary.reason}`);
@@ -385,7 +385,7 @@ class ChannelService {
385
385
  if (bay === undefined)
386
386
  this.deps.claudeLink?.write(session, "open");
387
387
  else
388
- this.deps.claudeLink?.remove(undefined);
388
+ this.deps.claudeLink?.remove(undefined, session, bay); // …and notes its conversation all the same (resume-names.ts)
389
389
  return toolResult("active", `Active: session "${session}"${bayName ? ` (${bayName})` : ""} now hears the Bay through the channel. New messages ` +
390
390
  `arrive here as <channel event="messages"> events, with no deadline and no re-arming. Do NOT open a ` +
391
391
  `Monitor or call listen_messages — either would replace this feed. Summary first: the join's Catch-up is the ` +
package/dist/cli-help.js CHANGED
@@ -33,8 +33,12 @@ Usage:
33
33
  with a name for it; never returns to an old one
34
34
  baychat attach [name] Go back to a BayChat session open on this computer:
35
35
  lists them (name, agent, how long running) and
36
- attaches to the one you pick
37
- baychat update Bring this machine onto the current version —
36
+ attaches to the one you pick. The name is a tmux
37
+ session BayChat started, or a BayChat session name
38
+ (found in any tmux, once its pane is proven to run
39
+ it). Exit 0: attached or listed; 1: not found,
40
+ not proven, or nothing open
41
+ baychat update Bring this machine onto the current version —
38
42
  the package, every connected client's config, and
39
43
  the relay daemon (which otherwise keeps running
40
44
  old code). The relay does this by itself about
@@ -68,6 +72,12 @@ Usage:
68
72
  channel on (no Monitor deadline). Every argument is
69
73
  Claude Code's own, so \`baychat claude --help\` is
70
74
  Claude Code's help
75
+ baychat claude --resume <BayChat name>
76
+ Reopen that session's last Claude conversation in
77
+ its folder (after a crash). A session id or an
78
+ unknown word goes to Claude unchanged;
79
+ \`baychat claude -- …\` skips the lookup. Exit 1:
80
+ several to choose from and no terminal, or no pick
71
81
  baychat channel The Claude Code channel server. Claude Code starts it
72
82
  (\`baychat connect claude\` sets that up); not for
73
83
  running by hand. Needs Node 22 or newer
@@ -17,7 +17,12 @@
17
17
  // takes no arguments must omit the key entirely.
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
19
  exports.registerToolDefs = registerToolDefs;
20
- const tool_defs_1 = require("./tool-defs");
20
+ const tool_hints_1 = require("./tool-hints");
21
+ /** A definition's annotations (tool-hints.ts); a tool missing there is a build error in its test, never silently bare. */
22
+ function annotationsOf(def) {
23
+ const annotations = (0, tool_hints_1.toolAnnotations)(def.name, def.access, def.title);
24
+ return annotations ? { annotations } : {};
25
+ }
21
26
  /**
22
27
  * Register every def against its handler, failing loudly if one is missing.
23
28
  *
@@ -34,7 +39,7 @@ function registerToolDefs(server, defs, handlers) {
34
39
  description: def.description,
35
40
  ...(Object.keys(def.inputSchema).length ? { inputSchema: def.inputSchema } : {}),
36
41
  ...(def._meta ? { _meta: def._meta } : {}),
37
- annotations: (0, tool_defs_1.toolAnnotations)(def.access),
42
+ ...annotationsOf(def),
38
43
  }, async (args) => handler(args));
39
44
  }
40
45
  }