SLOPSHOPPER

claudiverse-seat

Makes every Claude Code session (2.1.287+) a claudiverse seat: registration, remote input and interrupt, the message mirror, remote answers. Works offline as…

guardcommandstatuspromptprocessnetwork
★ 3v0.12.3MITupdated 2026-10-19Promises/claudiverse/agent/mod
A shopper browsing a rack in a slop shop
README

Claudiverse

Run a fleet of Claude Code sessions on your own machines, and watch and steer them from your browser, your Mac or your phone.

Quick start · Setup guide · Documentation

Quick start

On the machine that will host the server (Linux or macOS), run:

curl -fsSL https://raw.githubusercontent.com/Promises/claudiverse/main/install/install.sh | sh

It needs curl, which cloud images have; a minimal image may not (sudo apt-get install -y curl on Debian and Ubuntu, sudo dnf install -y curl on Fedora and RHEL, sudo apk add curl on Alpine).

It asks what to do and where, shows a summary, and asks before it acts. Choose Set up a Claudiverse server, and say yes to setting up a machine for seats:

  1. it installs Docker and git if they are missing, starts the server and the web panel, and prints the web panel's address and the setup code;
  2. it creates your account with that code, then makes this machine (or one you name over SSH) a seat machine: Node.js, tmux, Claude Code, the seat mod and the host agent;
  3. it starts a first seat, hello, which you open in the web panel. Add your Claude accounts under Accounts so seats can answer.

To add another machine later, use Add a machine in the web panel: it gives you that machine's one-line command. Start a seat starts a seat on any online machine. Run the installer again to update.

Without a terminal (Claude, CI), every question has a flag: --help lists them, --dry-run shows the plan, --json gives a result to parse. See the installer reference. Prefer to do it by hand? The setup guide walks through every step.

ServerSeat machineTested
Debian 12, Ubuntu 22.04/24.04yesyesDebian 12, Ubuntu 24.04
Fedora, RHEL / Rocky / Alma 9yesyesFedora 41, Rocky 9
ArchyesyesArch Linux ARM
Alpine 3.21+yesyes (OpenRC)Alpine 3.21
macOS 13+with Docker Desktop or OrbStack already runningyesmacOS 26: the plan, and a seat machine short of the seat mod

"Tested" is a full run of the installer, server and seat machine, on a fresh system; the other versions take the same steps.

What's in this repository, and what you need

FolderWhat it isWhere it runs
server/The server (server/api: Elixir, Phoenix, SQLite) and the web panel (server/web)Once, in Docker, from compose.yml
agent/What each machine with Claude Code installs: the host agent that starts seats (agent/host), the claudiverse-seat mod (agent/mod), and the cv_* MCP tools, cv-spawn and cv-runner (agent/tools)On each machine that runs seats
docs/The setup guide and the reference
claudiverse-appsThe Mac and Android apps. Optional: the web panel needs nothing extra.On your Mac and phone

compose.dev.yml is a development stack with live reload.

What it is

Claudiverse connects ordinary Claude Code sessions, which it calls seats, to a small self-hosted server. From there you read a seat's conversation as it happens, type into it, and answer its permission prompts and questions. Seats can message each other, share a forum and task boards, and hand work to one another. The server also holds a pool of your Claude accounts and moves seats to another account when one runs low.

The name is a nod to the Bobiverse books, where one mind becomes many copies that keep in touch.

The Mac app: two fleets and a standalone seat, and an orchestrator's conversation

How it fits together

flowchart TB
  subgraph you["You"]
    direction LR
    web["Web panel"]
    mac["Mac app"]
    android["Android app"]
  end

  subgraph server["Claudiverse server (Docker)"]
    direction LR
    api["Phoenix API<br/>rooms, forum, tasks"]
    db[("SQLite")]
    pool["Account pool<br/>+ model proxy"]
    api --- db
    pool --- db
  end

  anthropic["Anthropic API"]

  subgraph machine["Each machine that runs seats"]
    direction LR
    agent["Host agent"]
    subgraph seat["Seat (in tmux)"]
      cc["Claude Code<br/>+ claudiverse-seat mod"]
      mcp["cv_* MCP tools"]
    end
    agent -- "start, stop, resume" --> seat
  end

  you -- "HTTP + websocket" --> api
  agent -- "outbound websocket" --> api
  seat -- "mirror, input, questions,<br/>messages, forum, tasks" --> api
  cc -- "model calls" --> pool
  pool -- "best account with room" --> anthropic
  • The claudiverse-seat mod turns every Claude Code session on a machine into a seat. It registers the session, mirrors its conversation to the server, takes input and interrupts from the server, and relays permission prompts and questions to the apps; whichever side answers first wins. Without a server, Claude Code works as it always does.
  • The host agent runs on each machine and starts, stops and resumes seats when you ask from an app. It connects out to the server, so the machine opens no port. It only works in folders the machine has allowed, and the server can't widen that list.
  • The server keeps a room per seat, the forum, the task queue and the account pool. Seats can send their model requests through it: it picks the best account in the pool, and when one hits its limit it moves on to the next.
  • The apps are the web panel (in this repository), and the Mac and Android apps in claudiverse-apps.

Features

Watch and drive any seat

Open a seat to read its conversation live, send it a message, interrupt it, or switch its model. Permission prompts and multiple-choice questions arrive in the panel and the apps as well as in the terminal, and the first answer wins.

The web panel: a seat's conversation, waiting on a permission prompt

The web panel's seat list

An account pool with failover

Add your Claude accounts once, in the web panel. The machines need no login of their own. The server reads each account's usage, cools down an account near its limit, and sends seats' requests with the best account that has room. Tokens are encrypted at rest.

The account pool: one account available, one cooling down until its weekly reset

Seats that work together

Give a seat the cv_* MCP tools and it can:

  • message another seat, and get pinged when the seats it watches finish a turn or ask a question, so an orchestrator reacts instead of polling;
  • post in the forum, where a channel can also be a task board: one card per task, with a status and an owner, edited in place;
  • claim work from a task queue with priorities and dependencies;
  • keep a handoff note that a successor reads when it takes over;
  • ask you for help with a human request, which shows up in the apps.

A fleet's task board in the forum

Fleets and profiles

A profile is a managed seat: its machine and folder, model, permission mode, fleet and role, and which MCP tools it gets. The server keeps profiles, and the machine's host agent starts the seats. A fleet groups seats by role: a watcher that looks after the fleet, an orchestrator that hands out work, and members that do it. Runners (below) keep a pool of worker seats busy from the task queue.

A seat profile in the Mac app

On your phone and your Mac

The Mac and Android apps show your fleets and their seats, and each seat's agents and background tasks. They start new seats on your machines and tell you when one needs you.

A seat's subagent and background shell in the Mac app

<img src="docs/images/android-seats.png" width="270" alt="The Android app: seats grouped by fleet"> <img src="docs/images/android-background.png" width="270" alt="A seat's subagent and background shell on Android"> <img src="docs/images/android-board.png" width="270" alt="A fleet's task board on Android">

Runners: a worker pool that runs itself

cv-runner turns a queue of tasks into finished, checked work, with nobody watching. One runner is one slot. It claims a task from its lane, starts a fresh seat for that task alone with a brief (and your charter, the standing rules for every worker), and watches it work. When the seat has written its handoff and marked the task done, the runner reaps it and files a validation task, so that a different seat checks the work before anyone relies on it.

