Agent Switchboard's line: records this Claude Code session and connects it to the other sessions on the switchboard

swb keeps track of every coding-agent session I start, in pi, Claude Code, or Codex, from its first turn until I archive it, across quits, crashes, and reboots, and gets me back into any of them in one keystroke. The sessions can message each other, across harnesses and projects.
Sessions run headless in a dedicated tmux server. swb opens a Deck: a roster of those sessions, showing which ones need me, beside the selected session's real, interactive pi, Claude Code, or Codex.
swb needs tmux 3.8 or newer and pi 1.2.0 or newer.
swb binary, for linux-x64 or darwin-arm64, from the latest release, or with mise: mise use -g github:thurstonsand/agent-switchboard
pi branch where an npm mirror lags. With pi-sessions, it needs pi-sessions 0.22.0 or later: pi install npm:@thurstonsand/pi-agent-switchboard
pi install git:github.com/thurstonsand/agent-switchboard@pi
swb open a Deck where the last one in this Project left off
swb -c, --continue open a Deck on this Project's most recent session, or a new one
swb new [--cwd DIR] [--harness pi|claude|codex] open a Deck on a new session
swb open ID open a Deck on a session
swb adopt ID|TRANSCRIPT track a pi, Claude Code, or Codex session run outside swb, then open it; quit it first
swb adopt --all track every session pi, Claude Code, and Codex ran outside swb, archived, and index them
swb ls [--json] list sessions with derived state
swb dirs [--json] list the directories n offers for a new session
swb archive ID archive a session
swb unarchive ID reopen an archived session
swb snooze ID one_hour|one_day|monday|next_message|off|TIME snooze a session; TIME is ISO 8601, local unless it has an offset
swb quit [--force] stop every session, Deck, and swb's clock; sessions stay open
swb wake ID start a dormant session in the background
swb models [--harness H] [QUERY] list every model and agent the harnesses offer
swb launch [--harness H] [--model M] [--effort E] [--agent A] [--cwd DIR] [--from ID] [--title T] start a new session in the background on a preset; naming none, the one nearest what --from runs, else the default; its goal on stdin
swb send --from ID --to ID [--request-response] [--cancel] message a session, waking it if dormant; the body on stdin
swb runs Claude Code (2.1.300 or later) and Codex CLI (0.149 or later) the way it runs pi: the real TUI, in swb's tmux server, on the roster. Each plugs in through a line that swb ships and loads itself, so there is nothing else to install: Claude Code gets a plugin with a mod, and Codex runs on a private app-server that swb starts with it. n's picker shows the preset a new session starts on, harness and model, on a card on the Stage; it opens on the default, and Tab drops the rest of the shortlist, a harness at a time, numbered for one key to pick (see Settings).
Every managed session's agent gets the same tools, whatever its harness:
session_reachable: every other open session, in any harness or project, live or dormant, with its Group if it's in onesession_search: every other session's conversation, open or archived, its subagents' included, searched by words, "phrases", and filters (harness:, project:, file:, after:, before:, archived:), best match first with the passages that matchedsession_ask: a question about another session's conversation, answered by a reader with its own context, run in the asker's own harness, so the transcript never fills the asker'ssession_send_message: a message to one of them, arriving mid-turn when it's working, or starting a turn when it's idle; a dormant one is woken firstsession_cancel: stops another session's turnsession_launch: starts a new session in any harness, whose first turn is the goal it's given, in the launcher's Group when both are in one Project; group names another, or null nonesession_schedule: a message for later, once (at: an ISO 8601 time or duration) or on a 5-field cron, to this session, another, or a new session launched when it fires, in a Group as session_launch picks it; snooze snoozes the recipient until thensession_schedules and session_unschedule: the schedules a session set or receives, and cancelling oneswb_update_session: archives, unarchives, snoozes, or unsnoozes a session, moves it into a Group, or retitles it, any of them in one call. family archives everything it started too; a member mid-turn, blocked, cut off, or errored refuses the whole call by name, changing nothing, until force archives it anyway and cancels the turn. A new title becomes the harness's own name: pi and Codex take it at once, a dormant one as it starts, and Claude Code with its next prompt. Renaming the session in its harness later winsswb_show_session: takes you to another session, moving the Deck you're watching this one in onto it and starting it if it's dormant, as clicking its row would; view (agent, editor, or split) opens it in a given view instead of the one it was last left inMessages wait in swb's db until their session takes them, so one sent to a session that's starting, or whose sender has quit, still arrives. Claude Code takes a message at its next tool call, or as a new turn when idle; pi and Codex steer the running turn. Codex's own /archive archives the session in swb too.
swb's clock runs in its tmux server, which stays up after every Deck closes, so schedules fire with no Deck open, waking a dormant recipient. After a reboot it starts with the first swb; anything due meanwhile, or while the machine slept, fires then, and the message says when it was scheduled for and when it arrived. A recurring schedule that missed several runs fires once. Claude Code's own scheduler (CronCreate, /loop) is switched off in sessions swb runs, since it dies with its process. swb quit stops everything; sessions stay open and schedules wait for the next swb.
A snoozed session waits in the roster's Snoozed section, folded like Archived, each row saying when it wakes, ↘ for its next message. A timed snooze holds through any conversation; next_message ends with the next message or prompt. Blocked, cut off, or errored, it shows in its usual place anyway, and when its time runs out it comes back Unseen, so it can't fold into Inactive before you've looked.
An idle session nobody is viewing stops after reap_after, and an upgrade stops idle sessions; pi and Claude Code get their unsent prompt back on the next wake. Codex has no way for swb to read its prompt box, so a Codex session loses an unsent prompt when it stops.
Inside a managed pi, swb owns coordination between sessions and recall of them, session_search and session_ask among them, so pi-sessions keeps only its subagent tools (subagent_launch, subagent_send, and the rest). Subagents still run in their parent's tmux and never become sessions. A pi launched by another session records its parent where pi-sessions sees it, so the lineage survives the session leaving swb. The roster nests a session under the one that started it, and marks one whose parent sits elsewhere ↳, or ⌁ when an Operator started it.
In the roster, j/k move, Enter focuses the session (waking it if it's dormant), w wakes it in the background (either one continues a turn its process died in), x stops its agent and keeps it open, n picks a directory for a new session, starting from the highlighted one, N adds a directory and starts one there, a archives or unarchives (on a session that started others still open, it asks first whether they go too), s snoozes for an hour, a day, a week, or until its next message, or unsnoozes, p goes to the session that started this one, h/l fold and open the family under a session, m picks the session's Group from a list or names a new one (or renames one from its header), / filters, and q quits. Every pane names itself on its top edge, the one with the keyboard lit. M-a is the Deck's prefix from anywhere, and while it's down, the other panes show the key that reaches them: M-a h/j/k/l move to the pane that way, Tab returns to the pane you left, M-a J/M-a K stage the next or previous session from anywhere, as M-a j/k do in the roster, M-a e swaps the agent and the editor and focuses it, M-a v splits them, M-a s opens the directory's shell beside a wide agent or below a tall one, or in its place when neither leaves room (ctrl-d closes it), M-a z hides the roster, M-a S snoozes or unsnoozes, M-a n/M-a N and the other roster keys work after it too, M-a q closes the Deck, M-a ? lists the rest. ctrl-h/j/k/l move between panes; with nvim as the editor they walk its windows first and step off its edge into the Deck, and its line highlight shows only while it has the keyboard. Dragging a session onto a Group, or anywhere beneath one, moves it there. Hovering a session, or moving onto it with j/k, opens its Peek beside it: its full title, state, directory and branch, its last turn, and its keys as buttons, which act on that session wherever the cursor is. The Peek goes when the pointer leaves the roster and the Peek, or a key is typed outside the roster. A narrow Deck, with no Stage beside the roster, draws the Peek at the roster's right edge instead. Clicking a session focuses it, and the tabs under the roster (shell among them) and its legend are clickable; any control lights up under the pointer. While the Stage fills the Deck, ◂ at the top brings the roster back.
n's picker lists each repository with its worktrees beneath it, alongside plain directories: those under [dirs], every directory a session is in, and ones added with N. Typing filters it, best match first. M-a d, or the ✕ on the highlighted row, removes a directory from the list, and a repository's worktrees go with it; adding it again with N brings it back. A directory that no longer exists drops off on its own.
The Operators section sits atop the roster: sessions that coordinate the others rather than work in a Project. n on it opens the picker on ~/.config/agent-switchboard/operator, where Tab picks its preset; that folder's AGENTS.md, which swb keeps current, makes it the dispatcher. An Operator reads only that AGENTS.md, not the user-level one or any above it, and reaches the other sessions through swb's tools. Codex is the exception: it always reads ~/.codex/AGENTS.md. Its new sessions are always session_launches, in whichever harness suits the work, and its subagents are off, since the Deck can't see them. It can't start another Operator. Settings' Operators section holds your own instructions, which swb adds after its own in that AGENTS.md. To promote an existing pi session, /mv it into that folder.
, in the roster, or M-a , from anywhere, opens Settings across the whole Deck: every setting by section, with search (/) over names, descriptions, and the words you'd look for. A value is dim while it's the default and bright once you set it, and setting it back to the default takes it out of the file. Toggles and choices save at once; the rest edit in place and save on ⏎. Every key works by mouse too. Changes apply to every open Deck as soon as they're saved, whether from Settings or by hand.
Behind it is ${XDG_CONFIG_HOME:-~/.config}/agent-switchboard/config.toml, which Settings edits in place, so your comments stay, except the ones on a key it removes. A file swb can't read stops every new swb command with the line at fault; an open Deck keeps what it had, says so in red, and O opens the file at that line.
The Harnesses section holds the shortlist: the presets, each a harness, a model and effort or a Claude Code agent, and a note, that n's picker offers (it opens on the ★ default, and Tab drops the rest) and that agents choose from in session_launch. Until you edit it, swb makes one from each harness's own list, up to four each from Claude Code and Codex and two from pi; your first edit writes that list into the file, and r on it brings the automatic one back. swb models lists everything the harnesses offer.
<!-- settings:start (generated by scripts/settings-readme.ts) -->
wake_on_highlight = false # true starts a dormant session after the cursor rests 500 ms on its row
roster_width = 42 # columns, or a share of the Deck like "25%"; never more than half
shell_position = "auto" # "below" or "beside" fixes it, except where only the other fits; with room for neither, it replaces the agent
inactive_after = "72h" # open sessions idle this long, with all they started, move to Inactive
reap_after = "30m" # an idle live session nobody is viewing is stopped after this long
harnesses = ["pi", "claude", "codex"] # which harnesses new sessions may start in; all of them by default
warn_long_shortlist = true # Settings warns once the shortlist passes 10 entries
editor = "nvim" # defaults to $EDITOR
clipboard = "wl-copy" # defaults to wl-copy, else xclip, else pbcopy
[operator]
instructions = "Prefer Codex for anything in Rust." # after swb's own, in every Operator's AGENTS.md; up to 16,000 characters
[dirs]
scan = ["~/code"] # git checkouts and their worktrees beneath these; none by default
depth = 2 # how far beneath each to look, 1 to 10; a checkout is never entered
include = ["~/notes"] # always offered, git or not
exclude = ["dotfiles"] # like .gitignore: a bare name anywhere, a pattern with a slash under each scan root, or one ~/ path
sort = "name" # "recent" puts directories with the latest session activity first
[keys]
prefix = "M-a" # as tmux spells it
[[presets]] # the shortlist; without any, swb makes one from each harness's own
harness = "claude" # "pi", "claude", or "codex"
model = "opus"
effort = "high" # off, minimal, low, medium, high, xhigh, max, ultra, as the harness takes them; none for its default
use = "Hard design and review" # a line for agents choosing among them
default = true # what n opens on, and a launch's fallback; else the first
[[presets]]
harness = "pi"
provider = "openrouter" # pi's presets name their provider
model = "moonshotai/kimi-k3"
effort = "low"
[[presets]]
harness = "claude"
agent = "Explore" # Claude Code only: the whole session runs as this agent, on its model and effort
<!-- settings:end -->
See DEV.md. The design lives in docs/designs/01-agent-switchboard.md.
MIT
hooks/register.js 510 lines1// Agent Switchboard's Claude Code line, written by swb into its state directory and loaded with --plugin-dir.
2// It records this session's lifecycle, gives Claude the switchboard's coordination tools, and delivers messages from
3// other sessions: mid-turn as context on the next tool result, or as a new turn when idle.
4//
5// claude plugin validate only accepts `$` passed to top-level functions, so every call goes through one.
6import { READER_PROMPT, READER_TOOLS, TOOLS } from "./tools.js";
7
8async function registerReader($) {
9 await $.agent.register({
10 name: "reader",
11 description: "Answer a question about a switchboard session's conversation.",
12 prompt: READER_PROMPT,
13 tools: [...READER_TOOLS.map((tool) => `mcp__swb__${tool.name}`), "Read", "Grep", "Glob"],
14 model: "inherit",
15 });
16}
17
18// Readers session_ask started, by agentId, each with the session it reads: only they may read transcripts, and each
19// one's turn.complete ends its wait.
20const readers = new Map();
21
22/**
23 * Starts a reader and returns its final answer. $.tool.call refuses the Agent tool, and $.agent.spawn resolves once the
24 * reader starts. A hook's 10s budget stops only while a $ call is in flight, so the hook waits on a child that writes
25 * nothing: the reader's turn.complete ends it, and Esc kills it.
26 *
27 * HACK: the idle child, and the timer that stops a reader after Esc, stand in for an API the mods SDK lacks: a way to
28 * await a spawned agent's answer and stop it from the hook that spawned it. Replace both once Claude Code offers one,
29 * such as $.agent.wait, or lets $.tool.call run the Agent tool.
30 */
31async function ask($, e) {
32 const first = JSON.parse(await swb($, ["recall", "begin", e.session], JSON.stringify({ question: e.question })));
33 const { agentId, deny } = await $.agent.spawn({
34 subagentType: "swb:reader",
35 prompt: first.text,
36 description: "Read session conversation",
37 });
38 if (deny) throw new Error(deny);
39 if (!agentId) throw new Error("Claude did not start a reader");
40 const reader = { session: e.session, answer: undefined, wait: $.process.spawn({ argv: ["tail", "-f", "/dev/null"] }) };
41 readers.set(agentId, reader);
42 try {
43 for await (const _ of reader.wait);
44 } finally {
45 readers.delete(agentId);
46 // Esc leaves a spawned agent running, and denies a tool call from the aborted hook; a timer's isn't the hook's.
47 if (reader.answer === undefined) $.clock.after(0, () => stopReader($, agentId));
48 }
49 if (reader.answer === undefined) throw new Error("session_ask's reader stopped waiting");
50 return reader.answer;
51}
52
53/** A reader's tool, on the session it reads, with the arguments its schema names. */
54async function readerTool($, tool, e) {
55 const reader = readers.get(e.agentId);
56 if (!reader) return { deny: `${tool.name} is only available to session_ask's reader` };
57 const args = Object.fromEntries(Object.keys(tool.inputSchema.properties).flatMap((key) => (e[key] === undefined ? [] : [[key, e[key]]])));
58 try {
59 return { result: JSON.parse(await swb($, ["recall", tool.name.replace("recall_", ""), reader.session], JSON.stringify(args))).text };
60 } catch (error) {
61 return { deny: error.message };
62 }
63}
64
65async function stopReader($, agentId) {
66 try {
67 const stopped = await $.tool.call({ tool: "TaskStop", task_id: agentId });
68 if (stopped.deny || stopped.isError) throw new Error(stopped.deny ?? stopped.text);
69 } catch (error) {
70 $.ui.log(`swb: session_ask's reader didn't stop: ${error.message}`);
71 }
72}
73
74const line = {
75 managed: false,
76 started: false,
77 bin: "",
78 host: "",
79 session: "",
80 cwd: "",
81 transcript: "",
82 /** The session whose start swb has recorded, so a late environment records it once. */
83 recorded: "",
84 busy: false,
85 turnId: "",
86 blocked: false,
87 draft: "",
88 pending: [],
89 /** A title set through swb, { target, title }, that Claude Code takes as its own with the next prompt. */
90 title: null,
91 /** The model and effort of this session's last model request recorded, so only a change is recorded again. */
92 request: "",
93 /** The last record in flight; each waits for the one before, so swb sees them in order. */
94 recording: Promise.resolve(""),
95};
96
97async function env($, name) {
98 if (name === "SWB_BIN") return (await $.env.get("SWB_BIN")) ?? "";
99 if (name === "SWB_TMUX_SESSION") return (await $.env.get("SWB_TMUX_SESSION")) ?? "";
100 return (await $.env.get("SWB_DB")) ?? "";
101}
102
103/** Runs swb; a failure carries its stderr, which is what the model or the person should read. */
104async function swb($, args, stdin) {
105 const result = await $.process.run([line.bin, ...args], { ...(stdin === undefined ? {} : { stdin }), timeoutMs: 90000 });
106 if (result.exitCode !== 0) throw new Error(result.stderr.trim().replace(/^swb: /, "") || `swb ${args[0]} exited ${result.exitCode}`);
107 return result.stdout;
108}
109
110/**
111 * Records in order, after any still in flight. A turn's hooks don't wait for theirs: each is an swb process to boot,
112 * which Claude's next model request would wait out.
113 */
114function record($, args) {
115 line.recording = line.recording.then(() => recordNow($, args));
116 return line.recording;
117}
118
119/** Recording never fails a hook: it says so where the person looks, and Claude carries on. */
120async function recordNow($, args) {
121 try {
122 return await swb($, ["__record", ...args, "--host", line.host]);
123 } catch (error) {
124 $.ui.toast(`swb: not recording: ${error.message}`);
125 $.ui.log(`swb: not recording: ${error.message}`, { to: "debug" });
126 return "";
127 }
128}
129
130async function ack($, ids) {
131 if (ids.length > 0) await swb($, ["__ack", ...ids]);
132}
133
134function receipt($, m, how) {
135 // Claude Code draws a log's trailing newline as �.
136 const body = m.body.trim();
137 $.ui.log(`↘ ${m.title} (${how}): ${body.length > 200 ? `${body.slice(0, 200)}…` : body}`);
138}
139
140/** The held messages for the session this process shows now; any others wait for theirs. */
141function take() {
142 const batch = line.pending.filter((m) => m.target === line.session);
143 line.pending = line.pending.filter((m) => m.target !== line.session);
144 return batch;
145}
146
147/**
148 * Starts a turn with what arrived while idle. submit resolves once that turn starts, which is when the batch is
149 * delivered; awaited inside a hook that runs while Claude works, it never would, so callers don't await this.
150 */
151async function submitPending($) {
152 if (line.busy || !line.session) return;
153 const batch = take();
154 if (batch.length === 0) return;
155 try {
156 await $.prompt.submit({ text: batch.map((m) => m.text).join("\n\n---\n\n") });
157 } catch (error) {
158 line.pending.unshift(...batch);
159 $.ui.log(`swb: couldn't start a turn for ${batch.length} message(s): ${error.message}`);
160 return;
161 }
162 for (const m of batch) receipt($, m, "new turn");
163 await ack(
164 $,
165 batch.map((m) => m.id),
166 );
167}
168
169/** Keeps swb's inbox for this session running for the session's life, and says so when it fails. */
170async function pump($) {
171 for (;;) {
172 try {
173 const ended = await drain($);
174 // A signal means the session is ending, and the line with it; anything else is worth saying.
175 if (ended?.signal) return;
176 $.ui.log(`swb: inbox stopped (exit ${ended?.code}); restarting`);
177 } catch (error) {
178 $.ui.log(`swb: inbox failed: ${error.message}; restarting`);
179 }
180 await $.clock.sleep(1000);
181 }
182}
183
184async function drain($) {
185 const inbox = $.process.spawn({ argv: [line.bin, "__inbox", "--host", line.host] });
186 let buffer = "";
187 const iterator = inbox[Symbol.asyncIterator]();
188 for (;;) {
189 const { done, value } = await iterator.next();
190 if (done) return value;
191 const { stream, text } = value;
192 if (stream !== "stdout") {
193 $.ui.log(`swb inbox: ${text}`);
194 continue;
195 }
196 buffer += text;
197 for (let nl = buffer.indexOf("\n"); nl >= 0; nl = buffer.indexOf("\n")) {
198 const raw = buffer.slice(0, nl);
199 buffer = buffer.slice(nl + 1);
200 if (!raw.trim()) continue;
201 const m = JSON.parse(raw);
202 if (m.kind === "title") line.title = m;
203 else if (m.kind === "cancel") {
204 if (line.busy && line.turnId) await $.turn.abort({ turnId: line.turnId });
205 await ack($, [m.id]);
206 } else {
207 line.pending.push(m);
208 void submitPending($);
209 }
210 }
211 }
212}
213
214/** A launch's Group as swb's flags take it: omitted, named, or none. */
215function groupFlags(prefix, group) {
216 if (group === undefined) return [];
217 return group === null ? [`${prefix}no-group`] : [`${prefix}group`, group];
218}
219
220async function useTool($, name, e) {
221 // The caller is whoever Claude Code says this session is now, never a value cached from an event that can be missed.
222 const self = await $.session.id();
223 const from = ["--from", self];
224 // A launch carries forward the model and effort this session runs on, which swb reads from its records.
225 if (name === "session_launch" || name === "session_schedule") await line.recording;
226 switch (name) {
227 case "session_reachable":
228 return swb($, ["reachable", ...from]);
229 case "session_search":
230 return swb($, ["search", ...from, ...(e.limit ? ["--limit", String(e.limit)] : [])], e.query);
231 case "session_send_message":
232 return swb(
233 $,
234 ["send", ...from, "--to", e.session, "--request-id", e.tool_use_id, ...(e.requestResponse ? ["--request-response"] : [])],
235 e.message,
236 );
237 case "session_cancel":
238 return swb($, ["send", ...from, "--to", e.session, "--cancel"]);
239 case "session_launch":
240 return swb(
241 $,
242 [
243 "launch",
244 ...from,
245 ...["harness", "model", "effort", "agent"].flatMap((k) => (e[k] ? [`--${k}`, e[k]] : [])),
246 "--cwd",
247 e.cwd ?? line.cwd,
248 "--title",
249 e.title,
250 ...groupFlags("--", e.group),
251 ...(e.requestResponse ? ["--request-response"] : []),
252 ],
253 e.goal,
254 );
255 case "session_schedule":
256 return swb(
257 $,
258 [
259 "schedule",
260 ...from,
261 "--label",
262 e.label,
263 "--request-id",
264 e.tool_use_id,
265 ...(e.at !== undefined ? ["--at", e.at] : []),
266 ...(e.cron !== undefined ? ["--cron", e.cron] : []),
267 ...(e.session !== undefined ? ["--to", e.session] : []),
268 ...(e.launch
269 ? [
270 ...["harness", "model", "effort", "agent"].flatMap((k) => (e.launch[k] ? [`--launch-${k}`, e.launch[k]] : [])),
271 "--launch-title",
272 e.launch.title,
273 "--launch-cwd",
274 e.launch.cwd ?? line.cwd,
275 ...groupFlags("--launch-", e.launch.group),
276 ]
277 : []),
278 ...(e.requestResponse ? ["--request-response"] : []),
279 ...(e.snooze ? ["--snooze"] : []),
280 ],
281 e.message,
282 );
283 case "session_schedules":
284 return swb($, ["schedules", ...from]);
285 case "session_unschedule":
286 return swb($, ["unschedule", e.id, ...from]);
287 case "swb_show_session":
288 return swb($, ["show", e.session, ...from, ...(e.view ? ["--view", e.view] : [])]);
289 case "swb_update_session": {
290 // The event carries the call's own fields beside its arguments; swb checks only the arguments.
291 const { properties } = TOOLS.find((t) => t.name === name).inputSchema;
292 const args = Object.fromEntries(Object.keys(properties).flatMap((key) => (e[key] === undefined ? [] : [[key, e[key]]])));
293 return swb($, ["update", ...from], JSON.stringify(args));
294 }
295 default:
296 throw new Error(`swb: no tool ${name}`);
297 }
298}
299
300/**
301 * Reads swb's launch environment and the session this process shows, and records that session's start once. Every
302 * hook asks, since none is sure to arrive: another mod can answer classic.SessionStart without passing it on.
303 */
304async function init($, start) {
305 if (!line.managed) {
306 line.bin = await env($, "SWB_BIN");
307 line.host = await env($, "SWB_TMUX_SESSION");
308 line.managed = Boolean(line.bin && line.host);
309 if (line.managed && !line.started) {
310 line.started = true;
311 void pump($);
312 }
313 }
314 if (!line.managed) return;
315 await follow($, start);
316 await begin($);
317}
318
319/** Moves to the session Claude Code shows now; /clear and /resume change it. classic.SessionStart also names its transcript. */
320async function follow($, start) {
321 const id = start?.session_id ?? (await $.session.id());
322 if (id !== line.session) {
323 // Messages held for a session this process left stay undelivered, for when that session runs again.
324 line.pending = line.pending.filter((m) => m.target === id);
325 line.session = id;
326 line.cwd = start?.cwd ?? (await $.session.cwd());
327 line.transcript = "";
328 line.busy = false;
329 line.blocked = false;
330 line.request = "";
331 }
332 if (start?.transcript_path) line.transcript = start.transcript_path;
333}
334
335/** Records the start of the session this process shows, once. */
336async function begin($) {
337 if (line.recorded === line.session) return;
338 line.recorded = line.session;
339 await record($, ["start", "--session", line.session, "--cwd", line.cwd, "--transcript", line.transcript]);
340 await restoreDraft($);
341 void submitPending($);
342}
343
344/**
345 * swb is the only thing that loads this plugin, so its coordination tools are offered; a call outside swb says so. All at
346 * once: each registration reconnects the plugin's tool server and waits until its tool lists, which the first turn
347 * waits for, and five in a row took 750 ms.
348 */
349async function registerTools($) {
350 await Promise.all([...TOOLS, ...READER_TOOLS].map((tool) => registerTool($, tool)));
351}
352
353async function registerTool($, tool) {
354 try {
355 // Coordination is upfront; only the reader needs its tools' schemas.
356 await $.tool.register({ ...tool, isDeferred: READER_TOOLS.includes(tool) });
357 } catch (error) {
358 $.ui.log(`swb: tool ${tool.name} not registered: ${error.message}`);
359 }
360}
361
362async function draftPath($, id) {
363 const db = await env($, "SWB_DB");
364 return `${db.slice(0, db.lastIndexOf("/"))}/drafts/${id}`;
365}
366
367async function restoreDraft($) {
368 const path = await draftPath($, line.session);
369 if (!(await $.fs.exists(path))) return;
370 const draft = await $.fs.read(path);
371 await $.fs.write(path, "");
372 if (draft) await $.prompt.fill({ text: draft });
373}
374
375async function trackDraft(_$, e, next) {
376 const result = await next(e);
377 line.draft = result.text;
378 return result;
379}
380
381async function saveDraft($) {
382 if (line.draft.trim()) await $.fs.write(await draftPath($, line.session), line.draft);
383}
384
385export function register(on) {
386 on("session.start", async ($, e, next) => {
387 const result = await next(e);
388 await registerTools($);
389 await registerReader($);
390 await init($);
391 return result;
392 });
393
394 on("agent.offer", { agent: "swb:reader" }, () => ({ isOffered: false }));
395
396 // Fires at startup and again after /clear and /resume, which move this process to another session.
397 on("classic.SessionStart", async ($, e, next) => {
398 await init($, e);
399 return next(e);
400 });
401
402 on("turn.start", async ($, e, next) => {
403 await init($);
404 if (line.managed && !e.agentId) {
405 line.busy = true;
406 line.turnId = e.turnId;
407 void record($, ["turn", "--session", line.session, "--cwd", line.cwd, "--transcript", line.transcript]);
408 }
409 return next(e);
410 });
411
412 // Claude Code names a session from a prompt hook's sessionTitle, and writes it as its own custom title.
413 on("classic.UserPromptSubmit", async (_, e, next) => {
414 const result = await next(e);
415 const pending = line.title;
416 if (!line.managed || pending?.target !== line.session) return result;
417 line.title = null;
418 return { ...result, sessionTitle: pending.title };
419 });
420
421 on("classic.PermissionRequest", async ($, e, next) => {
422 if (line.managed && line.busy && !line.blocked) {
423 line.blocked = true;
424 void record($, ["phase", "blocked", "--session", line.session]);
425 }
426 return next(e);
427 });
428
429 // A model request means the permission prompt was answered.
430 // Its transcript records the model of each turn but never the effort, so the line records both as each request goes out.
431 // An effort given as a number of tokens isn't a level, and is recorded as none.
432 on("turn.step", async function* ($, e, next) {
433 if (line.managed && !e.agentId && e.model) {
434 const effort = typeof e.effort === "string" ? e.effort : "";
435 if (`${e.model}\t${effort}` !== line.request) {
436 line.request = `${e.model}\t${effort}`;
437 void record($, ["request", "--session", line.session, "--model", e.model, ...(effort ? ["--effort", effort] : [])]);
438 }
439 }
440 if (line.managed && !e.agentId && line.blocked) {
441 line.blocked = false;
442 void record($, ["phase", "working", "--session", line.session]);
443 }
444 return yield* next(e);
445 });
446
447 on("turn.complete", async ($, e, next) => {
448 const result = await next(e);
449 const reader = e.agentId && readers.get(e.agentId);
450 if (reader) {
451 reader.answer = e.answer ?? "The reader stopped without an answer.";
452 await reader.wait.return();
453 }
454 if (line.managed && !e.agentId) {
455 line.busy = false;
456 line.blocked = false;
457 // swb stops this session after recording, when it was archived during the turn.
458 void record($, ["settled", "--session", line.session, "--cwd", line.cwd, "--transcript", line.transcript]);
459 void submitPending($);
460 }
461 return result;
462 });
463
464 // The turn ended on an API error; turn.complete still settles it.
465 on("classic.StopFailure", async ($, e, next) => {
466 if (line.managed && !e.agent_id) void record($, ["errored", "--session", line.session]);
467 return next(e);
468 });
469
470 // Separate from the spawning hook: Claude skips that hook in the nested agent to prevent re-entry.
471 for (const tool of READER_TOOLS) on("tool.call", { tool: `mcp__swb__${tool.name}` }, ($, e) => readerTool($, tool, e));
472
473 on("tool.call", async ($, e, next) => {
474 const tool = TOOLS.find((t) => e.tool === `mcp__swb__${t.name}`);
475 if (tool) {
476 await init($);
477 if (!line.managed) return { deny: "this Claude Code session isn't on the switchboard: swb didn't start it" };
478 try {
479 if (tool.name === "session_ask") return { result: await ask($, e) };
480 return { result: JSON.parse(await useTool($, tool.name, e)).text };
481 } catch (error) {
482 return { deny: error.message };
483 }
484 }
485 const result = await next(e);
486 // Messages that arrived mid-turn ride on the next main-loop tool result, which Claude reads before going on.
487 if (!line.managed || e.agentId || next.origin.plugin !== "engine" || !("result" in result)) return result;
488 const batch = take();
489 if (batch.length === 0) return result;
490 for (const m of batch) receipt($, m, "mid-turn");
491 await ack(
492 $,
493 batch.map((m) => m.id),
494 );
495 return { ...result, context: [...(result.context ?? []), ...batch.map((m) => m.text)] };
496 });
497
498 // A typed edit raises prompt.edit; a submit, a clear, a recall, or a fill raises prompt.change.
499 on("prompt.edit", trackDraft);
500 on("prompt.change", trackDraft);
501
502 on("session.end", async ($, e, next) => {
503 if (line.managed && e.reason !== "clear" && e.reason !== "resume") {
504 await saveDraft($);
505 await record($, ["end"]);
506 }
507 return next(e);
508 });
509}
510