SLOPSHOPPER

specialists

Specialists execution runtime in Claude Code: specialist activation and dispatch over MCP, session continuity hooks, and the using-specialists skill. Consumes…

panebandcommandtoastprompttimer
★ 3v4.1.1MITupdated 2026-10-26xtrm-dev/specialists/plugins/specialists
A shopper browsing a rack in a slop shop
README

Specialists

npm version License: MIT TypeScript

Deep material lives in docs/ — start with docs/installation.md, docs/bootstrap.md, docs/workflow.md, and docs/cli-reference.md; sp --help is authoritative for flags.

Specialists is an agent-mind runtime for getting real work done.

Two surfaces: native XTRM activation, where the Substrate Issue is the durable executable work authority (see the specialists Claude Code plugin below); and the Beads-backed job workflow, which remains available through the legacy sp CLI (sp run, sp feed, sp result, sp resume, sp steer, sp stop).

It is not just “run many agents”. The core idea is that a long single-agent chat becomes cognitively contaminated: old hypotheses, abandoned plans, tool residue, self-review bias, forgotten constraints, and context-window noise all accumulate in one mind. Quality drops because the same context tries to be explorer, implementer, tester, reviewer, security auditor, memory keeper, and release operator at once.

Specialists gives an AI workflow a healthier shape:

  • the orchestrator stays the central executive — it owns the user intent, task identity, evidence, and publication decision;
  • the pinned Substrate Issue revision is the executable work contract — problem, scope, success criteria, validation, dependencies, and authorized work live there; Journal/settlement evidence records what happened without rewriting that authority;
  • specialists are fresh, scoped cognitive faculties — explorer, debugger, executor, test-engineer, reviewer, sync-docs, researcher, and domain roles each get only the context, tools, rules, and output contract they need;
  • structured handoffs flow back to the orchestrator — results are evidence to consume, not conversational vibes to remember;
  • workspaces and gates keep changes publishable — edit-capable roles work in branches/worktrees, reviewer/QA/security roles judge against the contract.

The result is a shared project mind: continuity without hoarding every detail in one agent’s context.

Specialists sits in the xt/xtrm stack:

  • pi coding agent executes model sessions and exposes tool events/RPC boundaries.
  • xtrm-tools provides operator workflow: worktree sessions, .xtrm/ skills/hooks, reports, update tooling, and gates.
  • Substrate (@jaggerxtrm/substrate) provides durable Issues/revisions, claims, Journal continuity, ExecutionBinding, provenance, and explicit Closure. Beads remains migration/legacy compatibility only.

See specialists.scheme.md for the full rationale.


Why not one big agent chat?

flowchart LR
  Long[One long agent session] --> Residue[Context residue]
  Long --> Bias[Self-review bias]
  Long --> Drift[Goal drift]
  Long --> Noise[Tool/output noise]
  Long --> Fatigue[Instruction fatigue]

  Residue --> Bad[Lower-quality decisions]
  Bias --> Bad
  Drift --> Bad
  Noise --> Bad
  Fatigue --> Bad

  Bad --> Symptoms[Symptoms]
  Symptoms --> Vibes[Reviews become vibes]
  Symptoms --> Mirrors[Tests mirror implementation]
  Symptoms --> Scope[Scope silently widens]
  Symptoms --> Forgotten[Constraints disappear]

The problem is not only token count. It is cognitive contamination. A single context window carries every role’s history, including false starts and stale assumptions. The agent starts defending its own implementation, testing what it built instead of what was requested, and treating completion claims as proof.

Specialists replaces context hoarding with contract-bound cognition.


The common-mind model

flowchart TD
  U[User / project need] --> O[Orchestrator\ncentral executive]
  O --> B[Substrate Issue revision\nproblem · scope · success · validation]
  B --> Check{Contract ready?}
  Check -->|repair needed| Refine[Refine scope / constraints / outputs]
  Refine --> B
  Check -->|ready| O

  O --> Choose{Choose faculty}
  Choose --> E[Explorer\nfresh read-only context]
  Choose --> D[Debugger\nfresh root-cause context]
  Choose --> X[Executor\nfresh implementation context]
  Choose --> QA[Test-engineer / test-runner\nfresh validation context]
  Choose --> R[Seconder / reviewer\nfresh judgment context]
  Choose --> Docs[Sync-docs / service-skills\nfresh documentation context]
  Choose --> Research[Researcher / domain specialist\nfresh external evidence]

  B --> E
  B --> D
  B --> X
  B --> QA
  B --> R
  B --> Docs
  B --> Research

  Rules[Mandatory rules\npermissions · tools · output schema] --> E
  Rules --> D
  Rules --> X
  Rules --> QA
  Rules --> R
  Rules --> Docs
  Rules --> Research

  E --> H[Structured handoff / evidence]
  D --> H
  X --> H
  QA --> H
  R --> H
  Docs --> H
  Research --> H

  H --> O
  O --> Decision{Next decision}
  Decision -->|resume / steer| Choose
  Decision -->|fix loop| B
  Decision -->|publish| Merge[Merge / PR / release]
  Decision -->|done| Close[Explicit Issue Closure\nafter verified evidence]

This is close to how a human mind works: a central executive does not consciously compute every perception, motor skill, language move, and memory lookup at once. It activates specialized faculties, receives summaries/evidence, and decides what to do next.

Specialists gives an AI workflow the same structure. The orchestrator remains the “self”; specialists are bounded capabilities that can be activated without permanently polluting the central context.


What Specialists lets you do

NeedUse
Turn vague work into an executable task contractSubstrate Issue + planner / orchestrator
Map unfamiliar local codesp run explorer --bead <id>
Diagnose a bug with unknown causesp run debugger --bead <id>
Implement a scoped change in an isolated workspacesp run executor --bead <id> --worktree
Add tests from the actual implementation difftest-engineer
Run and classify validation commandstest-runner
Check scope/quality before final reviewseconder
Review implementation evidence against the pinned Issue contractreviewer/seconder against the same pinned revision; legacy sp run ... --bead remains a compatibility surface
Research current docs, repos, APIs, papers, or domain evidenceresearcher, quant-researcher, transcriber
Sync one stale doc safelysync-docs
Keep service-expert skill docs aligned with code driftservice-knowledge-sync
Generate immediate JSON/text from a specialistsp script or sp serve
Watch all active specialist work across repossp console
Inspect runtime evidence and telemetrysp feed, sp log, sp forensic, sp metrics
Configure package specialists for your machinesp init --global, sp edit --global, sp setup

The live catalog is authoritative:

sp list
sp list --compact
sp list-rules
sp help

Install and bootstrap

Specialists is Bun-first and expects xtrm-tools to be installed explicitly. xtrm-tools is a runtime prerequisite, not an npm dependency of this package.

# 1. Bun
curl -fsSL https://bun.sh/install | bash
bun --version

# 2. xtrm-tools
npm install -g xtrm-tools
xt install
xt init

# 3. Specialists
npm install -g @jaggerxtrm/specialists
sp init --global       # machine-level user config and model defaults
sp setup --discovery   # inspect available models/config gaps
sp setup --plan cheap  # optional: propose model assignments
sp init                # per-repo wiring: MCP, hooks, skills, db paths
sp doctor --specialists
sp list

sp is an alias for specialists.

Claude Code plugin (optional)

Specialists ships two Claude Code plugins in the xtrm marketplace. specialists exposes specialist activation as MCP tools and injects live activation state at session start. specialists-ui is optional and draws the rows specialists raises as teammate-style transcript rows. Both are opt-in: nothing installs or enables them for you.

claude plugin marketplace add xtrm-dev/specialists
claude plugin install specialists@xtrm
claude plugin install specialists-ui@xtrm   # optional: teammate-style transcript rows

specialists-ui draws the rows the specialists plugin raises in Claude Code's own style. A channel wake becomes a teammate row, ● Specialist @explorer:d65bbed4 completed, with the wake's brief under it: run cost and purpose, the first result lines, the failing model and error, or the question. ctrl+o on a finished or failed wake shows the full result. A Specialists MCP call becomes a native tool row, ● Dispatch(executor · XTRM-4), with its result on an indented line under it. It is a separate plugin because Claude Code never runs a plugin's own drawing hooks on a row that plugin raised, and the wake comes from the specialists MCP server. Without it, everything works and the rows show as raw text.