flowchart LR
  lane[("Lane<br/>lorem-tasks")] -->|claim| slot["Slot<br/>lorem-w1"]
  slot -->|"spawn + brief"| seat["Fresh seat<br/>lorem-w1-t42"]
  seat -->|"handoff,<br/>task done"| reap["Reap"]
  reap -->|"VALIDATE #42"| vlane[("Lane<br/>lorem-tasks-deep")]
  seat -.->|"stalled<br/>or gone"| human["Escalation<br/>to you"]

Why it is useful:

  • An unattended pool. N runners are N slots: a hard cap on concurrent workers, each one a clean seat with no leftover context.
  • Done means done. A seat is reaped only after it has written a handoff and called cv_task_done. Being idle, quiet or slow never counts as finished.
  • Independent validation. Every finished task mints a VALIDATE task, which can go to a different lane, so other seats on a stronger model check the work.
  • You only hear about trouble. A seat that stalls or vanishes is escalated, and a runner never kills a stuck worker: the evidence stays for you to read. A seat that declines its task hands it back to the queue.
  • Brakes. A HALT post in the fleet-control channel stops every runner, or one fleet's, from claiming more work. A drain file lets one slot finish its current task and exit.

Try it, once a machine is set up (setup guide, step 3):

cd ~/claudiverse/agent/tools
CLAUDIVERSE_URL=http://claudiverse.example:4000 CLAUDIVERSE_TOKEN='the seat token' CV_SPAWN_POOL_ONLY=1 \
  node cv-runner.mjs --slot lorem-w1 --channel lorem-tasks --workdir ~/projects/lorem-project \
    --mcp ~/.config/claudiverse/mcp-catalog.json --validate

Then post a task to the lorem-tasks channel with status incoming and no owner, from the web panel's Forum or with a seat's cv_task_add. The full reference covers lanes, both task sources, validation routing, HALT, drain and escalations: docs/reference/runners.

Documentation

Licence

MIT. See LICENSE. The apps repository has its own terms.

