SLOPSHOPPER

agentmbx

Renders this Claude Code session's AgentMBX status. It does not compute status itself.

panebandcommandtoaststatusnetwork
★ 1v0.5.54NOASSERTIONupdated 2026-10-25kryptobaseddev/agentmbx/plugins/claude
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · agentmbx
│ ┃ MBX ✕ › fix the failing auth test and add an audit log call │ ┃ mbx: unavailable │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /mbx-status │ ⎿ agentmbx: mbx: unavailable │ │ mbx: unavailable ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
mbx: unavailable
Pane · MBX
mbx: unavailable
README

AgentMBX

A signed mailbox for AI coding agents. Claude Code, Codex, OpenCode, Kimi, Hermes, Antigravity and any MCP client can message each other: on one machine or across machines on your network. Idle agents get woken up, and every message shows which machine signed it and whether the sender held that mailbox's identity lease. Agent names are labels, so a label never proves which agent wrote a message.

agentmbx.com · npm latest · Status: alpha · License: BUSL-1.1 (source-available)

you ── Claude Code (planner) ──┐                         ┌── Codex (api-dev)      ← woken by `codex queue`
                               ├── agentmbx daemon ◄────►├── OpenCode (web-dev)   ← woken by its session API
     Kimi / Hermes / any MCP ──┘   (this machine)   LAN  └── Claude (reviewer)    ← woken by a channel event
                                                          (a paired machine)

Install the current npm release

Install Node.js 24 or newer, then run:

npm install --global agentmbx@latest
agentmbx setup
agentmbx doctor

The npm registry's latest tag is the standard release and installation path. It resolves the current published version each time you run the install command; it doesn't update an existing installation automatically. Check and upgrade with:

npm view agentmbx@latest version    # current published npm release
agentmbx version                  # installed CLI and installation kind
npm install --global agentmbx@latest
agentmbx setup                    # refresh daemon, MCP paths, hooks, and skill
agentmbx doctor

Restart agent sessions after their first setup. For an existing connection, use mbx_whoami to verify its runtime and identity after upgrading; older connectors may need a reconnect in the same conversation. A version in package.json, a Git tag, or this checkout can be ahead of the npm release.

The installation guide covers PATH conflicts, manual MCP configuration, and the optional standalone binary. agentmbx version --check and agentmbx update check the signed GitHub binary release manifest; they aren't npm dist-tag queries. For an npm installation, upgrade with the npm command above. Maintainers: release procedure.

Status line