The /specialists command and the fleet band

The specialists plugin draws the live fleet above the prompt and opens a fleet pane with /specialists. Select a row to read its result or its event feed, or to reply, steer, resume or stop it. A toast reports each activation that finishes, fails or asks a question.

CommandEffect
/specialistsopen or close the fleet pane
/specialists status [activation]the fleet report, or one activation in detail
/specialists result <activation>the full result of a settled activation
/specialists feed <activation> [lines]the activation's event feed, like sp feed
/specialists reply <message_id> <answer>answer a waiting activation
`/specialists steer\resume\stop <activation> …`act on an activation
`/specialists show\hide\expand\collapse`band visibility

<activation> is a full id or a short prefix. result and feed also reach activations from earlier sessions. The coordinator has the same feed as the specialist_feed tool.

To turn every wake off (the channel push, the wake-watch fallback and the toasts), start Claude Code with SPECIALISTS_WAKE=off. Everything stays readable through specialist_status. This is the Claude Code equivalent of the Pi extension's --no-specialist-wake.

Updates

The plugins and the runtime update separately. Both carry the package version.

  • Plugins come from GitHub. Claude Code does not auto-update a third-party marketplace by default. To turn it on, run /plugin, open Marketplaces, select xtrm, and choose Enable auto-update. For a whole fleet, set "autoUpdate": true on the xtrm entry of extraKnownMarketplaces in managed settings. Without auto-update, run claude plugin marketplace update xtrm, then claude plugin update specialists@xtrm (and specialists-ui@xtrm). Run /reload-plugins or restart to apply.
  • The runtime comes from npm, and Claude Code never updates it. Run npm i -g @jaggerxtrm/specialists@latest, then restart Claude Code. When the plugin and the runtime versions differ, the plugin's MCP launcher writes a warning to stderr with the exact install command, and starts anyway.
What the plugins need
PieceNeeded forSet up by
Specialists runtime (@jaggerxtrm/specialists)the MCP server; the plugin launcher starts itnpm install -g @jaggerxtrm/specialists (see Install and bootstrap)
Bun on PATHthe MCP server and every plugin hook scriptinstall Bun
Substrate work storespecialist_dispatch (the contract)@jaggerxtrm/substrate installed, or XTRM_SUBSTRATE_DIR (below)
Claude Code with plugin hooks modules (verified on 2.1.288)the fleet band, the fleet pane, /specialists, and all specialists-ui rowsa current Claude Code; hooks must not be turned off with disableAllHooks
specialists@xtrmMCP tools, session-start state, the fallback wake, the band, pane and commandclaude plugin install specialists@xtrm
specialists-ui@xtrmteammate-style wake rows and native tool rowsclaude plugin install specialists-ui@xtrm
--channels plugin:specialists@xtrmthe channel wake (primary)launch flag; xt claude passes it for you
Managed settings channelsEnabled + allowedChannelPluginsthe channel wake (primary)root, /etc/claude-code/managed-settings.json (below)

The plugin hooks API (the band, pane and rows) is early access in Claude Code and can change between releases. If a row or the band stops drawing after a Claude Code update, run claude --debug and search the log for ui.render to see whether a hook was skipped or refused.

Verify the server is reachable from Claude Code:

claude mcp list | grep specialists
# plugin:specialists:specialists: ... - ✔ Connected

Dispatch needs the Substrate work store, which supplies the contract. It is resolved in this order: an explicit XTRM_SUBSTRATE_DIR, then normal module resolution of the installed @jaggerxtrm/substrate package, then the npm global prefix, then failure. No environment variable is required as long as the package is installed in one of those places:

npm install @jaggerxtrm/substrate           # in the project the session runs in
npm install --global @jaggerxtrm/substrate  # or beside a globally installed Specialists

The npm global prefix is searched because a global install from a FOLDER is a symlink: default resolution dereferences it and walks the checkout's ancestors, which never reach <prefix>/lib/node_modules, so a sibling global Substrate would otherwise be invisible. xt init enrolls Substrate into that prefix, which is why the XTRM-managed path needs no extra step.

Set XTRM_SUBSTRATE_DIR only to override that with a local checkout, for example when developing Substrate itself. It wins over the installed package when set.

If neither is available, specialist_dispatch is refused with work_item_store_unavailable while specialist_status and specialist_list keep working — so the plugin looks healthy until you try to dispatch. An override must be in the environment the session is launched with; a shell export afterwards does not reach the already-running MCP server.

export XTRM_SUBSTRATE_DIR=/path/to/xtrm/packages/substrate
claude

The plugin requires Bun on PATH and reads Substrate's canonical store, resolved from SUBSTRATE_DB, else XTRM_STATE_DB, else ~/.xtrm/state.db. SUBSTRATE_DB comes first because the store belongs to Substrate and is shared with sb and Pi. To develop against a checkout instead of an install, load both plugins: claude --plugin-dir ./plugins/specialists --plugin-dir ./plugins/specialists-ui. Loading only ./plugins/specialists gives the runtime without the transcript rows.

Enable the channel wake

When an activation settles, fails, escalates or asks a question, the plugin's MCP server pushes a short notice into the coordinator session (a Claude Code Channel). The notice wakes an idle session; the authoritative read of a result is specialist_result (specialist_status for asks and state). Claude Code drops the push without any error unless all of the following are true, so configure both parts.

  1. Launch the session with the plugin's server named as a channel:
   claude --channels plugin:specialists@xtrm
  1. As root, allow the plugin in Claude Code's managed settings, in /etc/claude-code/managed-settings.json or a file under /etc/claude-code/managed-settings.d/:
   {
     "channelsEnabled": true,
     "allowedChannelPlugins": [{ "plugin": "specialists", "marketplace": "xtrm" }]
   }

Set both keys. ~/.claude/settings.json is not read for either key. Without a managed allowlist, Claude Code uses a default list fetched from Anthropic that does not include this plugin. claude.ai Team and Enterprise plans need channelsEnabled: true in every case. For a login that is not claude.ai (an API key, for example), any managed-settings file without channelsEnabled: true turns channels off, so a file that only holds the allowlist makes delivery worse, not better.

For local development without root, launch with claude --dangerously-load-development-channels plugin:specialists@xtrm instead of --channels. A channel loaded this way skips the allowlist. Use it only for a plugin you build yourself.

The push also needs the legacy (2025-11-25) MCP protocol revision, because the stateless 2026-07-28 revision has no path for a message the server sends unprompted. You do not need to configure this: the plugin's launcher serves the legacy revision only, so Claude Code downgrades this one server and keeps negotiating normally with every other server. Do not set MCP_PROTOCOL_NEGOTIATION=legacy for this; it pins every MCP server to the legacy handshake.

If the channel wake is not available, a fallback still wakes the session: the plugin's wake-watch hook starts with each session, watches the Substrate store, and wakes the session once when an activation settles or asks a question. It stops after that first wake or after about 15 minutes, so it is a safety net, not a replacement for the channel. The deployed companion specialists-ui plugin acknowledges each channel wake (a marker under ~/.xtrm/wake-acks), and this watcher drops any event that marker covers, so a push that arrived is not woken a second time; without that plugin it falls back to today's behaviour. specialist_result is the authoritative read either way.

Check the result with specialists doctor --channels, which reports the first closed gate. Channels work only in an interactive session; claude -p never receives them. Behaviour was read from Claude Code 2.1.288; see docs/claude-channel-constraints.md for the full gate chain.

Global model config

Package specialist definitions ship with execution.model = null. This is intentional: the package defines roles, tools, contracts, and safety boundaries; your machine-level config defines provider/model choices.

Use:

sp init --global
sp edit --global
sp setup --fetch-benchmarks --json
sp setup --plan <budget-preset>
sp doctor --specialists