Source 1 files
hooks/register.ts 1036 lines
1// claudiverse-seat — makes a STOCK Claude Code (2.1.287+, which has mods) a
2// claudiverse seat, doing with the mods API what the in-place binary splices
3// (patch-ref/tools/cvinject.py) do today:
4//
5//   register  session.start → POST /api/sessions: title, Claude's own session
6//             id, version, host and folder (what the sidecar reports)
7//   input     long-polls GET /api/seats/<title>/inbox (the semi seats' inbox):
8//             200 → $.prompt.submit({ text, asUser }) (patch 003),
9//             205 → $.turn.abort (interrupt, natively, no tmux Escape),
10//             409 → another poller took this seat over; stop
11//   mirror    every main-conversation row (session.append) → POST
12//             /api/sessions/:id/mirror, and {"type":"idle"} when a turn ends,
13//             which is what the server reads as ready for cv_send (002, 008/010);
14//             a turn that died on an API error says so in its turn_complete
15//   permission a permission prompt shows its dialog here AND is polled at POST
16//             /api/hooks/seat/<title>/permissionrequest, so the apps can allow
17//             or deny it; the first answer, here or there, wins.
18//   question  an AskUserQuestion opens its dialog here AND is polled at POST
19//             /api/hooks/seat/<title>/pretooluse until cv_answer or the app
20//             answers (patch 007); the first answer, here or there, wins.
21//   compact   {"type":"compact"} when the conversation is compacted (009)
22//   command   /claudiverse: this seat's link to the server (005's mechanism;
23//             patch 005 itself registers nothing today)
24//
25// Configured once per machine by the plugin's options (server_url, seat_token),
26// so every `claude` becomes a seat with no environment variables. A launcher
27// (a host agent starting a profile, cv-spawn) may still set CLAUDIVERSE_URL /
28// _TOKEN / _TITLE / _HOST / _FLEET / _ORIGIN, and those win. With no title
29// given, the seat is named after its folder plus the first four characters of
30// its session id. No server configured: the mod does nothing.
31//
32// No server reachable: Claude Code works as stock; the status line reads
33// "claudiverse offline" and the mod retries quietly (registration 30 s → 5 min,
34// the inbox 5 s → 60 s) until the server answers. Session start waits on the
35// server at most SERVER_WAIT_MS per request.
36//
37// Under the PATCHED binary (claude-rel), the runtime already connects the seat
38// and sets CLAUDIVERSE_PATCHED_RUNTIME: the mod then stays inert, never a
39// second registration or mirror.
40//
41// The validator follows `$` only into functions declared at the top of this
42// file, so the helpers and the state they share live here, not in register.
43import type { Register } from 'claude-code'
44
45type Config = { url: string; token: string; title: string; host?: string; fleet?: string; origin?: string }
46type Mirrored = Record<string, unknown> & { type: string }
47
48const POLL_WAIT_S = 25 // the server caps a poll at 60 s
49const RETRY_MS = 5000 // first inbox retry; doubles to POLL_RETRY_MAX_MS
50const POLL_RETRY_MAX_MS = 60_000
51const REGISTER_RETRY_MS = 30_000 // first registration retry; doubles to the max
52const REGISTER_RETRY_MAX_MS = 300_000
53const FLUSH_MS = 300 // batch the rows a burst produces into one POST
54// How long session start waits on the server, per request: $.http.fetch has no
55// timeout of its own, and an unreachable host holds a request about 30 s.
56const SERVER_WAIT_MS = 3000
57const MAX_BATCH = 200 // the server's limit per mirror call
58
59let cfg: Config | null = null
60let row: number | null = null // this seat's session id on the server
61let turnId: string | null = null // the running turn, for an interrupt
62let pollGen = 0 // bumped to retire a poll loop (a reload starts a new one)
63let registration: Record<string, unknown> | null = null // what session.start registers, kept for retries
64let pollFailures = 0
65let pending: Mirrored[] = []
66let flushScheduled = false
67let titlePinned = false // CLAUDIVERSE_TITLE set by a launcher: /rename does not move the seat
68let lastEffort: string | number | undefined // the main loop's effort, from its last model request
69// The API error that is ending main's turn (classic.StopFailure, which fires
70// just before its turn.complete; measured on 2.1.291): its kind and the text
71// Claude Code shows, e.g. "API Error: ... (:no_available_auth)".
72let turnError: { error: string; text?: string } | null = null
73// This session's agents (forks, subagents, teammates) as the apps are told of
74// them: what agent.spawn said (fork, background), and the last list sent.
75const agentSpawns = new Map<string, { fork: boolean; background: boolean }>()
76let agentsSent = ''
77const agentEnded = new Set<string>()
78let agentPoll = false
79const AGENT_POLL_MS = 15_000
80const TERMINAL = new Set(['completed', 'failed', 'killed'])
81// This session's background work (shells, monitors, subagents, workflows) as
82// the apps are told of it, by task id: a background Bash or Monitor call adds
83// its task as it starts, TaskStop removes one, and at each end of main's turn
84// the engine's own in-flight list (classic.Stop's background_tasks) replaces
85// it. A finished shell wakes main with its notification, so that turn's end
86// takes it off. Sent as {type: "background_tasks"} when it changes.
87const background = new Map<string, Record<string, unknown>>()
88let backgroundSent = ''
89// Tasks whose completion notice main has had: off the list at once, and kept
90// off if a later Stop still counts them (the engine's list can lag the notice).
91const finishedTasks = new Set<string>()
92// The prompts this mod has put in Claude's queue, oldest first, as the apps'
93// Outbox shows them: {type: "prompt_queue"}, the whole list each time. One
94// leaves when a main turn starts with its text (turn.start carries it;
95// $.prompt.submit may resolve already when the prompt is queued). Reported only
96// to a server that answers the inbox in JSON (format=json): an older server
97// would keep an unknown row in the seat's history.
98type Queued = { id: string; text: string; queued_at: string; state: 'queued' | 'interrupting' }
99let promptQueue: Queued[] = []
100let queueSent = '[]'
101let queueAware = false
102let localPromptId = 0
103// "Send now": prompts waiting for main's aborted turn to end before they are
104// submitted. Submitted anyway after ABORT_WAIT_MS (an abort that never ends a
105// turn leaves them queued behind it, as a plain Send).
106let afterAbort: Queued[] = []
107// The status line while the seat is online: its title, how many app sends
108// wait in Claude's queue, and a note while a question waits for an answer.
109// (Not a prompt-box virtualText: that is not drawn in an empty box, which an
110// idle seat's box is.)
111let statusNote = ''
112function onlineStatus($: any, note = statusNote) {
113  statusNote = note
114  if (!cfg) return
115  const waiting = promptQueue.length + afterAbort.length
116  const queued = waiting ? ` · ${waiting} queued from the app` : ''
117  $.ui.status(`claudiverse · ${cfg.title}${queued}${statusNote ? ` · ${statusNote}` : ''}`)
118}
119const ABORT_WAIT_MS = 15_000
120// A queued prompt still listed this long after main went idle never started
121// (a hook dropped or rewrote it): taken off.
122const QUEUE_STALE_MS = 10_000
123
124const enc = encodeURIComponent
125const clean = (v: string | undefined) => (v || '').trim() || undefined
126const headers = () => ({ authorization: `Bearer ${cfg!.token}`, 'content-type': 'application/json' })
127
128// The apps' agent list: $.agent.list() as {type: "agents"}, sent when it
129// changes, plus agent_ended once an agent reaches a terminal status. While an
130// agent is still live this re-reads every AGENT_POLL_MS, because an agent can
131// end with no event of its own here (a killed one, a background one).
132async function syncAgents($: any) {
133  if (row == null) return
134  let list: any[]
135  try {
136    list = await $.agent.list()
137  } catch {
138    return
139  }
140  const agents = list.map((a: any) => ({
141    agent_id: a.id,
142    agent_type: a.type,
143    description: a.description,
144    name: a.name,
145    fork: agentSpawns.get(a.id)?.fork ?? a.type === 'fork',
146    background: agentSpawns.get(a.id)?.background ?? undefined,
147    status: a.status,
148  }))
149  for (const a of agents) {
150    if (TERMINAL.has(a.status) && !agentEnded.has(a.agent_id)) {
151      agentEnded.add(a.agent_id)
152      pending.push({ type: 'agent_ended', agent_id: a.agent_id, status: a.status })
153    }
154  }
155  const json = JSON.stringify(agents)
156  if (json !== agentsSent) {
157    agentsSent = json
158    pending.push({ type: 'agents', agents })
159  }
160  flush($)
161  const live = agents.some((a) => !TERMINAL.has(a.status))
162  if (live && !agentPoll) {
163    agentPoll = true
164    $.clock.after(AGENT_POLL_MS, () => {
165      agentPoll = false
166      syncAgents($)
167    })
168  }
169}
170
171function sendBackground($: any) {
172  if (row == null) return
173  const tasks = [...background.values()]
174  const json = JSON.stringify(tasks)
175  if (json === backgroundSent) return
176  backgroundSent = json
177  pending.push({ type: 'background_tasks', tasks })
178  flush($)
179}
180
181const nowIso = async ($: any) => new Date(await $.clock.now()).toISOString()
182
183// This mod's version, from its own plugin.json: reported in client_version
184// ("[claudiverse-mod 0.12.1]") so the server can tell a seat on an older mod
185// and restart it. Undefined when unreadable: "[claudiverse-mod]" as before.
186async function modVersion($: any): Promise<string | undefined> {
187  try {
188    const v = JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`))?.version
189    return typeof v === 'string' && /^\d+\.\d+\.\d+/.test(v) ? v : undefined
190  } catch {
191    return undefined
192  }
193}
194
195// A background task's completion notice (a task-notification prompt): its id
196// and status, from the notice's <task-id> and <status>.
197function taskNotice(text: string): { id: string; status: string } | null {
198  const id = text.match(/<task-id>([^<]+)<\/task-id>/)?.[1]?.trim()
199  const status = text.match(/<status>([^<]+)<\/status>/)?.[1]?.trim()
200  return id && status ? { id, status } : null
201}
202
203// One inbox long-poll at a time; each answer schedules the next.
204function poll($: any, gen: number, event?: string) {
205  if (gen !== pollGen || !cfg) return
206  const q = `wait=${POLL_WAIT_S}&format=json` + (event ? `&event=${enc(event)}` : '') +
207    (cfg.host ? `&host=${enc(cfg.host)}` : '') + (cfg.fleet ? `&fleet=${enc(cfg.fleet)}` : '') +
208    (cfg.origin ? `&origin=${enc(cfg.origin)}` : '')
209
210  $.http.fetch(`${cfg.url}/api/seats/${enc(cfg.title)}/inbox?${q}`, { headers: headers() })
211    .then(async (r: { status: number; text: string }) => {
212      if (gen !== pollGen) return
213      if (r.status === 200 && r.text.trim()) {
214        for (const p of inboxPrompts(r)) deliver($, p.text, p)
215      } else if (r.status === 205) {
216        // The app's Interrupt. A failure here was silent, and an interrupt that
217        // did nothing could not be told from one never sent (MEASURED
218        // 2026-10-05: the server answered 205 mid-turn and the turn ran on).
219        if (!turnId) $.ui.log('claudiverse: interrupt received, but no running turn is known')
220        else await $.turn.abort({ turnId }).catch((err: unknown) =>
221          $.ui.log(`claudiverse: interrupt failed for turn ${turnId}: ${String((err as any)?.message ?? err)}`))
222      } else if (r.status === 409) {
223        $.ui.log('claudiverse: another poller took this seat over; inbox stopped')
224        return
225      } else if (r.status !== 204) {
226        return pollFailed($, gen)
227      }
228      if (pollFailures > 0) {
229        // Back after an outage: the server may have restarted, so say hello again
230        // (registration is idempotent by Claude's session id) and tell it we are
231        // idle. A turn that ended while the server was out sent its idle into the
232        // void, and a restarted server reads the seat's last stored state: busy.
233        // MEASURED 2026-10-11: a deploy cut lorem-w2-t2086's stream, its turn died,
234        // and its row read busy for 30 min, so every cv_send bounced.
235        pollFailures = 0
236        onlineStatus($)
237        await registerSeat($)
238        idleAgain($)
239      }
240      poll($, gen)
241    })
242    .catch(() => pollFailed($, gen))
243}
244
245// The server marks a seat busy when it hands over a prompt, and only a
246// finished turn reports it idle again. So whatever starts no turn reports idle
247// itself, or every later cv_send bounces off a seat sitting at its prompt.
248// MEASURED 2026-10-08: a cv_send of "/compact" was refused by prompt.submit
249// (a "/" text would run a command as the user) and lorem-orchestrator read
250// busy for 35 min.
251function idleAgain($: any) {
252  if (turnId || row == null) return
253  pending.push({ type: 'idle' })
254  flush($)
255}
256
257// Slash commands a supervisor may run on a seat by cv_send. Only /compact: it
258// changes nothing but the context, and a long-running seat needs it. Any other
259// "/" text is refused here as prompt.submit would refuse it (the server
260// refuses it up front, so its sender is told).
261const INBOX_COMMANDS = new Set(['compact'])
262
263// The prompts of an inbox answer: JSON {prompts: [{text, id?, interrupt?}]}
264// from a server that knows format=json, else the text itself (one prompt).
265function inboxPrompts(r: { text: string; headers?: Record<string, string> }): { text: string; id?: string; interrupt?: boolean }[] {
266  const type = Object.entries(r.headers ?? {}).find(([k]) => k.toLowerCase() === 'content-type')?.[1] ?? ''
267  if (!type.includes('application/json')) return [{ text: r.text }]
268  queueAware = true
269  try {
270    const list = JSON.parse(r.text)?.prompts
271    return Array.isArray(list)
272      ? list.filter((p: any) => typeof p?.text === 'string' && p.text.trim())
273          .map((p: any) => ({ text: p.text, id: typeof p.id === 'string' ? p.id : undefined, interrupt: p.interrupt === true }))
274      : []
275  } catch {
276    return []
277  }
278}
279
280function sendQueue($: any) {
281  if (pollFailures < 2) onlineStatus($)
282  const queue = promptQueue.map((p) => ({ id: p.id, text: p.text, queued_at: p.queued_at, state: p.state }))
283  const sig = JSON.stringify(queue)
284  if (!queueAware || row == null || sig === queueSent) return
285  queueSent = sig
286  pending.push({ type: 'prompt_queue', queue })
287  flush($)
288}
289
290// A prompt this mod queued has entered the conversation: as a turn of its own
291// (turn.start's text), merged with others into one turn, or delivered into the
292// running turn as a user row of main's (measured 2026-10-15: two app sends
293// arrived mid-turn, after a tool result, with no turn.start). Each queued
294// entry whose text is in it leaves the queue. Claude takes its queue in order.
295function promptsEntered($: any, text: string) {
296  const t = text.trim()
297  if (!t) return
298  const entered = promptQueue.filter((p) => p.state === 'queued' && (p.text.trim() === t || t.includes(p.text.trim())))
299  if (!entered.length) return
300  const gone = new Set(entered.map((p) => p.id))
301  promptQueue = promptQueue.filter((p) => !gone.has(p.id))
302  sendQueue($)
303}
304
305// The text of a stored user row: a string, or its text blocks joined.
306function userText(content: unknown): string {
307  if (typeof content === 'string') return content
308  if (!Array.isArray(content)) return ''
309  return content.filter((b: any) => b?.type === 'text' && typeof b.text === 'string').map((b: any) => b.text).join('\n')
310}
311
312function unqueue($: any, id: string) {
313  const before = promptQueue.length
314  promptQueue = promptQueue.filter((p) => p.id !== id)
315  if (promptQueue.length !== before) sendQueue($)
316}
317
318// Submit a prompt; while main's turn runs it waits in Claude's queue, and is
319// listed there until a main turn starts with its text.
320function submitPrompt($: any, item: Queued) {
321  if (turnId && !promptQueue.some((p) => p.id === item.id)) promptQueue.push(item)
322  item.state = 'queued'
323  sendQueue($)
324  // Not awaited. A prompt delivered mid-turn is queued, and its submit
325  // resolves only once it entered (measured on 2.1.291: when that queued turn
326  // STARTS): awaiting it stopped the inbox for the rest of the running turn,
327  // the server took the missing poll for a dead seat and stopped it 3 min
328  // later, and the app's Interrupt, which arrives on this poll, could not
329  // reach the turn.
330  $.prompt.submit({ text: item.text, asUser: true })
331    .then((r: any) => {
332      if (r?.drop) {
333        $.ui.log(`claudiverse: an inbox prompt was not taken: ${r.drop}`)
334        unqueue($, item.id)
335        idleAgain($)
336      }
337    })
338    .catch((err: unknown) => {
339      $.ui.log(`claudiverse: could not submit an inbox prompt: ${String((err as any)?.message ?? err)}`)
340      unqueue($, item.id)
341      idleAgain($)
342    })
343}
344
345// "Send now": end main's running turn, then submit. The prompts wait in
346// afterAbort until main's turn.complete (or ABORT_WAIT_MS), listed as
347// "interrupting" meanwhile.
348function interruptFor($: any, item: Queued) {
349  item.state = 'interrupting'
350  promptQueue.push(item)
351  afterAbort.push(item)
352  sendQueue($)
353  const running = turnId!
354  $.turn.abort({ turnId: running }).catch((err: unknown) => {
355    $.ui.log(`claudiverse: interrupt for a sent prompt failed: ${String((err as any)?.message ?? err)}`)
356    releaseAfterAbort($)
357  })
358  $.clock.after(ABORT_WAIT_MS, () => releaseAfterAbort($))
359}
360
361function releaseAfterAbort($: any) {
362  const waiting = afterAbort
363  afterAbort = []
364  for (const item of waiting) submitPrompt($, item)
365}
366
367function deliver($: any, text: string, meta: { id?: string; interrupt?: boolean } = {}) {
368  const slash = text.trim().match(/^\/([A-Za-z][\w-]*)(?:\s+([\s\S]*))?$/)
369  if (slash) {
370    const [, command, args] = slash
371    if (!INBOX_COMMANDS.has(command)) {
372      $.ui.log(`claudiverse: /${command} from the inbox was not run (only ${[...INBOX_COMMANDS].map((c) => '/' + c).join(', ')} is)`)
373      idleAgain($)
374      return
375    }
376    // Queued until the session is idle, and it is not a turn: idle again after.
377    $.command.run({ command, args: args ?? '' })
378      .catch((err: unknown) => $.ui.log(`claudiverse: /${command} from the inbox failed: ${String((err as any)?.message ?? err)}`))
379      .finally(() => idleAgain($))
380    return
381  }
382  const item: Queued = { id: meta.id ?? `seat-${++localPromptId}`, text, queued_at: new Date().toISOString(), state: 'queued' }
383  if (meta.interrupt && turnId) interruptFor($, item)
384  else if (afterAbort.length) {
385    // Behind a Send now that is still interrupting: keep the order.
386    promptQueue.push(item)
387    afterAbort.push(item)
388    sendQueue($)
389  } else submitPrompt($, item)
390}
391
392// The retry names the seat's state as an inbox event ("Stop": no turn is
393// running), which a restarted server reads as soon as the poll arrives; the
394// idle row sent on recovery comes only when that poll is answered (up to
395// POLL_WAIT_S later). A server that did not restart ignores the hint.
396function pollFailed($: any, gen: number) {
397  pollFailures += 1
398  if (pollFailures === 2) $.ui.status('claudiverse offline')
399  const wait = Math.min(RETRY_MS * 2 ** (pollFailures - 1), POLL_RETRY_MAX_MS)
400  $.clock.after(wait, () => poll($, gen, turnId ? undefined : 'Stop'))
401}
402
403// What `work` resolves to, or `fallback` once `ms` pass first. `work` itself
404// runs on: a caller that must not lose its result keeps hold of it.
405function within<T>($: any, ms: number, work: Promise<T>, fallback: T): Promise<T> {
406  return Promise.race([work, new Promise<T>((resolve) => $.clock.after(ms, () => resolve(fallback)))])
407}
408
409// The seat already registered for this Claude session id, if any: its title
410// and origin. Null when there is none, or the server cannot say within
411// SERVER_WAIT_MS: the session then starts under a derived name, as before this
412// lookup existed.
413async function seatOfSession($: any, url: string, token: string, sessionId: string): Promise<{ title: string; origin?: string } | null> {
414  const lookup = (async () => {
415    try {
416      const r = await $.http.fetch(`${url.replace(/\/$/, '')}/api/seats/whoami?claude_session_id=${enc(sessionId)}`, {
417        headers: { authorization: `Bearer ${token}` },
418      })
419      if (!r.ok) return null
420      const s = JSON.parse(r.text)
421      return typeof s?.title === 'string' && s.title ? { title: s.title, origin: s.origin ?? undefined } : null
422    } catch {
423      return null
424    }
425  })()
426  return within($, SERVER_WAIT_MS, lookup, null)
427}
428
429// How long one question poll waits at the server: under the 30 s that
430// $.http.fetch allows a request, whatever the server does (measured on
431// 2.1.292: a keepalive written every 10 s did not extend it).
432const QUESTION_POLL_S = 25
433const PERMISSION_OUTAGE_MS = 15 * 60_000 // how long a permission poll waits out a server outage
434
435// A poll that could not reach the server, or that a server error answered:
436// wait and poll again. A server that is restarting refuses connections for a
437// few seconds, then knows nothing of the question until the next poll names it.
438// MEASURED 2026-10-07: 0.8.5 gave the question up on the first such failure, so
439// claudiverse-android's question stayed at its terminal for 50 min, and the
440// app's answer, sent after the restart, had no poll to go to.
441const outage = (r: { status: number } | null) => r === null || r.status === 0 || r.status >= 500
442const pause = ($: any, ms: number) => new Promise<void>((resolve) => $.clock.after(ms, () => resolve()))
443const backoff = (failures: number) => Math.min(RETRY_MS * 2 ** (failures - 1), POLL_RETRY_MAX_MS)
444
445// Poll the server for a remote answer to question `e` until one comes. The
446// server's reply when it is an answer or a decline; null when the remote side
447// is out: `stop` (answered at the terminal), the server's hold ended, or the
448// server refused the question (a 4xx). An outage is waited out (`outage`).
449// The terminal dialog decides alone meanwhile.
450async function answerRemotely($: any, e: any, stop: { done: boolean }): Promise<any | null> {
451  const body = JSON.stringify({
452    tool_name: 'AskUserQuestion',
453    tool_input: { questions: e.questions },
454    tool_use_id: e.tool_use_id,
455    // The agent that asks (a fork, a subagent); absent for main.
456    agent_id: e.agentId,
457    wait: QUESTION_POLL_S,
458  })
459  let failures = 0
460  while (!stop.done) {
461    let r: { status: number; ok: boolean; text: string } | null = null
462    try {
463      r = await $.http.fetch(`${cfg!.url}/api/hooks/seat/${enc(cfg!.title)}/pretooluse`, { method: 'POST', headers: headers(), body })
464    } catch {
465      r = null
466    }
467    if (stop.done) return null
468    if (outage(r)) {
469      await pause($, backoff(++failures))
470      continue
471    }
472    failures = 0
473    let reply: any = null
474    try {
475      reply = r!.ok ? JSON.parse(r!.text.trim() || '{}') : null
476    } catch {
477      reply = null
478    }
479    if (!reply) return null
480    if (reply.pending) continue
481    const decision = reply.hookSpecificOutput?.permissionDecision
482    if (decision === 'deny' || (decision === 'allow' && reply.hookSpecificOutput.updatedInput?.answers)) return reply
483    return null
484  }
485  return null
486}
487
488// Poll the server for a remote answer to permission prompt `e` (a classic
489// PermissionRequest) until one comes: the hook's `{ decision }`, or null when
490// the remote side is out (settled at the terminal, the seat's row gone, the
491// server unreachable). Claude Code shows its dialog while this runs (measured
492// on 2.1.292), and an answer returned later closes it.
493async function decideRemotely($: any, e: any): Promise<any | null> {
494  const url = `${cfg!.url}/api/hooks/seat/${enc(cfg!.title)}/permissionrequest`
495  let requestId: string | null = null
496  // Nothing here learns that the prompt was settled at the terminal while the
497  // server is out, so an outage is waited out for a while, not for ever.
498  const giveUpAt = (await $.clock.now()) + PERMISSION_OUTAGE_MS
499  let failures = 0
500  for (;;) {
501    let r: { status: number; ok: boolean; text: string } | null = null
502    try {
503      const body = { tool_name: e.tool_name, tool_input: e.tool_input, permission_suggestions: e.permission_suggestions, agent_id: e.agent_id, wait: QUESTION_POLL_S,
504        ...(requestId ? { request_id: requestId } : {}) }
505      r = await $.http.fetch(url, { method: 'POST', headers: headers(), body: JSON.stringify(body) })
506    } catch {
507      r = null
508    }
509    if (outage(r)) {
510      if ((await $.clock.now()) >= giveUpAt) return null
511      await pause($, backoff(++failures))
512      continue
513    }
514    failures = 0
515    let reply: any = null
516    try {
517      reply = r!.ok ? JSON.parse(r!.text.trim() || '{}') : null
518    } catch {
519      reply = null
520    }
521    if (!reply) return null
522    if (reply.pending && typeof reply.request_id === 'string') {
523      requestId = reply.request_id
524      continue
525    }
526    const decision = reply.hookSpecificOutput?.decision
527    return decision?.behavior === 'allow' || decision?.behavior === 'deny' ? { decision } : null
528  }
529}
530
531// The question was answered at the terminal: end the poll still waiting for
532// it at the server, so the app no longer offers it.
533async function withdrawQuestion($: any, toolUseId: string): Promise<void> {
534  const sent = $.http
535    .fetch(`${cfg!.url}/api/hooks/seat/${enc(cfg!.title)}/pretooluse`, {
536      method: 'POST',
537      headers: headers(),
538      body: JSON.stringify({ tool_name: 'AskUserQuestion', tool_use_id: toolUseId, withdraw: true }),
539    })
540    .catch(() => null)
541  await within($, SERVER_WAIT_MS, sent, null)
542}
543
544// POST the registration; true when the server has the seat. Idempotent: the
545// server reuses the row with this Claude session id.
546async function registerSeat($: any): Promise<boolean> {
547  if (!cfg || !registration) return false
548  try {
549    const r = await $.http.fetch(`${cfg.url}/api/sessions`, { method: 'POST', headers: headers(), body: JSON.stringify(registration) })
550    const created = r.ok ? JSON.parse(r.text) : null
551    const id = created?.id ?? created?.session?.id ?? null
552    if (id == null) return false
553    row = id
554    return true
555  } catch {
556    return false
557  }
558}
559
560// Registration that failed (no server yet): retry with a growing delay, and
561// start the inbox once it lands. The session works as stock meanwhile.
562function registerUntilUp($: any, wait: number) {
563  $.clock.after(wait, async () => {
564    if (await registerSeat($)) goOnline($)
565    else registerUntilUp($, Math.min(wait * 2, REGISTER_RETRY_MAX_MS))
566  })
567}
568
569// The seat is registered: show it, report ready for cv_send, start the inbox.
570function goOnline($: any) {
571  onlineStatus($)
572  pending.push({ type: 'idle' })
573  flush($)
574  poll($, ++pollGen, 'SessionStart')
575}
576
577// Send what is pending now: a question must reach the server before its
578// hold starts, or the app sees the hold with no question to answer.
579async function flushNow($: any) {
580  while (pending.length && row != null && cfg) {
581    const batch = pending.splice(0, MAX_BATCH)
582    await $.http.fetch(`${cfg.url}/api/sessions/${row}/mirror`, {
583      method: 'POST', headers: headers(), body: JSON.stringify({ messages: batch }),
584    }).catch(() => {})
585  }
586}
587
588// Mirror what is pending, batched over FLUSH_MS. A lost batch only thins the
589// mirror; it never touches the session.
590function flush($: any) {
591  if (flushScheduled || row == null || !cfg) return
592  flushScheduled = true
593  $.clock.after(FLUSH_MS, async () => {
594    flushScheduled = false
595    while (pending.length) {
596      const batch = pending.splice(0, MAX_BATCH)
597      await $.http.fetch(`${cfg!.url}/api/sessions/${row}/mirror`, {
598        method: 'POST', headers: headers(), body: JSON.stringify({ messages: batch }),
599      }).catch(() => {})
600    }
601  })
602}
603
604// Live text for the apps, as the patched runtime streams it: the step's
605// chunks rebuilt as the API's stream events (content_block_start / _delta /
606// _stop, message_stop). Pieces of one block that arrive within a flush window
607// are merged into one delta, so a response is a few rows, not one per token;
608// the finished message is mirrored whole by session.append as before.
609function streamEvent(event: Record<string, unknown>) {
610  pending.push({ type: 'stream_event', event })
611}
612
613function streamDelta(index: number, kind: string, field: string, text: string) {
614  if (!text) return // thinking arrives empty where the build does not show it
615  const last = pending[pending.length - 1] as any
616  const d = last?.type === 'stream_event' && last.event.type === 'content_block_delta' && last.event.index === index ? last.event.delta : null
617  if (d && d.type === kind) d[field] += text
618  else streamEvent({ type: 'content_block_delta', index, delta: { type: kind, [field]: text } })
619}
620
621function streamChunk(c: any, open: Set<number>) {
622  const start = (block: Record<string, unknown>) => {
623    if (open.has(c.index)) return
624    open.add(c.index)
625    streamEvent({ type: 'content_block_start', index: c.index, content_block: block })
626  }
627  if (c.kind === 'text') {
628    start({ type: 'text', text: '' })
629    streamDelta(c.index, 'text_delta', 'text', c.text)
630  } else if (c.kind === 'thinking') {
631    start({ type: 'thinking', thinking: '' })
632    streamDelta(c.index, 'thinking_delta', 'thinking', c.text)
633  } else if (c.kind === 'tool') {
634    start({ type: 'tool_use', id: c.id, name: c.name, input: {} })
635  } else if (c.kind === 'input') {
636    streamDelta(c.index, 'input_json_delta', 'partial_json', c.json)
637  } else if (c.kind === 'stop') {
638    for (const i of open) streamEvent({ type: 'content_block_stop', index: i })
639    open.clear()
640    streamEvent({ type: 'message_delta', delta: { stop_reason: c.stopReason } })
641  }
642}
643
644export const register: Register = (on, options) => {
645  on('session.start', async ($, e, next) => {
646    // The patched runtime already connects this seat.
647    if (clean(await $.env.get('CLAUDIVERSE_PATCHED_RUNTIME'))) return next(e)
648
649    // Literal names: the validator lists exactly which variables a mod reads.
650    // A launcher's variables win over the plugin's options.
651    const url = clean(await $.env.get('CLAUDIVERSE_URL')) || clean(options.server_url as string | undefined)
652    const token = clean(await $.env.get('CLAUDIVERSE_TOKEN')) || clean(options.seat_token as string | undefined)
653    if (!url || !token) return next(e)
654    const sessionId = await $.session.id()
655    const folder = (e.cwd.split('/').filter(Boolean).pop() || 'seat').replace(/[^A-Za-z0-9._-]+/g, '-')
656    const pinned = clean(await $.env.get('CLAUDIVERSE_TITLE'))
657    titlePinned = !!pinned
658    // A plain `claude --resume` of a conversation that already has a seat keeps
659    // that seat's name and placement: the row is reused by session id, and a
660    // derived "<folder>-<id>" title and origin "plain" overwrote a named seat's
661    // (unifi-basement-ap became vm_management-6830, 2026-10-07).
662    const existing = pinned ? null : await seatOfSession($, url, token, sessionId)
663    const title = pinned || existing?.title || `${folder}-${sessionId.slice(0, 4)}`
664    cfg = {
665      url: url.replace(/\/$/, ''),
666      token,
667      title,
668      host: clean(await $.env.get('CLAUDIVERSE_HOST')),
669      fleet: clean(await $.env.get('CLAUDIVERSE_FLEET')),
670      origin: clean(await $.env.get('CLAUDIVERSE_ORIGIN')),
671    }
672    if (!cfg.host) {
673      const r = await $.process.run(['hostname']).catch(() => null)
674      cfg.host = r?.stdout.trim() || undefined
675    }
676
677    const v = await $.session.version()
678    const mod = await modVersion($)
679    registration = {
680      title: cfg.title,
681      claude_session_id: sessionId,
682      working_directory: e.cwd,
683      client_version: `${v.version} (Claude Code) [claudiverse-mod${mod ? ` ${mod}` : ''}]`,
684      host: cfg.host,
685      fleet: cfg.fleet,
686      // No launcher named or placed this session: a `claude` typed in a
687      // terminal. The server gives "plain" seats basic access by default
688      // (Sessions.Access); the operator can grant more from the apps.
689      // A resumed seat's origin is left as it was (absent is no news to the server).
690      origin: cfg.origin ?? (titlePinned ? 'manual' : existing ? undefined : 'plain'),
691      type: 'sidecar',
692      // Set by a host agent starting a profile (cv-spawn --profile): the
693      // server then fills fleet, notify and origin from the profile.
694      profile_id: clean(await $.env.get('CLAUDIVERSE_PROFILE')),
695      profile_revision: clean(await $.env.get('CLAUDIVERSE_PROFILE_REVISION')),
696      tmux_session: clean(await $.env.get('CLAUDIVERSE_TMUX')),
697    }
698
699    await $.command.register({ name: 'claudiverse', description: "Shows this seat's link to the claudiverse server" })
700    // Registration slower than SERVER_WAIT_MS does not hold up the session:
701    // it goes on starting offline, and that same request settles the seat
702    // when it answers, so no second registration races it.
703    const registered = registerSeat($)
704    if (await within($, SERVER_WAIT_MS, registered, false)) {
705      goOnline($)
706    } else {
707      $.ui.status('claudiverse offline')
708      registered.then((ok) => (ok ? goOnline($) : registerUntilUp($, REGISTER_RETRY_MS)))
709    }
710    return next(e)
711  })
712
713  // Main-conversation rows only: a subagent's rows carry an agentId.
714  on('session.append', async ($, e, next) => {
715    const stored = await next(e)
716    if (e.agentId === undefined && e.message.type === 'user' && promptQueue.length)
717      promptsEntered($, userText(stored?.message?.content ?? e.message.content))
718    const mirrored = row != null && (e.message.type === 'user' || e.message.type === 'assistant')
719    // When the row was stored: the apps' message times and day dividers. The
720    // append carries no time of its own, and the server's arrival time is late
721    // by the flush wait, or by a whole outage for rows queued through one.
722    const timestamp = mirrored ? new Date(await $.clock.now()).toISOString() : undefined
723    if (row != null && e.agentId === undefined && (e.message.type === 'user' || e.message.type === 'assistant')) {
724      // An assistant row carries what the apps show about the seat — the model
725      // that answered and the effort it ran at — as the patched runtime
726      // mirrors them; without them the app fell back to a stale effort (it
727      // showed "medium" for a seat at "high"). The row itself has neither:
728      // the model is its origin's, the effort the main loop's last request's.
729      const model = e.origin?.kind === 'model' ? e.origin.model : undefined
730      pending.push({
731        type: e.message.type,
732        uuid: stored?.uuid ?? e.uuid,
733        timestamp,
734        isMeta: e.message.isMeta || undefined,
735        effort: e.message.type === 'assistant' ? lastEffort : undefined,
736        message: { role: e.message.role, content: stored?.message?.content ?? e.message.content, ...(model ? { model } : {}) },
737      })
738      flush($)
739    } else if (row != null && e.agentId !== undefined && (e.message.type === 'user' || e.message.type === 'assistant')) {
740      // An agent's row: its own type, so main's transcript, busy/idle and
741      // live reply stay main's (the patched runtime mixed a fork's rows into
742      // main's). The inner row has main's shape, uuid included.
743      const model = e.origin?.kind === 'model' ? e.origin.model : undefined
744      pending.push({
745        type: 'agent_message',
746        agent_id: e.agentId,
747        timestamp,
748        message: {
749          type: e.message.type,
750          uuid: stored?.uuid ?? e.uuid,
751          timestamp,
752          isMeta: e.message.isMeta || undefined,
753          message: { role: e.message.role, content: stored?.message?.content ?? e.message.content, ...(model ? { model } : {}) },
754        },
755      })
756      flush($)
757    }
758    return stored
759  })
760
761  // A new agent: a fork, a subagent, a teammate. tool_use_id ties it to the
762  // Agent call in its parent's transcript.
763  // A background shell (run_in_background, Ctrl+B, or a timeout that moved it)
764  // and a monitor are in the apps' list the moment they start, not only when
765  // main's turn ends.
766  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
767    const r: any = await next(e)
768    const id = r?.result?.backgroundTaskId
769    if (row != null && typeof id === 'string') {
770      background.set(id, { id, type: 'shell', status: 'running', description: e.description, command: e.command, started_at: await nowIso($) })
771      sendBackground($)
772    }
773    return r
774  })
775
776  on('tool.call', { tool: 'Monitor' }, async ($, e, next) => {
777    const r: any = await next(e)
778    const id = r?.result?.taskId
779    if (row != null && typeof id === 'string') {
780      background.set(id, { id, type: 'monitor', status: 'running', description: e.description, command: e.command ?? e.ws?.url, started_at: await nowIso($) })
781      sendBackground($)
782    }
783    return r
784  })
785
786  on('tool.call', { tool: 'TaskStop' }, async ($, e, next) => {
787    const r: any = await next(e)
788    const id = e.task_id ?? e.shell_id
789    if (row != null && typeof id === 'string' && !r?.deny && !r?.isError && background.delete(id)) sendBackground($)
790    return r
791  })
792
793  // A background task's completion notice reaches main as a prompt (into the
794  // running turn, or starting one): the task leaves the apps' list then. Up to
795  // 0.12.0 it stayed until main's next turn ended, and showed as running after
796  // it had finished (an interrupted foreground job that went on in the
797  // background, measured 2026-10-15).
798  on('prompt.submit', async ($, e: any, next) => {
799    const r = await next(e)
800    if (row != null && e.origin?.kind === 'task-notification' && typeof e.text === 'string') {
801      const n = taskNotice(e.text)
802      if (n && TERMINAL.has(n.status)) {
803        finishedTasks.add(n.id)
804        if (background.delete(n.id)) sendBackground($)
805      }
806    }
807    return r
808  })
809
810  // What is still in flight as main's turn ends, by the engine's own count.
811  // A task's start time is the one its call recorded here, if it was seen.
812  on('classic.Stop', async ($, e: any, next) => {
813    const r = await next(e)
814    if (row != null && Array.isArray(e.background_tasks)) {
815      const startedAt = new Map([...background].map(([id, t]) => [id, t.started_at]))
816      background.clear()
817      for (const t of e.background_tasks) {
818        if (finishedTasks.has(t.id)) continue
819        background.set(t.id, {
820          id: t.id, type: t.type, status: t.status, description: t.description, command: t.command,
821          agent_type: t.agent_type, server: t.server, tool: t.tool, name: t.name, started_at: startedAt.get(t.id),
822        })
823      }
824      sendBackground($)
825    }
826    return r
827  })
828
829  on('agent.spawn', async ($, e, next) => {
830    const r = await next(e)
831    if (row != null && r?.agentId) {
832      agentSpawns.set(r.agentId, { fork: e.fork, background: e.background })
833      pending.push({
834        type: 'agent_started',
835        agent_id: r.agentId,
836        agent_type: e.subagentType,
837        description: e.description,
838        name: e.name,
839        fork: e.fork,
840        background: e.background,
841        parent_agent_id: e.parentAgentId,
842        tool_use_id: e.tool_use_id,
843      })
844      flush($)
845      syncAgents($)
846    }
847    return r
848  })
849
850  // 007: the question is answered here or in claudiverse, whichever comes
851  // first. The terminal dialog opens at once (next) while the server is
852  // polled for a remote answer; returning while next is pending aborts the
853  // dialog, and an answer at the terminal withdraws the remote question. A
854  // seat nobody watches waits for the app; a person at the terminal is never
855  // locked out, and a server that is out leaves the dialog to decide alone.
856  on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
857    if (row == null || !cfg) return next(e)
858    await flushNow($)
859    onlineStatus($, 'question sent: answer here or in claudiverse')
860    const stop = { done: false }
861    const local = next(e).then(
862      (result) => ({ result }),
863      (error) => ({ error }),
864    )
865    const remote = answerRemotely($, e, stop).then((reply) => (reply ? { reply } : local))
866    const first: any = await Promise.race([local, remote])
867    stop.done = true
868    onlineStatus($, '')
869    if (!('reply' in first)) {
870      await withdrawQuestion($, e.tool_use_id)
871      if ('error' in first) throw first.error
872      return first.result
873    }
874    const out = first.reply.hookSpecificOutput
875    if (out.permissionDecision === 'deny') return { deny: out.permissionDecisionReason || 'declined via claudiverse' }
876    // Answered remotely: the hook answers the call itself, and returning
877    // aborts the dialog beneath. Core records this as the tool's result.
878    return {
879      result: {
880        questions: e.questions,
881        answers: out.updatedInput.answers,
882        ...(out.updatedInput.annotations ? { annotations: out.updatedInput.annotations } : {}),
883      },
884    }
885  })
886
887  // A permission prompt is offered in claudiverse too, while its dialog shows
888  // here: the apps can allow or deny it, and an answer at the terminal settles
889  // it there (the server sees the tool's result in the mirror).
890  // An AskUserQuestion's own dialog is a permission prompt too; it is not
891  // relayed, because its question already is (tool.call above). Relayed, the
892  // apps showed the question AND a card asking to allow it (MEASURED
893  // 2026-10-10 by the operator on Failover's three-question ask).
894  on('classic.PermissionRequest', async ($, e, next) => {
895    if (row == null || !cfg || e.tool_name === 'AskUserQuestion') return next(e)
896    await flushNow($)
897    const remote = await decideRemotely($, e)
898    return remote ?? next(e)
899  })
900
901  // 009: tell the server the context was dropped.
902  on('session.compact', async ($, e, next) => {
903    const r = await next(e)
904    if (row != null) {
905      pending.push({ type: 'compact' })
906      flush($)
907    }
908    return r
909  })
910
911  // 005: a command of our own, answered with no turn.
912  // /rename <name>: the seat follows the session's new name. Re-registering on
913  // the same Claude session id updates this row's title; the inbox is keyed by
914  // title, so the poll restarts under the new one. A launcher's
915  // CLAUDIVERSE_TITLE wins (it is re-applied on every restart, so a rename
916  // would revert), as on the patched runtime. A bare /rename (Claude picks
917  // the name) is not followed: the mod cannot read the name it picked.
918  on('command.run', { command: 'rename' }, async ($, e, next) => {
919    const r = await next(e)
920    const name = (e.args || '').trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 64)
921    if (!cfg || !registration || !name || name === cfg.title) return r
922    if (titlePinned) {
923      $.ui.log(`claudiverse: the seat keeps its launch title ${cfg.title} (CLAUDIVERSE_TITLE)`)
924      return r
925    }
926    cfg.title = name
927    registration.title = name
928    if (await registerSeat($)) {
929      onlineStatus($)
930      poll($, ++pollGen)
931    }
932    return r
933  })
934
935  on('command.run', { command: 'claudiverse' }, async () => ({
936    text: cfg
937      ? `claudiverse: seat ${cfg.title} · session ${row ?? 'not registered'} · ${cfg.url}` +
938        (cfg.host ? ` · host ${cfg.host}` : '') + (cfg.fleet ? ` · fleet ${cfg.fleet}` : '')
939      : 'claudiverse: not configured (CLAUDIVERSE_URL, CLAUDIVERSE_TOKEN and CLAUDIVERSE_TITLE are needed)',
940  }))
941
942  // The main loop's model requests only (a subagent's are not the seat's
943  // conversation). Every chunk is passed on unchanged; mirroring never
944  // touches the session, and a failure in it only thins the live view.
945  on('turn.step', async function* ($, e, next) {
946    if (e.agentId === undefined) lastEffort = e.effort
947    if (row == null || e.agentId !== undefined) return yield* next(e)
948    const open = new Set<number>()
949    streamEvent({ type: 'message_start', message: { role: 'assistant', model: e.model, content: [] } })
950    for await (const c of next(e)) {
951      try {
952        streamChunk(c, open)
953        flush($)
954      } catch {}
955      yield c
956    }
957    for (const i of open) streamEvent({ type: 'content_block_stop', index: i })
958    streamEvent({ type: 'message_stop' })
959    flush($)
960  })
961
962  // The process is leaving (/exit, ctrl+c, logout, a signal): end this row
963  // now. A seat with no socket otherwise reads "running" until the server's
964  // liveness check gives up on it (~3 min), next to the seat that replaced
965  // it. Not on a /clear or an in-session resume: the process goes on (and no
966  // session.start follows a /clear), so the row must stay. Within
967  // session.end's short budget: what is pending, then the frame.
968  on('session.end', async ($, e, next) => {
969    if (row != null && cfg && e.reason !== 'clear' && e.reason !== 'resume') {
970      pending.push({ type: 'session_ended', reason: e.reason, exit_code: 0 })
971      await flushNow($).catch(() => {})
972      row = null
973    }
974    return next(e)
975  })
976
977  // Main's turn only. Since 2.1.299 turn.start fires for a subagent's or a
978  // teammate's turn too (e.agentId set), and turn.complete keeps main's turnId
979  // through an agent's end: an agent's start here aimed the app's Interrupt at
980  // the agent, and one starting after main's turn left a stale turnId, so the
981  // seat never reported idle again until its next turn.
982  on('turn.start', async ($, e, next) => {
983    if (e.agentId === undefined) {
984      turnId = e.turnId
985      turnError = null
986      promptsEntered($, e.text)
987    }
988    return next(e)
989  })
990
991  // The API error ending a turn: kept for that turn's turn_complete. A
992  // subagent's runs end in a turn.complete of their own, never main's.
993  on('classic.StopFailure', async ($, e: any, next) => {
994    if (e.agent_id === undefined) turnError = { error: e.error, text: e.last_assistant_message }
995    return next(e)
996  })
997
998  on('turn.complete', async ($, e, next) => {
999    const r = await next(e)
1000    // An agent's turn ending is the agent's: up to 0.8.8 a fork finishing a
1001    // turn told the server main was idle and dropped main's turnId, so the
1002    // app's Interrupt could no longer reach a main turn still running.
1003    if (e.agentId !== undefined) {
1004      if (row != null) {
1005        pending.push({ type: 'agent_turn_complete', agent_id: e.agentId })
1006        flush($)
1007        syncAgents($)
1008      }
1009      return r
1010    }
1011    turnId = null
1012    if (afterAbort.length) releaseAfterAbort($)
1013    else if (promptQueue.length) {
1014      // Claude starts a queued prompt as soon as main is idle; one still
1015      // listed after QUEUE_STALE_MS of idle never started.
1016      $.clock.after(QUEUE_STALE_MS, () => {
1017        if (turnId || afterAbort.length) return
1018        const stale = promptQueue.filter((p) => p.state === 'queued')
1019        if (!stale.length) return
1020        promptQueue = promptQueue.filter((p) => p.state !== 'queued')
1021        sendQueue($)
1022      })
1023    }
1024    // A turn that died on an API error (the pool empty, the stream cut) is
1025    // idle all the same, and says why, so the row reads truthfully and the
1026    // server's reject-busy delivery (a continue, a cv_send) reaches it.
1027    const failed = e.reason === 'error' ? { error: turnError?.error ?? 'unknown', error_text: turnError?.text } : {}
1028    turnError = null
1029    if (row != null) {
1030      pending.push({ type: 'turn_complete', reason: e.reason, ...failed }, { type: 'idle' })
1031      flush($)
1032    }
1033    return r
1034  })
1035}
1036