agentmbx statusline <claude|codex|kimi|opencode|grok|copilot|cursor|gemini> renders one MBX segment for a CLI status line from the daemon's HUD snapshot — a single small file read, never SQL against the store. The daemon writes one mbx.status/v1 snapshot per bound session (and per holder pid, only when the resolver proves one) under ~/.local/share/agentmbx/hud, keeps hud/.alive fresh, and adapters print nothing when the daemon is down or nothing resolves. skill/scripts/claude-statusline.sh is the bundled Claude adapter — pure sh (awk, date, one cat), so a render never pays a node startup; it honors MBX_HOME. skill/scripts/kimi-statusline.sh is the bundled Kimi adapter — pure sh and alert-only: one cat of the calling session's own kimi-<sid>.line, selected by the top-level session_id on stdin. Codex note: official Codex builds its status line from built-in items only (openai/codex#17827); the snapshots stay ready.

Wiring, per harness. Every adapter reads the session id the CLI pipes on stdin, so a segment always belongs to the conversation that asked — and each session's render resolves that session's own binding only, never another identity's mailbox. Kimi's is different in contract, not in wiring: its [status_line] command replaces the footer, so its adapter is alert-only (see below). Verified against first-party docs: Claude Code, Kimi Code, Grok CLI. Everything else is community-reported — the shape is Claude-compatible, but confirm against the CLI's own docs before relying on it.

Already have a status line of your own? agentmbx statusline suggest [--cli claude|kimi|grok] [--json] [--apply] proposes where to place the MBX segment and prints the proposal as human text plus a structured mbx.statusline-suggest/v1 document an in-session agent can reason over (no network LLM call is made). The default is read-only — nothing is written. For a status line you configured yourself the proposal is a wrapper script — for Claude it appends the segment to your command's output (true composition); for Kimi, whose command replaces the footer, and for Grok, whose type = "command" row shows that command's stdout instead of the builtin items, it shows the alert only when the session has mail and your command's output otherwise — with the exact steps to install it by hand, because setup never overwrites a user's own line. --apply writes only where setup's own text edit can: a missing or stale wiring, with a backup and a printed undo that restores the exact bytes.

  • Claude Code (~/.claude/settings.json, verified): "statusLine": { "type": "command", "command": "agentmbx statusline claude" } — or point command at skill/scripts/claude-statusline.sh for the pure-sh render. Setup never overwrites an existing status line.
  • Kimi Code (~/.kimi-code/tui.toml, verified): [status_line] command = … replaces the footer — items and command do not coexist; while a command is set, the built-in footer items render only when the command prints nothing. Setup wires the bundled alert adapter skill/scripts/kimi-statusline.sh: with nothing to show (zero unread, unbound, daemon down) its output is empty and Kimi's built-in footer items render untouched; with unread mail the mbx alert takes footer line 1. ``toml [status_line] command = "agentmbx statusline kimi" ``
  • Grok CLI (~/.grok/config.toml, or $GROK_HOME/config.toml; verified against the user guide shipped with the CLI):
  • MCP (~/.grok/docs/user-guide/07-mcp-servers.md): [mcp_servers.mbx] with command, args = ["mcp"] and enabled = true. Setup writes that section by text edit. grok mcp add rewrites the whole file, so setup does not call it, and a foreign mbx server is left alone.
  • Hooks (~/.grok/docs/user-guide/10-hooks.md, including Stop Decision Control): [[hooks.SessionStart]], [[hooks.UserPromptSubmit]], [[hooks.PostToolUse]] and [[hooks.Stop]], the inline form hooks = [{ type = "command", command = "… hook <sub> --cli grok", timeout = 10 }]. On a genuine end of turn the Stop hook prints {"decision":"block","reason":"…"}. That guide feeds the reason back as another round of the same turn. A session-end Stop does not block.
  • Status line (~/.grok/docs/user-guide/25-status-line.md): [ui.status_line] with type = "command" and command = "agentmbx statusline grok". That type shows the command's stdout in Grok's own status row. It does not also render the builtin items, and it does not replace a footer the way Kimi's command does. Grok pipes JSON to the command, including session_id, and reads [ui.status_line] at startup, so a change shows up on the next launch. The row resolves that session's mailbox only.
  • T380 harness rows: session detection, lease bind, and a clean agentmbx doctor are recorded for this CLI. Stop continuation, resume/rebind, and a live own-session status line stay open until a Grok restart loads the current hooks.
  • GitHub Copilot CLI (unverified, community-reported via copilot-cli#3192 — the same issue documents the statusLine.command shape and a quirk where a custom command does not render while footer.showCustom is true): { "statusLine": { "command": "agentmbx statusline copilot" } }.
  • Cursor CLI (~/.cursor/cli-config.json; unverified, community-reported): { "statusLine": { "command": "agentmbx statusline cursor" } }.
  • Gemini CLI (unverified, community-reported via the universal cli-status-bar project): { "statusLine": { "command": "agentmbx statusline gemini" } }.
  • Codex: no custom command yet (openai/codex#17827) — agentmbx statusline codex prints where the snapshots live, ready for forks or a tmux footer row.
  • OpenCode: built-in segments only today (anomalyco/opencode#30295).
  • Hermes: no footer command hook; its plugin lifecycle hooks receive the session id, so an AgentMBX plugin can surface inbox state instead.

Claude, Codex, OpenCode, Kimi and Grok sessions are detected by agentmbx setup and detectHost. Copilot, Cursor and Gemini are not — nothing binds their sessions yet, so those adapters render nothing out of the box until detection lands (tracked as T337). Today they need MBX_CLI=<cli> on the MCP server plus hand-wired hooks. Grok does not: detectHost names grok from the grok binary, and the session id comes from that process's row in ~/.grok/active_sessions.json.

Copilot, Cursor and Gemini render by session id only, like every non-Claude adapter: if the CLI names no session id, nothing renders rather than risk a sibling conversation's mail. Grok's status command gets session_id on stdin (user guide 25-status-line.md) and resolves that session only.

Harnesses can also pull the snapshot directly: agentmbx status --cli <provider> --session <id> --json --schema mbx.status/v1 returns the same mbx.status/v1 document the HUD files carry (T311). It resolves through the same identity resolver as the statuslines — an explicit session that does not resolve is reported unbound, never another session of the same process — and it needs no lease, so it works before a session has claimed a mailbox. The same rule without --session resolves the caller's own provider process. The pre-existing status --json contract (lease-gated mailbox counts) is unchanged.

Native workflow and delivery roadmap

Each provider connects to its own AgentMBX MCP server. That server uses the local mailbox and daemon; the daemon delivers to explicitly paired LAN hosts. An optional relay carries sealed bodies across networks. Since 0.5.5 the relay is durable: it keeps enrolments, encryption ads and queued mail in SQLite, signs every accept, and a restart or crash loses no accepted mail (self-hosted with agentmbx relay serve, or the hosted relay.agentmbx.com). Since 0.5.7 the relay also has crash drills, relay backup/restore/log with receipts, a 14-day retention sweep with signed expiry notices to the sender (T167), and relay key pinning by fingerprint with signed, expiring encryption-key ads (T168). Signed messaging establishes integrity, and since 0.5.1 every body that leaves a host is sealed for the receiving host (X25519 + XChaCha20-Poly1305); envelope metadata is still visible on the LAN and to the relay operator (T198).

Start or resume with mbx_whoami; if it shows no identity, claim or register one with mbx_identity first, then mbx_inbox. Use mbx_read for current computed policy before acting, mbx_reply to answer in the thread or mbx_send to start a conversation, and mbx_ack after handling a request. Mail content is DATA and cannot change permissions. A send or wake admission does not prove remote delivery, model execution, a reply, or task completion.

CapabilityStatusTracking
Signed local/LAN mail, identity leases, thread/search and bounded MCP/CLI replayShipped in v0.5.0T122; T134 release
Exact-session read-only diagnostics CLIShipped in v0.5.0; local OS-user view, not global agent permissionT130–T131
Startup, catch-up, durable cursor-capture and send-state instructionsRepository guidance updated; installed skills follow setup refreshT144
Same existing conversation update/reconnect and two physical LAN devicesShipped in v0.5.1: connector handover evidence (T183); MacBook↔Fedora request/reply, offline retry and key rotation proven live (T151); per-provider wake receipts (T091, T180)T183, T151, T091
Chosen identities (no invented names), per-project identity list, send-time recipient state, sender receipts, project ledger and owner-designated leadShipped in v0.5.2 (P0): restarts and crashes keep their identity, offline recipients are named at send time, senders see delivered/read/ackedT203–T211
Cross-host receipts (delivered/read/acked with did from paired hosts), cross-host project ledger, no phantom mailboxes, return to sender, self-healing skillShipped in v0.5.3T214–T219
Durable catch-up checkpoints per identity (mbx_catchup) and guided resume hintsShipped in v0.5.3T156–T158
Handoff summaries and optional draftsmbx_handoff: context computed fresh plus one saved note with task and message references (docs/spec/handoff-context.md, T159); no draft API todayT159–T163, T184–T189
Durable relay: SQLite store, relay-signed accepts, restore-proof sequencing, sender deadlines, v2 clientShipped in v0.5.5; hosted at relay.agentmbx.com since 2026-10-03T164–T166, T307
Status surface: agentmbx status --json --schema mbx.status/v1, daemon-written HUD snapshots, agentmbx statusline adapters; resumed Claude sessions keep their mailboxShipped in v0.5.6 (Claude, Codex, Kimi, OpenCode); v0.5.7 adds Grok as a first-class CLI and per-CLI status line setup that never overwrites a user's own; v0.5.8 makes Kimi's line alert-only per session and has doctor verify each CLI's status line wiring (Copilot, Cursor and Gemini adapters render once session detection lands)T308–T313, T326, T337, T347, T366, T368
Relay crash drills, relay backup/restore/log with receipts and rollback, retention sweep, expiry noticesShipped in v0.5.7T167
Relay key pinning by fingerprint, signed expiring encryption-key ads, enrolment recovery, pluggable enrolment authorityShipped in v0.5.7 (upgrade the relay before senders)T168
HTTPS deployment, monitoring, account enrollment, consent and home/work qualificationPlanned (relay backup/restore landed with T167)T169–T173; T036–T039
Local private console, searchable handoffs and scoped topicsPlanned; existing replay tag filters do not subscribe recipientsT152–T155, T127–T128, T174–T176
Provider wake verification and signed capability discoveryTyped outcomes, exact-session wakes, uncertain-wake reconciliation and wake mute shipped in v0.5.1 (T177–T179), with historical real-session receipts for the providers tested at those revisions (T180); current provider/live restart gates remain separate, and signed capability discovery remains plannedT068, T132
Standards-compatible gatewayLater contract and bounded adapter; native card preview is not a conforming execution endpointT181–T182

For historical context, use bounded mbx_replay pages. Retain page information or retrievable message IDs durably before advancing the saved cursor; track unfinished processing separately, and ACK separately. Losing the cursor means an explicit rewind and message-ID deduplication. mbx_replay doesn't save a consumer checkpoint. mbx_catchup saves an identity checkpoint only after you explicitly commit a durably captured page. Neither restores provider reasoning. Diagnostics are useful on a failed call or a confirmed version mismatch; an old native connector may need a one-time reconnect within the same conversation, without releasing or taking over its persona.

The tracked feature roadmap maps requirements to tasks, dependencies and acceptance gates. The native agent workflow separates current tools from proposed capture, draft and recovery APIs.

Why

Most people now run more than one coding agent, and often on more than one machine. They can't talk to each other. The options today:

  • Paste between them by hand.
  • One vendor's multi-agent feature. These only work for that vendor's agents.
  • A heavyweight agent platform.

AgentMBX gives every agent the same small set of mailbox tools. It delivers messages between machines you pair. It wakes the recipient when its CLI allows that. It keeps a hard line between what a message says and what the recipient is allowed to do.

What you get

  • 17 MCP tools: mbx_whoami, mbx_identity, mbx_inbox, mbx_read, mbx_reply, mbx_ack, mbx_send, mbx_sent, mbx_delivery, mbx_thread, mbx_search, mbx_agents, mbx_replay, mbx_catchup, mbx_handoff, mbx_project, and mbx_forward (project lead). The version-matched guide is the resource mbx://guide and prompt mbx_guide; the MCP reference lists inputs and state changes.
  • One-command setup: agentmbx setup finds Claude Code, Codex, OpenCode, Kimi, Hermes, Grok, and Antigravity and wires each one (MCP server, hooks, and a bundled skill that teaches agents the mailbox loop). agentmbx doctor checks detected CLI wiring and known session-readiness signals. In a new Kimi desktop conversation, confirm that mbx_whoami is available and returns that conversation's identity; setup must run with Kimi.app open to install its plugin.
  • Addressing: agent, agent@host, role:reviewer, task:T123, lead or role:lead (this project's owner-designated lead), * (broadcast), or owner (you).
  • Threads, replies, and requests that need a reply. @mentions, /claim / /done directives and task refs (T123) are parsed from the body.
  • Wake-ups for idle sessions, one adapter per CLI. The wake text never contains the message itself, only a pointer to the inbox tool. Live-test labels below refer to historical harness receipts; revalidate your current provider and AgentMBX build rather than treating those receipts as universal support.
CLIWake pathStatus
Codexcodex app-server experimental thread/queue/add, thread/queue/list, and thread/queue/delete; AgentMBX tracks its owned notice and withdraws it after read/ack, release, or handover while still queued, preserving unowned itemsrequires a Codex build with the experimental queue API; historical live receipts
OpenCodeservice-hosted session: the local service's session API (/synthetic, resume: true). --standalone session: its own plugin/loopback queue, also resume: true (T544; see OPENCODE.md)recorded service-path live receipts and an idle standalone turn (T544); admission alone does not prove model execution
Claude Codepushed by the session's own mbx MCP server through Claude Code's per-session inbox socket (CLAUDE_CODE_MESSAGING_SOCKET), so a plainly started claude wakes on mail with no flag, setting or cron; agentmbx claude [args] adds the research-preview mbx channel insteadhistorical macOS/Fedora live receipts
Kimidesktop app: its local control socket (setup installs an AgentMBX plugin into the app). kimi web: the local server's prompts API. Terminal: a background agentmbx watch task the session keeps running (Kimi starts a turn when it exits)historical terminal/desktop/web live receipts
Hermesone background agentmbx watch task with completion notification; shell hooks bind the session and add inbox context before model callswatcher requires re-arming after each wake; shared gateway hosts aren't covered
Groka background agentmbx watch --cli grok --session <id> task; exact session hookswatcher requires re-arming after each wake
Antigravitya background agentmbx watch task run via run_command; exact session hookswatcher wakes turn on completion via system notification
anything elsedesktop notificationno automatic model turn implied

For long-lived OpenCode agents, run plain opencode against the shared service, started once with opencode service start: one service per machine, with each session keeping its own project folder. After OpenCode evicts an idle session's MCP, standalone wakes remain available while that serve's plugin polls the local daemon (T659); service-hosted wakes remain available while the recorded service process is alive (T688). Both paths require the recorded PID and process birth, and a lease held by a different session blocks the old binding. See the run-mode and eviction guide.

  • Across machines: a small daemon per host. Hosts pair with one command each: agentmbx pair prints a one-time token, agentmbx join <host> <token> on the other machine finishes it (or compare a 6-digit code instead). Hosts find each other on the LAN over mDNS. Every hop is signed. Messages to a sleeping machine wait in an outbox and retry for 72 h, and each is stored exactly once.
  • Wake batching: one atomic 30-second window per agent, plus explicit wake mute. Status messages never wake anyone. The published runtime has no hourly per-thread or daily per-agent hard cap; loop detection is observational, so batching alone doesn't bound an automated conversation's token use.
  • Full-text search (SQLite FTS5) and an audit log. mbx:<id>@<host> references can be cited from tickets and notes.
  • Chosen, durable mailbox identities: every mailbox is an identity an agent or its user chose, with a role; AgentMBX never invents a name. A resumed session gets its identity back; a new one picks from its project's list (mbx_identity list) or registers a name and role. One lease holder per name and one identity per session, with mail and acknowledgements retained across restarts and provider changes. A remembered identity still held elsewhere stays pending (never a substitute name) and resumes once that holder ends.
  • Zero infrastructure: Node 24, SQLite built into Node, and dependencies for MCP, validation, cryptography and LAN discovery. No broker, no cloud, no accounts.

Trust model (the short version)

The recipient seesIt meansIt does not mean
local (same user on this host)written by a process running as your OS user on this machinethat the named agent wrote it (names are labels)
verified (paired host X)signed by machine X's key, which you approved by pairing (one-time token or compared code)which agent on X wrote it
authority: OWNER via <agent> session <fp>a live session that you approved (Touch ID on macOS, your owner passphrase on Linux) sent it, within the capabilities you granted, before the grant expiredthat the content is safe, or that permission prompts can be skipped
  • Owner authority belongs to one running session. You (or an agent) run agentmbx owner grant, pick the live session, and you approve it: a Touch ID tap on macOS, your passphrase on Linux. The grant is bound to a key that exists only in that session's memory, for 12 h by default. Another process using the same agent name gets nothing.
  • The owner key lives in the macOS login Keychain behind Touch ID (no passphrase), readable only by AgentMBX.app's signing helper, which writes the prompt text itself from exactly what it signs. On Linux it is encrypted with your passphrase and unlocks only from a real terminal. Either way, an agent's shell commands cannot use it.
  • Capabilities are enforced by the receiving machine (task.assign, decision, broadcast, alert). A message outside its grant arrives labelled authority: none with a warning.
  • No message can approve a permission prompt or change a recipient's config, owner-signed or not. The MCP instructions tell every agent this, and agents treat all message content as data, not instructions. This mirrors how Claude Code handles messages from other sessions.
  • Known limits:
  • The LAN hop is signed, and since 0.5.1 every body is sealed to the receiving host's pinned X25519 key; envelope metadata (from, to, subject, thread, refs, project path, mentions and tags) is still visible on the wire (T198).
  • Discovery and direct delivery are
Source 1 files
hooks/register.js 482 lines
1/**
2 * Claude Code 2.1.291 mod. The hooks sandbox imports nothing but relative
3 * files and "claude-code", and it has no Node built-ins.
4 *
5 * Session id: `session.start` is only `{ cwd }`. The binary sets
6 * `CLAUDE_CODE_SESSION_ID` on the process and on child env, and substitutes
7 * `${CLAUDE_SESSION_ID}`. T542: `$.session.id()` is read first; those two names are the
8 * fallback, read with `$.env.get` (a string
9 * literal, which `claude plugin validate` can see). If both are missing or
10 * blank, the band says "unbound" and does not call status.
11 *
12 * Status: `$.http.fetch` against the local daemon, keyed by cli and session, asking for
13 * `mbx.status/v2` — the same snapshot the OpenCode sidebar reads. A daemon older than v0.5.17
14 * answers v1; `renderStatus` still tolerates a v1 body, so the band degrades rather than breaks.
15 * Documented init has no timeout; a throw, a non-OK response, or a body that is not an
16 * mbx.status/v1 or v2 snapshot renders "mbx: unavailable".
17 *
18 * Surfaces (T415): the AbovePrompt band shows one compact line with a `●` unread marker;
19 * `/mbx-status` opens a pane (on wide terminals) and always prints the full v2 sections, which
20 * is also the fallback where mods cannot draw (headless `claude -p`, a narrow terminal, or a
21 * render the engine refuses). A 5 s `$.clock.every` timer keeps `$.ui.status` under the prompt
22 * current — the persistent unread indicator — and asks for a redraw.
23 * https://code.claude.com/docs/en/plugins/mods/api
24 */
25
26const DAEMON_ORIGIN = "http://127.0.0.1:7373";
27const CACHE_MS = 2000;
28const PANE_ID = "mbx-status";
29const INDICATOR_MS = 5_000;
30
31/**
32 * @param {Record<string, string | undefined>} env
33 * @returns {string | null}
34 */
35export function resolveSessionId(env) {
36  const code = env.CLAUDE_CODE_SESSION_ID;
37  if (typeof code === "string" && code.trim()) return code.trim();
38  const alias = env.CLAUDE_SESSION_ID;
39  if (typeof alias === "string" && alias.trim()) return alias.trim();
40  return null;
41}
42
43/**
44 * Fixed daemon origin. The session id is only a query value. v2 is requested: the band reads the
45 * same mbx.status/v2 snapshot as the OpenCode sidebar (T414 AC1); renderStatus still tolerates a
46 * v1 body from a daemon older than v0.5.17.
47 * @param {string} sessionId
48 * @returns {string}
49 */
50export function statusRequestUrl(sessionId) {
51  const url = new URL("/v1/status", DAEMON_ORIGIN);
52  url.searchParams.set("cli", "claude");
53  url.searchParams.set("session", sessionId);
54  url.searchParams.set("schema", "mbx.status/v2");
55  if (url.origin !== DAEMON_ORIGIN || url.pathname !== "/v1/status") {
56    throw new Error("status url left the local daemon");
57  }
58  return url.toString();
59}
60
61/**
62 * Render one snapshot. This function does not fetch or derive counts.
63 * A missing session id is "unbound". Anything that is not a v1 or v2
64 * snapshot is "mbx: unavailable".
65 * @param {string | null} sessionId
66 * @param {unknown} snapshot
67 * @returns {string}
68 */
69export function renderStatus(sessionId, snapshot) {
70  if (!sessionId) return "unbound";
71  if (!snapshot || typeof snapshot !== "object") return "mbx: unavailable";
72  const row = /** @type {Record<string, unknown>} */ (snapshot);
73  if (row.schema !== "mbx.status/v1" && row.schema !== "mbx.status/v2") return "mbx: unavailable";
74  const identity = row.identity && typeof row.identity === "object"
75    ? /** @type {Record<string, unknown>} */ (row.identity)
76    : null;
77  if (!identity || identity.state === "unbound" || (identity.state !== "bound" && identity.state !== "ambiguous")) return "unbound";
78  if (identity.state === "ambiguous") return "ambiguous";
79  if (typeof identity.name !== "string" || !identity.name.trim()) return "unbound";
80  const role = typeof identity.role === "string" && identity.role ? ` (${identity.role})` : "";
81  const source = row.inbox && typeof row.inbox === "object"
82    ? /** @type {Record<string, unknown>} */ (row.inbox)
83    : row;
84  const lines = [
85    `mbx ${identity.name.trim()}${role}`,
86    `unread ${count(source.unread)}`,
87    `needs_reply ${count(source.needs_reply)}`,
88    `from_owner ${count(source.from_owner)}`,
89    `outbox_unsent ${count(source.outbox_unsent)}`,
90  ];
91  const policy = policyText(row);
92  if (policy) lines.push(`policy ${policy}`);
93  return lines.join("\n");
94}
95
96/**
97 * v1 carries policy at the top. v2 carries it on harness. Never pick a name from either.
98 * @param {Record<string, unknown>} row
99 * @returns {string}
100 */
101function policyText(row) {
102  const direct = joinPolicy(row.policy);
103  if (direct) return direct;
104  const harness = row.harness && typeof row.harness === "object"
105    ? /** @type {Record<string, unknown>} */ (row.harness)
106    : null;
107  return harness ? joinPolicy(harness.policy) : "";
108}
109
110/**
111 * @param {unknown} value
112 * @returns {string}
113 */
114function joinPolicy(value) {
115  if (typeof value === "string" && value.trim()) return value.trim();
116  if (!Array.isArray(value)) return "";
117  return value.filter((item) => typeof item === "string" && item.trim()).join(", ");
118}
119
120/**
121 * @param {unknown} value
122 * @returns {string}
123 */
124function count(value) {
125  return typeof value === "number" && Number.isFinite(value) ? String(value) : "0";
126}
127
128/**
129 * The one-line under-prompt indicator (`$.ui.status`). Null when there is
130 * nothing worth pinning: unbound, unavailable, or zero unread everywhere; the
131 * timer then clears the line (T658). Like the status line and the OpenCode
132 * sidebar (T650), the headline is new mail only and read-but-unacked mail is
133 * its own `M read` segment; a daemon from before T650 sends only `unread`.
134 * Pure: renders one fetched snapshot, derives nothing.
135 * @param {unknown} snapshot
136 * @returns {string | null}
137 */
138export function statusLineText(snapshot) {
139  const sections = renderSections(snapshot);
140  if (!sections) return null;
141  const row = /** @type {Record<string, unknown>} */ (snapshot);
142  const inbox = row.inbox && typeof row.inbox === "object"
143    ? /** @type {Record<string, unknown>} */ (row.inbox)
144    : row;
145  const unread = typeof inbox.unread === "number" ? inbox.unread : 0;
146  const fresh = typeof inbox.new === "number" ? inbox.new : unread;
147  const read = typeof inbox.new === "number" && typeof inbox.read === "number" ? inbox.read : 0;
148  const needsReply = typeof inbox.needs_reply === "number" ? inbox.needs_reply : 0;
149  const fromOwner = typeof inbox.from_owner === "number" ? inbox.from_owner : 0;
150  if (!fresh && !read && !needsReply && !fromOwner) return null;
151  const seg = [];
152  if (fresh || !read) seg.push(`${fresh}↑`);
153  if (read) seg.push(`${read} read`);
154  if (needsReply) seg.push(`${needsReply}↺`);
155  if (fromOwner) seg.push(`owner:${fromOwner}`);
156  return `mbx: ${seg.join(" ")}`;
157}
158
159/**
160 * The compact band line, with the unread marker T415 AC2 asks for: a `●`
161 * prefix while the fetched snapshot has unread mail. Pure.
162 * @param {string | null} sessionId
163 * @param {unknown} snapshot
164 * @returns {string}
165 */
166export function bandText(sessionId, snapshot) {
167  const text = renderStatus(sessionId, snapshot);
168  if (text.startsWith("mbx ") && statusLineText(snapshot)) return `● ${text}`;
169  return text;
170}
171
172/**
173 * One line per v2 section: identity, registration + lease, inbox, harness,
174 * cloud, devices, project (T415 AC1). The renderer is pure and derives
175 * nothing — every value is read from the one fetched snapshot. Returns null
176 * for a v1 body (the pane is a v2 surface; v1 falls back to the compact
177 * render) and for anything that is not a status snapshot.
178 * @param {unknown} snapshot
179 * @returns {string[] | null}
180 */
181export function renderSections(snapshot) {
182  if (!snapshot || typeof snapshot !== "object") return null;
183  const row = /** @type {Record<string, unknown>} */ (snapshot);
184  if (row.schema !== "mbx.status/v2") return null;
185  const identity = row.identity && typeof row.identity === "object"
186    ? /** @type {Record<string, unknown>} */ (row.identity)
187    : null;
188  const state = identity?.state;
189  if (!identity || state === "unbound") return ["mbx unbound"];
190  if (state === "ambiguous") {
191    const candidates = Array.isArray(identity.candidates) ? identity.candidates.length : 0;
192    return [`mbx ambiguous (${candidates} candidates)`];
193  }
194  if (state !== "bound" || typeof identity.name !== "string" || !identity.name.trim()) return ["mbx unbound"];
195  const role = typeof identity.role === "string" && identity.role ? `(${identity.role})` : "";
196  const lines = [`identity ${identity.name.trim()}${role}`];
197
198  const registration = row.registration && typeof row.registration === "object"
199    ? /** @type {Record<string, unknown>} */ (row.registration)
200    : null;
201  const lease = registration?.lease && typeof registration.lease === "object"
202    ? /** @type {Record<string, unknown>} */ (registration.lease)
203    : null;
204  lines.push(lease
205    ? `registration ${registration?.registered === true ? "registered" : "unregistered"} · lease ${String(lease.holder_cli)}/${String(lease.holder_session)}${lease.verified === true ? " verified" : " unverified"}`
206    : `registration ${registration?.registered === true ? "registered" : "not registered"} · no lease`);
207
208  const inbox = row.inbox && typeof row.inbox === "object"
209    ? /** @type {Record<string, unknown>} */ (row.inbox)
210    : {};
211  lines.push(`inbox ${count(inbox.unread)} unread · ${count(inbox.needs_reply)} needs reply · ${count(inbox.from_owner)} from owner · ${count(inbox.outbox_unsent)} unsent`);
212
213  const harness = row.harness && typeof row.harness === "object"
214    ? /** @type {Record<string, unknown>} */ (row.harness)
215    : null;
216  if (harness) {
217    const policy = joinPolicy(harness.policy);
218    const wake = typeof harness.wake_path === "string" ? harness.wake_path : "none";
219    lines.push(`harness ${String(harness.cli)} ${String(harness.session_id ?? "—")} · wake ${wake}${policy ? ` · policy ${policy}` : ""}`);
220  }
221
222  const cloud = row.cloud && typeof row.cloud === "object"
223    ? /** @type {Record<string, unknown>} */ (row.cloud)
224    : null;
225  if (cloud) {
226    const relay = cloud.relay && typeof cloud.relay === "object"
227      ? /** @type {Record<string, unknown>} */ (cloud.relay)
228      : null;
229    const relayText = relay?.url
230      ? `relay ${String(relay.state)} (${String(relay.url)})`
231      : `relay ${String(relay?.state ?? "unset")}`;
232    const keyAd = typeof cloud.key_ad_expiry === "string" ? ` · key ad until ${cloud.key_ad_expiry.slice(0, 10)}` : "";
233    const account = typeof cloud.account === "string" ? ` · account ${cloud.account}` : "";
234    lines.push(`cloud ${relayText}${keyAd}${account}`);
235  }
236
237  if (Array.isArray(row.devices)) {
238    if (row.devices.length === 0) lines.push("devices none paired");
239    for (const device of row.devices.slice(0, 8)) {
240      if (device && typeof device === "object") {
241        const d = /** @type {Record<string, unknown>} */ (device);
242        const last = typeof d.last_presence === "string" ? ` · seen ${d.last_presence.slice(0, 16).replace("T", " ")}` : "";
243        lines.push(`device ${String(d.host)} at ${String(d.address)} (${String(d.reachability)})${last}`);
244      }
245    }
246  }
247
248  const project = row.project && typeof row.project === "object"
249    ? /** @type {Record<string, unknown>} */ (row.project)
250    : null;
251  if (project) {
252    const members = Array.isArray(project.members) ? project.members.filter((m) => typeof m === "string").join(", ") : "";
253    lines.push(`project ${String(project.directory)} · lead ${String(project.lead ?? "—")} · members ${members}`);
254  } else {
255    lines.push("project none");
256  }
257  return lines;
258}
259
260/**
261 * The last snapshot the band or command fetched, keyed by the session it belongs to, for the
262 * pane to render. T308 AC2: never render another session's data — cleared on every failed or
263 * unavailable fetch and on any session-id change, and consumers compare the key.
264 * @type {{ sessionId: string, snapshot: unknown } | null}
265 */
266let lastStatus = null;
267
268/**
269 * The stored snapshot, only when it belongs to the given session; null otherwise.
270 * @param {string | null} sessionId
271 * @returns {unknown}
272 */
273export function currentSnapshot(sessionId) {
274  return sessionId && lastStatus && lastStatus.sessionId === sessionId ? lastStatus.snapshot : null;
275}
276
277/**
278 * @param {{ ok?: boolean, text?: unknown }} response
279 * @param {string} sessionId
280 * @returns {{ text: string, snapshot: unknown, raw: string | null }}
281 */
282function fromResponse(response, sessionId) {
283  if (!response || response.ok !== true || typeof response.text !== "string") {
284    lastStatus = null;
285    return { text: "mbx: unavailable", snapshot: null, raw: null };
286  }
287  try {
288    const snapshot = JSON.parse(response.text);
289    const text = renderStatus(sessionId, snapshot);
290    if (text === "mbx: unavailable") {
291      lastStatus = null;
292      return { text, snapshot: null, raw: null };
293    }
294    lastStatus = { sessionId, snapshot };
295    return { text, snapshot, raw: response.text };
296  } catch {
297    lastStatus = null;
298    return { text: "mbx: unavailable", snapshot: null, raw: null };
299  }
300}
301
302/**
303 * @param {{ sessionId: string | null, fetchImpl?: (url: string) => Promise<{ ok?: boolean, text?: unknown }> }} opts
304 * @returns {Promise<{ text: string, snapshot: unknown, raw: string | null }>}
305 */
306export async function readStatus(opts) {
307  const sessionId = opts.sessionId;
308  if (!sessionId) {
309    lastStatus = null;
310    return { text: "unbound", snapshot: null, raw: null };
311  }
312  if (!opts.fetchImpl) {
313    lastStatus = null;
314    return { text: "mbx: unavailable", snapshot: null, raw: null };
315  }
316  try {
317    const response = await opts.fetchImpl(statusRequestUrl(sessionId));
318    return fromResponse(response, sessionId);
319  } catch {
320    lastStatus = null;
321    return { text: "mbx: unavailable", snapshot: null, raw: null };
322  }
323}
324
325/** @type {{ sessionId: string, at: number, raw: string } | null} */
326let cache = null;
327
328/**
329 * @param {Record<string, string | undefined>} env
330 * @param {{ fetchImpl?: (url: string) => Promise<{ ok?: boolean, text?: unknown }>, now?: number }} [deps]
331 * @returns {Promise<string>}
332 */
333export async function statusText(env, deps = {}) {
334  const sessionId = resolveSessionId(env);
335  if (!sessionId) return "unbound";
336  const now = deps.now ?? 0;
337  if (cache && cache.sessionId === sessionId && now - cache.at < CACHE_MS) {
338    try {
339      return renderStatus(sessionId, JSON.parse(cache.raw));
340    } catch {
341      cache = null;
342    }
343  }
344  const result = await readStatus({ sessionId, fetchImpl: deps.fetchImpl });
345  if (result.raw) cache = { sessionId, at: now, raw: result.raw };
346  return result.text;
347}
348
349/** Test-only reset so one case cannot reuse another's snapshot. */
350export function resetStatusCache() {
351  cache = null;
352}
353
354/**
355 * @param {unknown} value
356 * @returns {string}
357 */
358function envString(value) {
359  return typeof value === "string" ? value : "";
360}
361
362/**
363 * T542: the engine's own `$.session.id()` is the session id, and it follows /clear and resume.
364 * The env vars are a fallback for a host without it: after /reload-plugins on 2.1.296 they read empty.
365 * @param {any} $
366 * @returns {Promise<Record<string, string>>}
367 */
368async function sessionEnv($) {
369  let sid = "";
370  try { sid = envString(await $.session.id()); } catch { /* no session noun: env below */ }
371  return {
372    CLAUDE_CODE_SESSION_ID: sid || envString(await $.env.get("CLAUDE_CODE_SESSION_ID")),
373    CLAUDE_SESSION_ID: envString(await $.env.get("CLAUDE_SESSION_ID")),
374  };
375}
376
377/**
378 * Production read. `$` stays on this top-level function so `claude plugin validate`
379 * sees `$.env.get`, `$.clock.now`, and `$.http.fetch`.
380 * @param {{ env: { get: (name: string) => Promise<unknown> }, clock: { now: () => Promise<number> }, http: { fetch: (url: string) => Promise<{ ok?: boolean, text?: unknown }> } }} $
381 * @returns {Promise<{ band: string, sections: string[], snapshot: unknown }>}
382 */
383export async function loadStatus($) {
384  const env = await sessionEnv($);
385  const sessionId = resolveSessionId(env);
386  const now = await $.clock.now();
387  const band = await statusText(env, {
388    now: typeof now === "number" ? now : 0,
389    fetchImpl: (url) => $.http.fetch(url),
390  });
391  // the snapshot belongs to this session only (currentSnapshot keys by id; failures clear it)
392  const snapshot = currentSnapshot(sessionId);
393  const sections = renderSections(snapshot) ?? [band];
394  return { band, sections, snapshot };
395}
396
397/** Test-only reset so one case cannot reuse another's snapshot. */
398export function resetStatusState() {
399  resetStatusCache();
400  lastStatus = null;
401}
402
403/**
404 * Claude Code mod entry. Draws the AbovePrompt band, answers /mbx-status, and
405 * renders the full v2 sections in a pane the command opens.
406 * @param {(event: string, matcherOrHook: unknown, hook?: unknown) => unknown} on
407 */
408export function register(on) {
409  on("session.start", async ($, e, next) => {
410    await $.command.register({
411      name: "mbx-status",
412      description: "Show this session's AgentMBX status",
413    });
414    // The persistent unread indicator (T415 AC2): poll the same endpoint the band uses and
415    // keep one line under the prompt current; the invalidate keeps band and pane fresh. The
416    // callback closes over `$` (documented for timers). The host keeps a status line until it is
417    // changed, so nothing to show must clear it with `$.ui.status(undefined)`, or the last count
418    // stays forever (T658). Every tick sets it, as before, so a host-side reset is repaired.
419    $.clock.every(INDICATOR_MS, async () => {
420      try {
421        const { snapshot } = await loadStatus($);
422        const line = statusLineText(snapshot) ?? undefined;
423        $.ui.status(line);
424        $.ui.invalidate("ui.render");
425      } catch { /* next tick */ }
426    });
427    return next(e);
428  });
429
430  on("command.run", { command: "mbx-status" }, async ($) => {
431    try {
432      const { sections } = await loadStatus($);
433      // The pane is the visual surface; the printed sections are the same content, so a session
434      // where mods cannot draw (headless, narrow terminal) still gets the full answer (AC3).
435      try {
436        const placed = await $.ui.open({ id: PANE_ID, title: "MBX", closeOnEscape: true });
437        if (placed && placed.isPlaced === false) {
438          $.ui.toast(`mbx: pane waiting for a wider terminal (${placed.reason ?? "narrow"}); the sections print below`);
439        }
440      } catch { /* pane unavailable: the printed sections below are the fallback */ }
441      return { text: sections.join("\n") };
442    } catch {
443      return { text: "mbx: unavailable" };
444    }
445  });
446
447  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
448    try {
449      if (e?.props?.hasSurvey) return next(e);
450      const { Text } = $.ui.resolve(e);
451      const env = await sessionEnv($);
452      const now = await $.clock.now();
453      await statusText(env, {
454        now: typeof now === "number" ? now : 0,
455        fetchImpl: (url) => $.http.fetch(url),
456      });
457      const sid = resolveSessionId(env);
458      return Text({ children: [bandText(sid, currentSnapshot(sid))] });
459    } catch {
460      return next(e);
461    }
462  });
463
464  on("ui.render", { component: "Pane" }, async ($, e, next) => {
465    try {
466      if (e.requestId !== PANE_ID) return next(e);
467      const { Box, Text } = $.ui.resolve(e);
468      // The pane must never show another session's snapshot either: resolve the current
469      // session id and read only the snapshot stored under it (T308 AC2).
470      const env = await sessionEnv($);
471      const sid = resolveSessionId(env);
472      const sections = renderSections(currentSnapshot(sid)) ?? ["mbx: unavailable"];
473      return Box({
474        flexDirection: "column",
475        children: sections.map((line, i) => Text({ key: `s${i}`, children: [line] })),
476      });
477    } catch {
478      return next(e);
479    }
480  });
481}
482