The loader merges configuration in this order:

  1. package canonical specialist JSON;
  2. ~/.config/specialists/user.json global overrides;
  3. .specialists/user/ repo-local overrides.

See docs/installation.md, docs/bootstrap.md, and docs/authoring.md.


First tracked run

bd create "Investigate flaky checkout flow" -t bug -p 1 --json
bd update <id> --claim --json

sp run explorer --bead <id> --context-depth 2
sp feed <job-id> --follow
sp result <job-id>

sp run debugger --bead <id> --context-depth 3
sp run executor --bead <id> --worktree
sp run reviewer --bead <id> --job <executor-job>

bd close <id> --reason "Root cause found, fix reviewed" --json

Ad-hoc one-offs are still supported, but tracked work should use beads:

sp run explorer --prompt "Map the CLI architecture"

Operator console

sp console is the multi-repo terminal dashboard for live specialist work.

It provides:

  • an ALL view aggregating active jobs across configured repos;
  • per-repo tabs and persistent repo registry (~/.config/specialists/console.json);
  • job list, feed, result, bead, diff, config, and repo-config views;
  • cursor navigation and direct actions (↵, r, i, b, d, g, R, x, 0, tab, 1-9);
  • TUI-styled rows shared with sp ps.
sp console
# Press R, then + to add a repository; select one and press d to remove it.

For shell-only workflows:

sp ps
sp feed <job-id>
sp feed -f
sp result <job-id>
sp log <job-id>
sp steer <job-id> "focus only on the API boundary"
sp resume <job-id> "continue with this additional evidence"
sp stop <job-id>
sp clean --reap-orphans --dry-run

Publication and review

Specialists separates doing work from publishing work.

  • executor, debugger, test-engineer, and sync-docs may create changes.
  • seconder, test-runner, and reviewer produce evidence/verdicts.
  • Reviewer PASS is the normal publish gate for implementation work.
  • sp merge and sp epic merge exist but are currently marked broken. Do not use them.

Follow the merge and integration procedure for reviewed publication work. sp epic status <epic-id> remains available for inspection.

Keep-alive specialists may stop in waiting after producing a result. Use sp result <job-id> to read the handoff, then sp stop <job-id> when no follow-up is needed.


Script and service specialists

Use sp run for interactive agent orchestration. Use sp script / sp serve when you need an immediate one-shot generation contract from a specialist.

sp script <name> --vars key=value --json
sp serve --port 8000 --readiness-canary warn
curl -sS http://localhost:8000/v1/generate \
  -H 'content-type: application/json' \
  -d '{"specialist":"hello","variables":{"name":"world"}}'

sp script flags:

sp script <name> [--vars k=v ...] [--template <text> | --template-field <name>] \
  [--model <override>] [--thinking <level>] [--json] \
  [--allow-local-scripts] [--allow-write-capable] [--single-instance <lockpath>]

sp serve flags (HTTP sidecar for the same runtime path):

sp serve [--port <n>] [--concurrency <n>] [--project-dir <path>] \
  [--allow-skills] [--allow-skills-roots <p1>:<p2>]

Script/service mode is useful for CI, internal services, deterministic JSON generation, and sidecar deployments. Only sp script supports trusted local scripts or write-capable execution through --allow-local-scripts and --allow-write-capable. sp serve supports neither — it remains READ_ONLY. Skills remain disabled unless --allow-skills is set; --allow-skills-roots restricts accepted canonical skill sources when supplied, but it is not a filesystem read boundary. Specialists 3.21.6 does not provide host-read isolation: allowed tools, extensions, MCP processes, and child processes can read paths visible to the runtime identity. Its bounded waiver permits only trusted single-tenant callers with private authenticated ingress, a dedicated container or OS account, minimal mounts, least-privilege credentials, trusted definitions, and reviewed extension sources. Untrusted, public, cross-tenant, and multi-tenant deployments are excluded. The waiver does not authorize publication and expires at 3.21.7.

See docs/specialists-service.md and docs/specialists-service-install.md.


Observability and telemetry

Specialists is DB-first. Runtime state lives in .specialists/db/observability.db; file mirrors under .specialists/jobs/ are legacy/operator recovery surfaces.

Useful surfaces:

sp ps                         # dashboard row view
sp feed <job-id>              # event stream replay
sp log <job-id>               # control/status/error log
sp forensic <job-id> --json   # persisted forensic envelopes
sp metrics --prometheus       # low-cardinality metrics
sp serve --port 8000          # exposes /metrics and job feed endpoints

Telemetry uses bounded labels and avoids high-cardinality IDs in Prometheus labels. Forensic events retain drill-down detail in SQLite/JSON output where IDs are appropriate.

Project-pack Service Knowledge

Source 2 files
hooks/register.tsx 894 lines
1/* @jsxRuntime classic */
2/* @jsx h */
3/* @jsxFrag Fragment */
4import type { Elements, EngineInterface, McpToolResult, On } from 'claude-code'
5import { ROLE_SPECIALIST_MAP } from './role-specialist-map.generated'
6
7// The live Specialists fleet of THIS session, drawn in the band above the prompt: the
8// Claude-native twin of the Pi native-specialists footer section
9// (config/pi-extensions/native-specialists). Presentation and control only — every read
10// and every action goes through the session's own Specialists MCP server, whose in-process
11// host is the fleet this session dispatched. No state of its own beyond the last read.
12
13/** The plugin's MCP server as /mcp lists it (`plugin:<plugin>:<server>`). */
14export const MCP_SERVER = 'plugin:specialists:specialists'
15export const COMMAND = 'specialists'
16/**
17 * Fallback cadence when the server has no blocking wait (an older runtime strips the
18 * wait arguments and answers instantly) or when it is failing fast: the band then polls
19 * at this interval, exactly the pre-4218 behaviour. With a server that blocks, calls run
20 * ~WAIT_TIMEOUT_S apart and this timer only re-arms the watch between calls.
21 */
22export const POLL_MS = 2000
23/** Server-side block per watch call. Under the common 30s MCP client tool timeout. */
24export const WAIT_TIMEOUT_S = 25
25/** A call that returns faster than this did not block: the server lacks the wait (or answered a change instantly). */
26const FAST_RETURN_MS = 1000
27/** Consecutive instant returns before the watch parks on the POLL_MS tick: three instant answers are an unsupported wait, not three coincidences. */
28const FAST_STREAK_MAX = 3
29export const FLEET_MAX_ROWS = 6
30/** Above this many activations the band folds to one line and the pane holds the list. */
31export const COLLAPSE_AT = 3
32export const PANE_ID = 'specialists-fleet'
33export const PURPOSE_ROW_MAX = 60
34
35const SPINNER_FRAMES = ['◐', '◓', '◑', '◒']
36/** Attention yellow: the terminal theme's warning key, shared with the error
37 *  lines and the specialists-ui WAITING_COLOR — no hard-coded hex. */
38const ATTENTION = 'yellow'
39
40export type Activation = {
41  activation_id: string
42  specialist?: string
43  bead_id?: string
44  state?: string
45  resolved_model?: string
46  thinking_level?: string
47  elapsed_s?: number
48  turn_count?: number
49  token_usage?: Record<string, number | undefined>
50  purpose?: string
51  result_status?: string
52}
53
54export type Ask = {
55  message_id: string
56  kind?: string
57  activation_id: string
58  from?: string
59  body?: string
60  asked_at?: number
61}
62
63/**
64 * One activation's ready-made display strings from the runtime (SPECIALISTS-4365).
65 * Plain text, no styling — the mod applies its own rendering. Absent when the
66 * runtime predates the `display` block; every reader falls back to its local
67 * formatters then. This file is engine-loaded with a type-only import, so the
68 * block is read from the MCP payload and nothing is imported at runtime.
69 */
70export type FleetDisplayEntry = {
71  activation_id: string
72  marker?: string
73  metrics?: string
74  work?: string
75}
76
77export type FleetDisplay = {
78  header?: string
79  activations?: FleetDisplayEntry[]
80}
81
82export type Fleet = { activations: Activation[]; asks: Ask[]; display?: FleetDisplay }
83
84const USAGE =
85  'Usage: /specialists [status [activation]|show|hide|expand|collapse] · result <activation> · ' +
86  'feed <activation> [lines] · reply <message_id> <answer> · steer <activation> <message> · ' +
87  'resume <activation> <prompt> · stop <activation> [reason]'
88
89/** Feed lines the pane's feed view asks for; the newest are kept. */
90export const FEED_LINES = 30
91/** Detail lines drawn in the pane; the band draws fewer so the prompt stays in view. */
92export const DETAIL_PANE_LINES = 24
93export const DETAIL_BAND_LINES = 6
94/** How long a transition toast stays up. */
95export const TOAST_MS = 6000
96
97const isActive = (state?: string) => state === 'running' || state === 'starting'
98
99function textOf(result: McpToolResult): string {
100  return result.content
101    .map(block => ('text' in block && typeof block.text === 'string' ? block.text : ''))
102    .filter(Boolean)
103    .join('\n')
104}
105
106/**
107 * One MCP tool call, its JSON payload or the reason it failed. A transport error, an
108 * `isError` result and a `{ status: 'error' }` payload are all failures: the fleet must
109 * never read an unreachable server as an empty one.
110 */
111export async function callTool(
112  $: EngineInterface,
113  tool: string,
114  args: Record<string, unknown> = {},
115): Promise<{ ok: true; value: Record<string, unknown> } | { ok: false; error: string }> {
116  let result: McpToolResult
117  try {
118    result = await $.mcp.call(MCP_SERVER, tool, args)
119  } catch (cause) {
120    return { ok: false, error: cause instanceof Error ? cause.message : String(cause) }
121  }
122  const text = textOf(result)
123  if (result.isError) return { ok: false, error: text || `${tool} failed` }
124  let value: unknown
125  try {
126    value = JSON.parse(text)
127  } catch {
128    return { ok: false, error: `${tool} returned non-JSON: ${text.slice(0, 120)}` }
129  }
130  if (!value || typeof value !== 'object') return { ok: false, error: `${tool} returned no object` }
131  const record = value as Record<string, unknown>
132  if (record.status === 'error') return { ok: false, error: String(record.error ?? `${tool} failed`) }
133  return { ok: true, value: record }
134}
135
136export function fleetOf(value: Record<string, unknown>): Fleet {
137  const activations = Array.isArray(value.activations) ? (value.activations as Activation[]) : []
138  const asks = Array.isArray(value.pending_asks) ? (value.pending_asks as Ask[]) : []
139  const fleet: Fleet = {
140    activations: activations.filter(a => a && typeof a.activation_id === 'string'),
141    asks: asks.filter(a => a && typeof a.message_id === 'string'),
142  }
143  // Additive and optional (SPECIALISTS-4365): old runtimes omit the block and
144  // every reader below falls back to its local formatters.
145  const display = value.display as Record<string, unknown> | undefined
146  if (display && typeof display === 'object') {
147    const entries = Array.isArray(display.activations)
148      ? (display.activations as FleetDisplayEntry[]).filter(e => e && typeof e.activation_id === 'string')
149      : undefined
150    const header = typeof display.header === 'string' ? display.header : undefined
151    if (header !== undefined || entries !== undefined) {
152      fleet.display = { ...(header !== undefined ? { header } : {}), ...(entries !== undefined ? { activations: entries } : {}) }
153    }
154  }
155  return fleet
156}
157
158/** One activation's display entry, or undefined when the payload predates `display`. */
159export function displayEntryOf(fleet: Fleet, activationId: string): FleetDisplayEntry | undefined {
160  const list = fleet.display?.activations
161  if (!Array.isArray(list)) return undefined
162  return list.find(e => e?.activation_id === activationId)
163}
164
165/** Fleet header text: the runtime's canonical header when present, else the local one. */
166export function headerTextOf(fleet: Fleet): string {
167  const header = fleet.display?.header
168  if (typeof header === 'string' && header) return header
169  return headerOf(fleet)
170}
171
172/** Row marker: the runtime's canonical marker when present, else the local one. */
173export function markerTextOf(fleet: Fleet, row: Activation, ask: Ask | undefined, nowMs: number): string {
174  const marker = displayEntryOf(fleet, row.activation_id)?.marker
175  if (typeof marker === 'string' && marker) return marker
176  return markerOf(row, ask, nowMs)
177}
178
179/** Row metrics: the runtime's canonical metrics when present, else the local ones. */
180export function metricsTextOf(fleet: Fleet, row: Activation, ask: Ask | undefined, nowMs: number): string {
181  const metrics = displayEntryOf(fleet, row.activation_id)?.metrics
182  if (typeof metrics === 'string' && metrics) return metrics
183  return metricsOf(row, ask, nowMs)
184}
185
186/**
187 * Work identity: the runtime's canonical issue ref when present, else the local
188 * bead fallback. The canonical identity is issue_ref (SPECIALISTS-4365); the
189 * fallback keeps the old output byte-identical.
190 */
191export function workTextOf(fleet: Fleet, row: Activation): string {
192  const work = displayEntryOf(fleet, row.activation_id)?.work
193  if (typeof work === 'string' && work) return work
194  return row.bead_id ?? '—'
195}
196
197/** Buckets are exclusive, so they sum to the entry count (as the Pi header does). */
198export function summaryOf({ activations, asks }: Fleet) {
199  const blocked = new Set(asks.map(a => a.activation_id))
200  const running = activations.filter(a => isActive(a.state) && !blocked.has(a.activation_id)).length
201  const blockedCount = activations.filter(a => blocked.has(a.activation_id)).length
202  return {
203    running,
204    blocked: blockedCount,
205    waiting: Math.max(0, activations.length - running - blockedCount),
206    total: activations.length,
207  }
208}
209
210export function headerOf(fleet: Fleet): string {
211  const { running, waiting, blocked, total } = summaryOf(fleet)
212  if (total === 0) return 'idle'
213  const parts: string[] = []
214  if (running > 0) parts.push(`${running} running`)
215  if (waiting > 0) parts.push(`${waiting} waiting`)
216  if (blocked > 0) parts.push(`! ${blocked} blocked`)
217  return parts.join(' • ')
218}
219
220/** `42s`, `2m14s`, `1h05m`. */
221export function elapsedShort(seconds?: number): string {
222  const total = Math.max(0, Math.floor(seconds ?? 0))
223  if (total < 60) return `${total}s`
224  if (total < 3600) return `${Math.floor(total / 60)}m${String(total % 60).padStart(2, '0')}s`
225  return `${Math.floor(total / 3600)}h${String(Math.floor((total % 3600) / 60)).padStart(2, '0')}m`
226}
227
228/** Spend counts only; `total_tokens` is a rollup, never a summand. */
229export function spendShort(usage?: Record<string, number | undefined>): string {
230  if (!usage) return ''
231  const keys = ['input_tokens', 'output_tokens', 'cache_creation_tokens', 'cache_read_tokens', 'reasoning_tokens', 'tool_tokens']
232  const total = keys.reduce((n, k) => n + (usage[k] ?? 0), 0)
233  if (total <= 0) return ''
234  if (total < 1000) return `${total}`
235  if (total < 10000) return `${(total / 1000).toFixed(1)}k`
236  return `${Math.round(total / 1000)}k`
237}
238
239export function purposeShort(purpose?: string): string {
240  const flat = String(purpose ?? '').replace(/\s+/g, ' ').trim()
241  return flat.length <= PURPOSE_ROW_MAX ? flat : `${flat.slice(0, PURPOSE_ROW_MAX - 1)}…`
242}
243
244const shortId = (id: string) => (id.startsWith('act:') ? id.slice(4, 12) : id.slice(0, 8))
245
246export function markerOf(row: Activation, ask: Ask | undefined, nowMs: number): string {
247  if (ask) return '!'
248  if (row.state === 'settled') return '✓'
249  if (row.state === 'failed') return '✕'
250  if (isActive(row.state)) return SPINNER_FRAMES[Math.floor(nowMs / 250) % SPINNER_FRAMES.length]!
251  return '●'
252}
253
254/** Turn count, spelled out: `1 turn` / `3 turns`. Mirrors the Pi extension's formatTurnsShort. */
255export function turnsShort(turnCount?: number): string {
256  if (turnCount === null || turnCount === undefined) return ''
257  return `${turnCount} turn${turnCount === 1 ? '' : 's'}`
258}
259
260export function metricsOf(row: Activation, ask: Ask | undefined, nowMs: number): string {
261  if (ask) return `waiting ${elapsedShort((nowMs - (ask.asked_at ?? nowMs)) / 1000)}`
262  const parts = [elapsedShort(row.elapsed_s)]
263  const turns = turnsShort(row.turn_count)
264  if (turns) parts.push(turns)
265  const spend = spendShort(row.token_usage)
266  if (spend) parts.push(spend)
267  if (row.result_status) parts.push(row.result_status)
268  return parts.join(' • ')
269}
270
271/** Blocked first, then live work, then the rest; each group keeps the host's order. */
272export function orderedOf({ activations, asks }: Fleet): Activation[] {
273  const blocked = new Set(asks.map(a => a.activation_id))
274  const rank = (a: Activation) => (blocked.has(a.activation_id) ? 0 : isActive(a.state) ? 1 : 2)
275  return [...activations].sort((a, b) => rank(a) - rank(b))
276}
277
278/** The plain-text fleet report `/specialists` prints (every surface, not only the band). */
279export function reportOf(fleet: Fleet, error: string | null, nowMs: number): string {
280  const lines = [`Specialists · ${headerTextOf(fleet)}`]
281  if (error) lines.push(`status unavailable · ${error}`)
282  for (const row of orderedOf(fleet)) {
283    const ask = fleet.asks.find(a => a.activation_id === row.activation_id)
284    lines.push(
285      `  ${markerTextOf(fleet, row, ask, nowMs)} ${row.specialist ?? 'specialist'} ${row.activation_id}  ${workTextOf(fleet, row)}  ${metricsTextOf(fleet, row, ask, nowMs)}`,
286    )
287    if (ask) lines.push(`      ${ask.kind ?? 'ask'} ${ask.message_id}: ${ask.body ?? ''}`)
288  }
289  return lines.join('\n')
290}
291
292/**
293 * Prompts that suggest a dispatchable specialist may fit (SPECIALISTS-4343): review or
294 * delegation work a coordinator might otherwise hand to a generic subagent. No `g` flag:
295 * `test` on a global regex is stateful and would skip alternate prompts.
296 */
297export const ROLE_NUDGE_RE = /review|dispatch|subagent|teammate|monitor|deploy/i
298
299/**
300 * The one-line nudge built from the GENERATED role map (config/catalog/role-specialist-map.json
301 * via ./role-specialist-map.generated): every specialist name in it comes from the map,
302 * never from a hand-kept list. Null when the map is unreadable, so the hook stays silent
303 * instead of nudging from a stale list.
304 */
305export function roleNudgeLine(): string | null {
306  try {
307    const roles: unknown = ROLE_SPECIALIST_MAP
308    if (!roles || typeof roles !== 'object') return null
309    const pairs = Object.entries(roles as Record<string, unknown>)
310      .filter((entry): entry is [string, string[]] => Array.isArray(entry[1]) && (entry[1] as string[]).length > 0)
311      .map(([role, names]) => `${role}→${names.join('/')}`)
312    if (pairs.length === 0) return null
313    return `Prefer a dispatchable specialist over a generic subagent (${pairs.join('; ')}) — verify with specialist_list`
314  } catch {
315    return null
316  }
317}
318
319/**
320 * The toasts one fleet read owes the operator: an activation that newly finished or failed,
321 * and an ask that newly appeared — the Claude Code twin of the Pi extension's `ui.notify`.
322 * Pure over two reads, so a missed read cannot replay old events: the FIRST read after start
323 * (prev null) owes nothing, since everything in it predates this session's view.
324 */
325export function transitionsOf(prev: Fleet | null, next: Fleet): string[] {
326  if (!prev) return []
327  const before = new Map(prev.activations.map(a => [a.activation_id, a.state]))
328  const askedBefore = new Set(prev.asks.map(a => a.message_id))
329  const out: string[] = []
330  for (const row of next.activations) {
331    if (before.get(row.activation_id) === row.state) continue
332    const who = `${row.specialist ?? 'specialist'}:${shortId(row.activation_id)}`
333    if (row.state === 'settled') out.push(`Specialist ${who} finished${row.bead_id ? ` · ${row.bead_id}` : ''}`)
334    if (row.state === 'failed') out.push(`Specialist ${who} FAILED${row.bead_id ? ` · ${row.bead_id}` : ''}`)
335  }
336  for (const ask of next.asks) {
337    if (askedBefore.has(ask.message_id)) continue
338    const row = next.activations.find(a => a.activation_id === ask.activation_id)
339    const who = `${row?.specialist ?? ask.from ?? 'specialist'}:${shortId(ask.activation_id)}`
340    out.push(`Specialist ${who} ${ask.kind === 'escalation' ? 'escalated' : 'asked a question'}`)
341  }
342  return out
343}
344
345/** The lines a result read draws: the output, or why there is none yet. */
346export function resultLinesOf(value: Record<string, unknown>): string[] {
347  if (typeof value.output === 'string') {
348    const head = [value.status, value.resolved_model].filter(v => typeof v === 'string' && v).join(' · ')
349    const body = value.output.trim() ? value.output.replace(/\n+$/, '').split('\n') : ['(empty output)']
350    return head ? [head, ...body] : body
351  }
352  if (typeof value.next === 'string') return [`${String(value.state ?? 'not settled')} · use ${value.next}`]
353  return ['no result']
354}
355
356/** The lines a feed read draws. */
357export function feedLinesOf(value: Record<string, unknown>): string[] {
358  const events = Array.isArray(value.events) ? value.events.filter((e): e is string => typeof e === 'string') : []
359  if (events.length === 0) return ['no events yet']
360  return value.truncated === true ? [`… ${Number(value.total ?? 0) - events.length} earlier events`, ...events] : events
361}
362
363/** An activation by its full id or an unambiguous prefix (with or without `act:`). */
364export function resolveActivation(fleet: Fleet, ref: string): Activation | string {
365  const needle = ref.startsWith('act:') ? ref : `act:${ref}`
366  const hits = fleet.activations.filter(a => a.activation_id === ref || a.activation_id.startsWith(needle))
367  if (hits.length === 1) return hits[0]!
368  return hits.length === 0 ? `Unknown activation: ${ref}` : `Ambiguous activation: ${ref}`
369}
370
371/** What the band draws from: the last read and the operator's view choices. */
372type State = {
373  fleet: Fleet
374  error: string | null
375  visible: boolean
376  expanded: boolean
377  selected: string | null
378  flash: string | null
379  polling: boolean
380  timer: { cancel: () => void } | null
381  paneOpen: boolean
382  /** A blocking specialist_status call is in flight (SPECIALISTS-4218). */
383  watching: boolean
384  /** Consecutive sub-second watch returns; parking on the tick after FAST_STREAK_MAX. */
385  fastStreak: number
386  /** The result or feed view open under the selected row; null when none is. */
387  detail: { kind: 'result' | 'feed'; id: string; lines: string[] } | null
388  /** A stop press waiting for its inline confirm; null when no stop is armed. */
389  pendingStop: string | null
390  /** The rows the open pane was last sized for; the pane re-opens when they drift. */
391  paneRows: number
392  /** The previous successful read, for transition toasts; null until the first one. */
393  last: Fleet | null
394  /** SPECIALISTS_WAKE=off silences toasts, as the Pi extension's --no-specialist-wake does. */
395  quiet: boolean
396  /** Role-to-specialist nudge (SPECIALISTS-4343): the one-line notice fires at most once per session. */
397  roleNudgeShown: boolean
398}
399
400/** Apply one specialist_status read to the band state and redraw. */
401function apply($: EngineInterface, s: State, read: { ok: true; value: Record<string, unknown> } | { ok: false; error: string }): void {
402  if (read.ok) {
403    s.fleet = fleetOf(read.value)
404    s.error = null
405    if (!s.quiet) for (const text of transitionsOf(s.last, s.fleet)) $.ui.toast(text, { timeoutMs: TOAST_MS })
406    s.last = s.fleet
407    if (s.selected && !s.fleet.activations.some(a => a.activation_id === s.selected)) s.selected = null
408    if (s.detail && s.detail.id !== s.selected) s.detail = null
409    // An armed stop dies with its activation; the operator re-arms deliberately.
410    if (s.pendingStop && !s.fleet.activations.some(a => a.activation_id === s.pendingStop)) s.pendingStop = null
411    void syncPaneRows($, s)
412    // A live feed keeps up with the activation; a settled one is read once.
413    const row = s.detail?.kind === 'feed' ? s.fleet.activations.find(a => a.activation_id === s.detail!.id) : undefined
414    if (row && isActive(row.state)) void loadDetail($, s, 'feed', row.activation_id)
415  } else {
416    s.error = read.error
417  }
418  $.ui.invalidate('ui.render')
419}
420
421async function refresh($: EngineInterface, s: State): Promise<void> {
422  if (s.polling) return
423  s.polling = true
424  try {
425    apply($, s, await callTool($, 'specialist_status'))
426  } finally {
427    s.polling = false
428  }
429}
430
431/**
432 * One blocking-watch cycle (SPECIALISTS-4218): call specialist_status with
433 * wait_for_change so the SERVER parks until the fleet changes or the timeout passes, then
434 * redraw and re-arm. Replaces the fixed 2s poll — the steady request stream that cost every
435 * idle session 0.03-0.1 core of MCP-server CPU. Self-sustaining while the server blocks; a
436 * server that answers instantly (no wait support, or failing fast) is detected by the
437 * streak and parks on the POLL_MS tick instead of spinning.
438 */
439async function watchOnce($: EngineInterface, s: State): Promise<void> {
440  if (s.watching) return
441  s.watching = true
442  try {
443    const startedAt = Date.now()
444    const read = await callTool($, 'specialist_status', { wait_for_change: true, timeout_s: WAIT_TIMEOUT_S })
445    const took = Date.now() - startedAt
446    apply($, s, read)
447    if (took >= FAST_RETURN_MS) {
448      s.fastStreak = 0
449      void watchOnce($, s) // blocked server: re-arm immediately, one call per WAIT_TIMEOUT_S
450    } else if (s.fastStreak < FAST_STREAK_MAX) {
451      s.fastStreak += 1 // maybe a real change answered in <1s: allow a couple before concluding
452      void watchOnce($, s)
453    } // else: instant answers are an unsupported wait — park on the POLL_MS tick
454  } finally {
455    s.watching = false
456  }
457}
458
459/** Read a result or feed into the detail view under the selected row. */
460async function loadDetail($: EngineInterface, s: State, kind: 'result' | 'feed', id: string): Promise<void> {
461  const read = kind === 'result'
462    ? await callTool($, 'specialist_result', { activation_id: id })
463    : await callTool($, 'specialist_feed', { activation_id: id, limit: FEED_LINES })
464  // The operator may have closed or switched the view while the call was in flight.
465  if (s.detail && (s.detail.id !== id || s.detail.kind !== kind)) return
466  s.detail = {
467    kind,
468    id,
469    lines: read.ok ? (kind === 'result' ? resultLinesOf(read.value) : feedLinesOf(read.value)) : [`${kind} unavailable · ${read.error}`],
470  }
471  $.ui.invalidate('ui.render')
472}
473
474function toggleDetail($: EngineInterface, s: State, kind: 'result' | 'feed', id: string): void {
475  if (s.detail?.kind === kind && s.detail.id === id) {
476    s.detail = null
477    $.ui.invalidate('ui.render')
478    return
479  }
480  s.detail = { kind, id, lines: ['loading…'] }
481  $.ui.invalidate('ui.render')
482  void loadDetail($, s, kind, id)
483}
484
485/** A stop press the operator confirmed inline: the only path from the band/pane
486 *  stop button to specialist_stop_activation (SPECIALISTS-4346). */
487async function confirmStop($: EngineInterface, s: State, id: string): Promise<void> {
488  s.pendingStop = null
489  await act($, s, 'specialist_stop_activation', { activation_id: id, reason: 'operator request' }, `Stopped ${id}.`)
490}
491
492/** One control action; its answer is what the operator sees. */
493async function act($: EngineInterface, s: State, tool: string, args: Record<string, unknown>, done: string): Promise<string> {
494  const result = await callTool($, tool, args)
495  s.flash = result.ok ? done : `${tool} refused: ${result.error}`
496  await refresh($, s)
497  return s.flash
498}
499
500/** The elements both sites draw with; the terminal and desktop tables have all four. */
501type Kit = Pick<Elements['terminal'], 'Box' | 'Text' | 'Button' | 'Input'>
502
503/** Pane rows for the live fleet: one line per activation, chrome, and the selected-row
504 *  detail reserve. Recomputed whenever the content changes (SPECIALISTS-4346); the old
505 *  `* 2` counted the retired two-line rows. */
506function paneRowsFor(s: State): number {
507  const n = s.fleet.activations.length
508  return Math.min(48, n + 8 + (s.selected ? DETAIL_PANE_LINES : 0))
509}
510
511/** Opens the fleet pane: docked beside a fullscreen transcript, else inline above the prompt. */
512async function openPane($: EngineInterface, s: State): Promise<void> {
513  const rows = paneRowsFor(s)
514  await $.ui.open({
515    id: PANE_ID,
516    title: 'Specialists',
517    focus: true,
518    closeOnEscape: true,
519    rows,
520  })
521  s.paneOpen = true
522  s.paneRows = rows
523  $.ui.invalidate('ui.render')
524}
525
526/** Re-opens the pane when the content outgrew its rows; a no-op otherwise. The engine
527 *  has no resize primitive, so open-again with the new count is the follow mechanism. */
528async function syncPaneRows($: EngineInterface, s: State): Promise<void> {
529  if (!s.paneOpen) return
530  const want = paneRowsFor(s)
531  if (want === s.paneRows) return
532  try {
533    await $.ui.open({ id: PANE_ID, title: 'Specialists', focus: true, closeOnEscape: true, rows: want })
534    s.paneRows = want
535  } catch {
536    // The open pane keeps its old height; the next change retries.
537  }
538}
539
540async function closePane($: EngineInterface, s: State): Promise<void> {
541  await $.ui.close({ id: PANE_ID }).catch(() => undefined)
542  s.paneOpen = false
543  s.paneRows = 0
544  $.ui.invalidate('ui.render')
545}
546
547/**
548 * Rows and the selected row's controls: the one drawing the band and the pane share, so
549 * both sites read and act the same way. `site` keeps element keys apart between them.
550 * One line per activation (the Pi row layout: marker, name:short, work, model facts,
551 * metrics); the purpose and the inputs live in the detail under the selected row.
552 * Indentation rides on paddingLeft, never on literal spaces.
553 */
554function fleetBody($: EngineInterface, s: State, ui: Kit, rows: Activation[], site: string, detailLines: number) {
555  const { Box, Text, Button, Input } = ui
556  const nowMs = Date.now()
557  const selectedRow = rows.find(a => a.activation_id === s.selected)
558  const selectedAsk = selectedRow && s.fleet.asks.find(a => a.activation_id === selectedRow.activation_id)
559
560  const selectRow = (id: string | null) => {
561    s.selected = id
562    s.flash = null
563    s.pendingStop = null
564    $.ui.invalidate('ui.render')
565    void syncPaneRows($, s)
566  }
567
568  return (
569    <Box flexDirection="column">
570      <Box flexDirection="column" paddingLeft={4}>
571        {rows.map(row => {
572          const ask = s.fleet.asks.find(a => a.activation_id === row.activation_id)
573          const isSelected = row.activation_id === s.selected
574          const thinking = row.thinking_level ? ` ${row.thinking_level}` : ''
575          return (
576            <Box key={`${site}:${row.activation_id}`} flexDirection="column">
577              <Button
578                plain
579                key={`row:${row.activation_id}`}
580                onPress={() => selectRow(isSelected ? null : row.activation_id)}
581              >
582                {`${isSelected ? '▾' : '▸'} ${markerTextOf(s.fleet, row, ask, nowMs)} ${row.specialist ?? 'specialist'}:${shortId(row.activation_id)} ${workTextOf(s.fleet, row)} ${row.resolved_model ?? '?model'}${thinking} · ${metricsTextOf(s.fleet, row, ask, nowMs)}`}
583              </Button>
584            </Box>
585          )
586        })}
587      </Box>
588
589      {selectedRow ? (
590        <Box flexDirection="column" paddingLeft={6}>
591          <Text dimColor wrap="wrap">{selectedRow.activation_id} · {selectedRow.state ?? 'unknown'}</Text>
592          {selectedRow.purpose ? <Text dimColor wrap="wrap">purpose: {purposeShort(selectedRow.purpose)}</Text> : null}
593          {selectedAsk ? (
594            <>
595              <Text color={ATTENTION} wrap="wrap">{selectedAsk.kind ?? 'ask'}: {selectedAsk.body ?? ''}</Text>
596              <Input
597                key={`reply:${selectedAsk.message_id}`}
598                label="reply "
599                placeholder="answer the specialist"
600                submitLabel="reply"
601                autoFocus
602                onSubmit={value => { if (value.trim()) void act($, s, 'specialist_reply', { message_id: selectedAsk.message_id, body: value.trim() }, `Answered ${selectedAsk.message_id}.`) }}
603              />
604            </>
605          ) : isActive(selectedRow.state) ? (
606            <Input
607              key={`steer:${selectedRow.activation_id}`}
608              label="steer "
609              placeholder="redirect the running specialist"
610              submitLabel="steer"
611              onSubmit={value => { if (value.trim()) void act($, s, 'specialist_steer', { activation_id: selectedRow.activation_id, message: value.trim() }, `Steered ${selectedRow.activation_id}.`) }}
612            />
613          ) : (
614            <Input
615              key={`resume:${selectedRow.activation_id}`}
616              label="resume "
617              placeholder="next instruction, same session"
618              submitLabel="resume"
619              onSubmit={value => { if (value.trim()) void act($, s, 'specialist_resume', { activation_id: selectedRow.activation_id, prompt: value.trim() }, `Resumed ${selectedRow.activation_id}.`) }}
620            />
621          )}
622          <Box>
623            <Button plain key={`result:${selectedRow.activation_id}`} onPress={() => toggleDetail($, s, 'result', selectedRow.activation_id)}>
624              {s.detail?.kind === 'result' ? 'hide result' : 'result'}
625            </Button>
626            <Text> </Text>
627            <Button plain key={`feed:${selectedRow.activation_id}`} onPress={() => toggleDetail($, s, 'feed', selectedRow.activation_id)}>
628              {s.detail?.kind === 'feed' ? 'hide feed' : 'feed'}
629            </Button>
630          </Box>
631          <Box>
632            {s.pendingStop === selectedRow.activation_id ? (
633              <Box flexDirection="column">
634                <Text wrap="wrap">Stop {shortId(selectedRow.activation_id)}? This cannot be undone.</Text>
635                <Box>
636                  <Button plain key={`confirm-stop:${selectedRow.activation_id}`} onPress={() => void confirmStop($, s, selectedRow.activation_id)}>
637                    confirm stop
638                  </Button>
639                  <Text> </Text>
640                  <Button plain key={`cancel-stop:${selectedRow.activation_id}`} onPress={() => { s.pendingStop = null; $.ui.invalidate('ui.render') }}>
641                    keep running
642                  </Button>
643                </Box>
644              </Box>
645            ) : (
646              <Button
647                plain
648                key={`stop:${selectedRow.activation_id}`}
649                onPress={() => { s.pendingStop = selectedRow.activation_id; s.flash = null; $.ui.invalidate('ui.render') }}
650              >
651                stop
652              </Button>
653            )}
654          </Box>
655          {s.detail && s.detail.id === selectedRow.activation_id ? (
656            <Box flexDirection="column">
657              {(s.detail.kind === 'feed' ? s.detail.lines.slice(-detailLines) : s.detail.lines.slice(0, detailLines)).map((line, i) => (
658                <Text key={`${site}:detail:${i}`} dimColor={s.detail!.kind === 'feed'} wrap="truncate-end">{line}</Text>
659              ))}
660              {s.detail.lines.length > detailLines ? (
661                <Text dimColor italic wrap="wrap">{`… ${s.detail.lines.length - detailLines} more lines · /specialists ${s.detail.kind} ${shortId(selectedRow.activation_id)}`}</Text>
662              ) : null}
663            </Box>
664          ) : null}
665        </Box>
666      ) : null}
667
668      {s.flash ? (
669        <Box paddingLeft={4}>
670          <Text dimColor wrap="wrap">{s.flash}</Text>
671        </Box>
672      ) : null}
673    </Box>
674  )
675}
676
677export function register(on: On) {
678  const s: State = {
679    fleet: { activations: [], asks: [] },
680    error: null,
681    visible: true,
682    expanded: true,
683    selected: null,
684    flash: null,
685    polling: false,
686    timer: null,
687    paneOpen: false,
688    watching: false,
689    fastStreak: 0,
690    detail: null,
691    pendingStop: null,
692    paneRows: 0,
693    last: null,
694    quiet: false,
695    roleNudgeShown: false,
696  }
697
698  on('session.start', async ($, e, next) => {
699    try {
700      await $.command.register({
701        name: COMMAND,
702        description: 'Live Specialists fleet: status, result, feed, reply, steer, resume, stop',
703        argumentHint: '[status|result|feed|show|hide|expand|collapse|reply|steer|resume|stop] …',
704        immediate: true,
705      })
706    } catch {
707      // Another Specialists surface may already serve the command.
708    }
709    s.quiet = String((await $.env.get('SPECIALISTS_WAKE').catch(() => undefined)) ?? '').toLowerCase() === 'off'
710    s.timer?.cancel()
711    // The tick is the skeleton, not the heartbeat: it re-arms the blocking watch whenever
712    // no call is in flight (server without wait support, or between re-arms), while a
713    // server that blocks makes each call last WAIT_TIMEOUT_S — the request rate of an
714    // idle session drops from one per POLL_MS to one per WAIT_TIMEOUT_S (SPECIALISTS-4218).
715    s.timer = $.clock.every(POLL_MS, () => void watchOnce($, s))
716    void refresh($, s)
717    void watchOnce($, s)
718    return next(e)
719  })
720
721  // Role-to-specialist nudge (SPECIALISTS-4343): a matching prompt carries the generated
722  // map's one-line notice once per session. Never denies, never throws (fail open), and a
723  // non-matching prompt pays one regex test and nothing else.
724  on('prompt.submit', async ($, e, next) => {
725    try {
726      if (s.roleNudgeShown) return next(e)
727      if (!ROLE_NUDGE_RE.test(e.text ?? '')) return next(e)
728      const line = roleNudgeLine()
729      if (!line) return next(e)
730      s.roleNudgeShown = true
731      return next({ ...e, context: [...(e.context ?? []), line] })
732    } catch {
733      return next(e)
734    }
735  })
736
737  on('command.run', { command: COMMAND }, async ($, e) => {
738    const trimmed = e.args.trim()
739    const [verb = '', ref = '', ...rest] = trimmed.split(/\s+/)
740    const tail = rest.join(' ')
741
742    if (verb === '') {
743      await refresh($, s)
744      if (s.paneOpen) {
745        await closePane($, s)
746        return { text: 'Specialists pane hidden' }
747      }
748      await openPane($, s)
749      return { text: 'Specialists pane shown' }
750    }
751
752    if (verb === 'status' && !ref) {
753      await refresh($, s)
754      return { text: reportOf(s.fleet, s.error, Date.now()) }
755    }
756
757    if (verb === 'status' || verb === 'result' || verb === 'feed') {
758      if (!ref) return { text: USAGE }
759      // result and feed reach earlier-session activations too, so an id the live fleet does
760      // not know goes to the server as given; only an ambiguous live prefix is refused here.
761      await refresh($, s)
762      const target = resolveActivation(s.fleet, ref)
763      if (typeof target === 'string' && target.startsWith('Ambiguous')) return { text: target }
764      const id = typeof target === 'string' ? ref : target.activation_id
765      if (verb === 'status') {
766        if (typeof target === 'string') return { text: target }
767        const ask = s.fleet.asks.find(a => a.activation_id === id)
768        const entry = displayEntryOf(s.fleet, id)
769        return {
770          text: [
771            `${entry?.marker ?? markerOf(target, ask, Date.now())} ${target.specialist ?? 'specialist'} ${id} · ${target.state ?? 'unknown'}`,
772            `  issue ${entry?.work ?? target.bead_id ?? '—'} · ${target.resolved_model ?? '?model'}${target.thinking_level ? ` · ${target.thinking_level}` : ''}`,
773            `  ${entry?.metrics ?? metricsOf(target, ask, Date.now())}`,
774            ...(target.purpose ? [`  purpose: ${target.purpose}`] : []),
775            ...(ask ? [`  ${ask.kind ?? 'ask'} ${ask.message_id}: ${ask.body ?? ''}`] : []),
776          ].join('\n'),
777        }
778      }
779      if (verb === 'result') {
780        const read = await callTool($, 'specialist_result', { activation_id: id })
781        return { text: read.ok ? resultLinesOf(read.value).join('\n') : `specialist_result refused: ${read.error}` }
782      }
783      const lines = Math.min(200, Math.max(1, Number(rest[0]) || FEED_LINES))
784      const read = await callTool($, 'specialist_feed', { activation_id: id, limit: lines })
785      return { text: read.ok ? feedLinesOf(read.value).join('\n') : `specialist_feed refused: ${read.error}` }
786    }
787
788    if (verb === 'show' || verb === 'hide' || verb === 'expand' || verb === 'collapse') {
789      if (verb === 'show') s.visible = true
790      if (verb === 'hide') s.visible = false
791      if (verb === 'expand') s.expanded = true
792      if (verb === 'collapse') s.expanded = false
793      $.ui.invalidate('ui.render')
794      return { text: `Specialists band: ${verb}` }
795    }
796
797    if (verb === 'reply') {
798      if (!ref || !tail) return { text: USAGE }
799      const text = await act($, s, 'specialist_reply', { message_id: ref, body: tail }, `Answered ${ref}.`)
800      return { text, context: [`The operator answered specialist ask ${ref} directly: ${tail}`] }
801    }
802
803    if (verb === 'steer' || verb === 'resume' || verb === 'stop') {
804      if (!ref || (verb !== 'stop' && !tail)) return { text: USAGE }
805      await refresh($, s)
806      const target = resolveActivation(s.fleet, ref)
807      if (typeof target === 'string') return { text: target }
808      const id = target.activation_id
809      const text =
810        verb === 'steer'
811          ? await act($, s, 'specialist_steer', { activation_id: id, message: tail }, `Steered ${id}.`)
812          : verb === 'resume'
813            ? await act($, s, 'specialist_resume', { activation_id: id, prompt: tail }, `Resumed ${id}.`)
814            : await act($, s, 'specialist_stop_activation', { activation_id: id, reason: tail || 'operator request' }, `Stopped ${id}.`)
815      return { text, context: [`The operator ran /specialists ${verb} on ${id}${tail ? `: ${tail}` : ''}. Result: ${text}`] }
816    }
817
818    return { text: USAGE }
819  })
820
821  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
822    // The band is raised on the terminal only; narrowing here also types `Input`.
823    if (e.surface !== 'terminal') return next(e)
824    if (!s.visible || e.props.hasSurvey || (s.fleet.activations.length === 0 && !s.error)) return next(e)
825
826    const { Box, Text, Button, Input } = await $.ui.resolve(e)
827    const ordered = orderedOf(s.fleet)
828    // Folded above COLLAPSE_AT, and while the pane holds the list: the band keeps the
829    // header and the blocked rows only, since an ask must never hide behind a count.
830    const isFolded = s.paneOpen || ordered.length > COLLAPSE_AT
831    const blocked = new Set(s.fleet.asks.map(a => a.activation_id))
832    const rows = !s.expanded
833      ? []
834      : isFolded
835        ? (s.paneOpen ? [] : ordered.filter(a => blocked.has(a.activation_id)))
836        : ordered.slice(0, FLEET_MAX_ROWS)
837
838    return (
839      <Box flexDirection="column">
840        <Box flexDirection="row" paddingLeft={2}>
841          <Text bold>specialists</Text>
842          <Text> {headerTextOf(s.fleet)}</Text>
843          <Text dimColor> · </Text>
844          <Button plain key="open" onPress={() => void (s.paneOpen ? closePane($, s) : openPane($, s))}>
845            {s.paneOpen ? 'close' : 'open'}
846          </Button>
847        </Box>
848        {isFolded && !s.paneOpen ? (
849          <Box paddingLeft={4}>
850            <Text dimColor wrap="wrap">open the pane or /specialists for the full fleet</Text>
851          </Box>
852        ) : null}
853        {s.error ? (
854          <Box paddingLeft={4}>
855            <Text color={ATTENTION} wrap="wrap">status unavailable · {s.error}</Text>
856          </Box>
857        ) : null}
858        {rows.length > 0 || s.flash ? fleetBody($, s, { Box, Text, Button, Input }, rows, 'band', DETAIL_BAND_LINES) : null}
859        {!isFolded && s.expanded && ordered.length > rows.length ? (
860          <Box paddingLeft={4}>
861            <Text dimColor wrap="wrap">+{ordered.length - rows.length} more</Text>
862          </Box>
863        ) : null}
864      </Box>
865    )
866  })
867
868  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
869    // The mobile app draws no Input; it keeps /specialists status.
870    if (e.requestId !== PANE_ID || e.surface === 'mobile') return next(e)
871
872    const { Box, Text, Button, Input } = await $.ui.resolve(e)
873    return (
874      <Box flexDirection="column">
875        <Text bold>{headerTextOf(s.fleet)}</Text>
876        {s.error ? <Text color={ATTENTION} wrap="wrap">status unavailable · {s.error}</Text> : null}
877        {s.fleet.activations.length === 0 ? <Text dimColor wrap="wrap">No live activations.</Text> : null}
878        {fleetBody($, s, { Box, Text, Button, Input }, orderedOf(s.fleet), 'pane', DETAIL_PANE_LINES)}
879        <Text dimColor wrap="wrap">esc closes · select a row to read its result or feed, or to reply, steer, resume or stop</Text>
880      </Box>
881    )
882  })
883
884  on('ui.close', { id: PANE_ID }, async ($, e, next) => {
885    const result = await next(e)
886    if (result.deny === undefined) {
887      s.paneOpen = false
888      s.paneRows = 0
889      $.ui.invalidate('ui.render')
890    }
891    return result
892  })
893}
894
hooks/role-specialist-map.generated.ts 4 lines
1// GENERATED by scripts/generate-role-specialist-map.mjs — do not edit.
2// Canonical source: config/catalog/role-specialist-map.json
3export const ROLE_SPECIALIST_MAP: Record<string, string[]> = {"review":["reviewer","seconder"],"quant":["quant-methodologist","quant-researcher"],"deep-analysis":["overthinker"],"deploy":["test-runner","reviewer"],"monitor":["test-runner","debugger"],"implement":["executor"],"explore":["explorer","researcher"],"plan":["planner"],"test":["test-engineer","test-runner"],"security":["security-auditor"],"debug":["debugger"],"coordinate":["chain-coordinator","node-coordinator"],"docs":["sync-docs","service-knowledge-sync"],"changelog":["changelog-keeper","changelog-drafter"],"merge":["xt-merge"],"transcribe":["transcriber"],"obligations":["obligations-scanner"],"author":["specialists-creator"]};
4