SLOPSHOPPER

swarm-mod

Spawn, watch and steer a swarm of Claude Code agents from a side pane

panebandguardcommandtoolprocess
v0.4.0MITupdated 2026-10-13netgfx/claude-swarm-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · swarm-mod
│ ┃ Swarm ✕ › fix the failing auth test and add an audit log call │ ┃ SWARM 0 agents · 0 working │ ┃ [ n: + Spawn agent ] r: Rosters ⏺ Read(src/auth.ts) │ ┃ No agents yet. Spawn one, or launch a saved ⎿ Read 6 lines │ ┃ roster (r). ⏺ 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 │ │ › /swarm │ │ swarm + Spawn agent ⟨Claude Code's own drawing⟩ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
swarm + Spawn agent ⟨Claude Code's own drawing⟩
Pane · Swarm
SWARM 0 agents · 0 working [ n: + Spawn agent ] r: Rosters No agents yet. Spawn one, or launch a saved roster (r).
Pane · Spawn agent
Spawn a swarm agent Runs as: Teammate (agent team, in this session) ▾ Agent: Default (general-purpose) ▾ Model: Inherit (lead's model) ▾ Thinking effort: Default ▾ Name: scout ●●● Color: lavender ▾ Approval mode: Ask me (default) ▾ Auto-restart: Off ▾ Task: what should it work on? Workspace: /work/app Agent teams are off (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1). It will run as a named background agent instead. [ Spawn scout ] [ Cancel ]
README

swarm-mod

A Claude Code mod for running a swarm of agents from a side pane. You spawn agents, watch their live state and token use, answer their approvals and questions, and message them, all from the session you started in.

Swarm paneSpawn form
The swarm pane: a Spawn agent button, Rosters, one finished reviewer agent with its token count, Broadcast and Clear finishedThe spawn form: transport, agent type, model, thinking effort, name, color, approval mode, auto-restart, task and workspace

Supports Windows and macOS (Linux best effort). Tested with Claude Code v2.1.289 on Windows 11 (PowerShell 7 and Windows Terminal). The macOS paths are covered by unit tests, and the generated launch script was checked with a POSIX shell, but they haven't been run on a Mac yet.

Install

This repo is a Claude Code plugin marketplace. Inside Claude Code:

/plugin marketplace add netgfx/claude-swarm-mod
/plugin install swarm-mod@claude-swarm-mod

Or from a shell:

claude plugin marketplace add netgfx/claude-swarm-mod
claude plugin install swarm-mod@claude-swarm-mod

Restart Claude Code (or run /reload-plugins), then type /swarm. To get updates later, run claude plugin marketplace update claude-swarm-mod.

For teammates that join this session's agent team, also set CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 (see Transports). To run it from a local checkout instead, see Load it from a checkout.

What it does

FeatureHow
Spawn Agent buttonThe n: + Spawn agent button in the swarm pane, + Spawn agent in the band above the prompt, or /swarm spawn.
Spawn formTransport (teammate or separate session), agent type (built-ins plus ~/.claude/agents and .claude/agents files, plus any type Claude Code offers, including plugin agents), model, thinking effort, instance name (unique, suggested for you), color (suggested at random from a 12-color palette, never one a live agent already has), approval mode, and an optional first task.
Same workspaceEvery agent starts in the lead session's working directory. Teammates share the lead's process. Separate sessions Set-Location / cd there before claude starts.
Live statestarting, working (with the current tool, such as Bash: npm test), waiting, idle, done, failed, stopped, exited, no heartbeat, plus ! needs approval and ? has a question.
Token usePer agent: total, input, output, cache read, cache write, current context size, and turn count. Plus a swarm total.
Agent viewClick a name to open its panel. On a wide fullscreen terminal it's a docked side panel; otherwise it opens inline in the main area. e expands it (with the teammate's conversation), c / Esc closes it and restores the normal layout. A separate session also has w: Open its window, which brings its exact tab forward: by tty in Terminal.app or iTerm2 on macOS, by window title on Windows.
Spawn errorsA failed agent's row shows a short failed · copy error button. Pressing it copies the whole error to the clipboard (or press o in its panel), so a long InputValidationError isn't cut off.
Needs-you iconA red ! review / magenta ? answer button on the agent's row and in the band, plus a toast. Its panel has Approve / Deny / Use its own prompt, or the question's options plus a free-text "Other".
MessagingMessage one agent from its panel, or broadcast to every live agent. This uses cross-session messaging ($.session.send): { agentId } for teammates, { sessionId } for separate sessions.
Kill / interruptPer agent, k: Kill. Teammates are stopped with TaskStop. A separate session's process is ended by its PID (taskkill /T /F on Windows, kill -TERM on macOS), after checking that the PID still belongs to claude, so a reused PID is never killed. If that check fails, the session ends itself. i: Interrupt stops only the current turn.
Kill allk: Kill all in the swarm pane (press twice within 6 s to confirm), or /swarm kill-all. Pending approvals are denied so nothing waits on a dead agent, and killed agents are never auto-restarted.
Auto-restartOff by default. Turn it on in the spawn form or with a in an agent's panel. A teammate that failed, or a separate session that crashed, exited unexpectedly, or hung (no heartbeat for a full minute of the main session's own time, so waking from sleep doesn't count), comes back with the same name, color, model, effort, approval mode and task. The task is prefixed with a note to check the workspace first. The backoff is 5 s, 15 s and 45 s, for up to 3 restarts. A hung session is killed first. Kill, /exit, and the agent panel's stop are treated as deliberate and never undone. p: Respawn brings back any stopped agent by hand.
Saved rostersr: Rosters (or /swarm rosters) saves the current swarm under a name: each agent's name, color, type, model, effort, approval mode, transport, task and auto-restart. Launch a roster in any workspace with one click (or /swarm load <name>). Names and colors already in use are adjusted (scout → scout-2). Rosters live in the mod store, shared by every session on this machine.
Every subagent, whoever spawned itSubagents and teammates spawned outside the swarm (Claude's own Agent calls, another plugin's spawns, ones started before the mod loaded) join the swarm too, named after their description (Game UI / HUD / cards → game-ui-hud-cards). You see their status, current tool and tokens, can message, kill or remove them, and Edit them (m in their panel) to rename, recolor, or change type, model, effort, approval mode, task and auto-restart, then save them in a roster. They keep Claude Code's own permission prompt and questions. They stay out of the automatic last swarm until you save a roster. A removed one is not added back.
Restore last swarmEach workspace's latest swarm is saved automatically. When you start Claude Code there again, the band and the pane offer Restore last swarm (N) (or /swarm restore).

Transports

Teammate (agent team). The mod calls $.agent.spawn({ name, subagentType, model, prompt }). $.agent.spawn only accepts a model family alias (opus, sonnet, haiku, fable), so the model picked in the form (stored as a full id such as claude-sonnet-5-5) is mapped to its alias first; Inherit sends no model. With CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 set, that joins this session's team. Without it, the agent runs as a named background agent that you can still message, and the form warns you. The agent's loop runs inside the lead's process, so the mod sees its model steps (tokens, plus the per-agent effort, applied by rewriting turn.step), its tool calls (activity, edited files), and its permission checks (the approval mode, applied in tool.check).

Separate Claude Code session. The mod writes ~/.claude/swarm-mod/launch/<id>.ps1 (Windows), .command (macOS), or .sh (Linux), then opens a terminal:

  • Windows: a tab in a Windows Terminal window named swarm (wt.exe -w swarm new-tab …), or a plain console window if Windows Terminal is missing.
  • macOS: a new iTerm2 window when the lead runs in iTerm2 (TERM_PROGRAM=iTerm.app), otherwise a new Terminal.app window (open -a Terminal <id>.command, which needs no permissions). The .command script records its own tty and runs claude through your login shell ($SHELL -lic; fish falls back to zsh/bash), so claude and node resolve from the PATH your shell normally has, even when the lead runs in the Desktop app.
  • Linux: x-terminal-emulator, gnome-terminal, konsole, or xterm.

The new terminal runs:

claude --name <name> --plugin-dir <this mod> [--agent <type>] [--model <m>] [--effort <e>]
       [--permission-mode <mode> | --dangerously-skip-permissions] --settings <worker-settings.json>

--model gets the full model id, which the CLI accepts.

worker-settings.json sets crossSessionInbound: "accept", so the lead's messages get through whatever the worker's permission mode. The first task is passed in SWARM_MOD_TASK and the worker submits it itself. Neither the task nor the JSON goes on the command line, because Windows PowerShell 5.1 mangles quotes inside native arguments.

In that session the same mod runs in worker mode. It reports status, activity, tokens, edited files, its last answer, and any pending approval or question to $.store (shared by all sessions on the machine). The lead checks for updates every 1.5 s and marks a worker no heartbeat after 20 s of silence.

Approval modes

ModeSeparate sessionTeammate (enforced by the mod)
Ask me (default)--permission-mode defaultAnything the lead would ask about waits in the swarm pane
Accept editsacceptEditsEdit, Write, and NotebookEdit allowed; the rest as default
AutoautoFollows the lead session's own mode
Plan / read-onlyplanEdits denied, and anything needing approval denied, with a reason Claude can act on
Don't askdontAskAnything not pre-approved is denied
Bypass all--dangerously-skip-permissionsEverything allowed except explicit deny rules

Claude Code can't set a teammate's permission mode at spawn time, so the mod applies the mode itself at tool.check, matching the check to the agent through tool_use_id.

A request waiting for you is held for up to 15 minutes for teammates and 3 minutes for workers. After that it falls back to Claude Code's normal prompt, in the lead for a teammate or in the worker's own window for a worker. The mod never approves anything unless you press Approve or picked the agent's approval mode yourself.

Commands, tool, and keys

  • /swarm: open the swarm pane.
  • /swarm spawn: open the spawn form.
  • /swarm status: print the roster.
  • /swarm rosters: open the rosters pane.
  • /swarm save <name> and /swarm load <name>: save or launch a roster.
  • /swarm restore: bring back this workspace's last swarm.
  • /swarm kill-all: kill every agent.
  • /swarm band off|on: hide or show the band.
  • /swarm-spawn: open the spawn form.
  • Tool mcp__swarm-mod__swarm_status: lets the lead Claude read the roster (status, activity, tokens, what's waiting on you, last answers) before it coordinates.
  • Pane keys: n spawn, r rosters, k kill all (twice), x clear finished.
  • Agent panel keys: y approve, d deny, l use its own prompt, o copy its error, w open its window, i interrupt, k kill, p respawn, a toggle auto-restart, e expand, m edit, r remove, c close.
  • Rosters pane: type a name and press Enter to save; Launch or Delete each roster; c close.

Load it from a checkout

PowerShell:

claude plugin validate D:\Projects\Projects\claude-plugins\swarm-mod
claude --plugin-dir D:\Projects\Projects\claude-plugins\swarm-mod
# optional, for teammates:
$env:CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = '1'

Bash/Zsh:

claude plugin validate ~/mods/swarm-mod
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 claude --plugin-dir ~/mods/swarm-mod

On macOS, the first time you use w: Open its window (or launch into iTerm2), macOS asks whether your terminal or the Claude app may control Terminal or iTerm. Allow it, or later in System Settings > Privacy & Security > Automation. Opening a Terminal.app worker doesn't need that permission.

For the Desktop app (Code tab), add the folder to env.CLAUDE_CODE_PLUGIN_DIRS in ~/.claude/settings.json (paths separated by ; on Windows, : on macOS), then start a new session. The sidebar docks in a fullscreen terminal at least 144 columns wide (110 once you've opened it yourself). Narrower than that, panes open inline above the prompt.

When swarm-mod is installed from the marketplace, separate-session workers get --plugin-dir pointing at the installed copy, so they run the same version as the lead.

Tests

Set-Location D:\Projects\Projects\claude-plugins\swarm-mod; claude plugin test

50 tests in three files cover the following. tests/adopt.test.ts covers subagents spawned outside the swarm: naming, adoption at spawn, from the agent list and from their first loop event, no double entry for the swarm's own spawns, keeping the native permission prompt, editing and saving one in a roster, kill and remove, and the edit form on both surfaces. tests/lifecycle.test.ts covers kill-all (the two-press confirm, TaskStop, kill by PID, the reused-PID guard, a worker ending itself), the auto-restart policy (failure, deliberate exits, hang detection, backoff, the restart limit), respawn and the auto-restart toggle, saving, launching and deleting rosters (with name and color fitting), restoring the last swarm, and the new panes on both surfaces. tests/swarm.test.ts covers: color picking, name rules, mapping a picked model to the alias $.agent.spawn accepts, approval-mode decisions, quoting of the worker CLI and launch script, path conflicts, the spawn form, per-agent effort and token counting, accept-edits and plan modes, an approval held and then approved from the pane, a question answered from the pane, launches on Windows and macOS (Terminal.app and iTerm2, the login-shell script, the tty record, focus by tty with balanced AppleScript blocks, case-insensitive paths on APFS), worker reporting, lead pickup and messaging, every pane plus the band on both terminal and Desktop, and a refused spawn keeping its full error (which you can copy from the agent's row).

Releasing

.claude-plugin/plugin.json is the plugin manifest and .claude-plugin/marketplace.json makes this repo a one-plugin marketplace ("source": "./"). claude plugin validate . checks both. When you release, bump version in both files so claude plugin marketplace update picks up the change.

What the mod calls (from claude plugin validate)

$.agent.spawn/list, $.session.send/messages/cwd/id, $.tool.call (TaskStop), $.tool.register, $.turn.abort, $.prompt.submit (a worker's first task), $.process.run (opening terminals: wt.exe/cmd start on Windows, open/osascript on macOS; focusing windows: PowerShell AppActivate or osascript; a worker reading its own PID (powershell / sh + ps); killing a worker: checking the name with Get-Process/ps, then taskkill/kill; ping/sleep as a one-second wait while a request is held; uname; chmod), $.fs.write (launch scripts under ~/.claude/swarm-mod/launch), $.fs.list/read (agent definitions, a worker's recorded tty), $.store (w:<id> worker reports, r:<id> lead replies and kill requests, roster:<name> saved rosters, last:<workspace> each workspace's last swarm, band), and $.state (the roster, kept across hot reloads).

Environment variables read: OS, USERPROFILE, HOME, TERM_PROGRAM, CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS, and the worker's SWARM_MOD_WORKER/LEAD/NAME/APPROVAL/TASK.

Extras built in

  • File-conflict radar: when two agents edit the same file (case-insensitive on Windows and macOS, matching NTFS and APFS defaults), you get a ▲ line in the pane, a warning in each agent's panel, and a toast.
  • Broadcast to every live agent.
  • Finished and failed lines in each agent's log, with toasts on failures.
  • Status tool so the lead Claude can coordinate the swarm with up-to-date information.

Ideas for later

  1. Worktree isolation per agent: an option to start a separate session in its own git worktree so edits never collide, with a merge view.
  2. Token and cost budgets: a per-agent or swarm-wide cap that warns at 80% and interrupts at 100% (turn.step can refuse further steps).
  3. Task board: show the team's shared task list (~/.claude/tasks/<team>/) with owners, color-coded by agent, plus drag-to-assign.
  4. File locks: when the conflict radar fires, the second agent's edit waits for the lead's OK, not just a warning.
  5. Supervisor digest: every N minutes, a Haiku summary of what each agent did ($.model.complete) in the pane.
  6. Stuck-task nudges: ping a teammate that sits on an in-progress task too long.
  7. Pause all: interrupt every agent's turn without killing it, then resume.
  8. Auto-launch a roster when a workspace opens (opt-in per roster).
  9. Remote approvals from your phone through Remote Control, using the same approval path.

Changes

  • 0.4.0: Every subagent or teammate spawned in the session joins the swarm, not just the ones spawned from the pane. An Edit form renames and retunes any agent, so ad-hoc subagents can be saved as a roster.
  • 0.3.1: Button labels drop the x: hotkey prefix (the hotkeys still work). The repo is now a plugin marketplace: install with /plugin marketplace add netgfx/claude-swarm-mod.
  • 0.3.0: First release: spawn, watch and steer a swarm of agents from a pane.

License

MIT. See LICENSE.

Source 3 files
hooks/register.js 1940 lines
1// swarm-mod: spawn, watch and steer a swarm of Claude Code agents from a pane.
2//
3// Two transports:
4//  - teammate: $.agent.spawn with a name, so it joins this session's agent team
5//    (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1) or runs as a named background agent.
6//    Its loop runs in this process, so these hooks see its steps, tools and checks.
7//  - session: a separate interactive `claude` in a new terminal, started in this
8//    workspace with this mod loaded. There the mod runs in "worker" mode and
9//    reports to the lead through $.store; the lead messages it over
10//    cross-session messaging and answers its approvals through $.store.
11
12import {
13  PALETTE, MODES, MODELS, EFFORTS, APPROVALS, BUILTIN_AGENTS, EDIT_TOOLS,
14  colorName, pickColor, labelOf, suggestName, adoptedName, validateName, fmtTokens, emptyTokens,
15  addUsage, totalTokens, clip, summarizeTool, describeCall, baseName, decide, statusView,
16  isLive, launchScript, launchCandidates, WORKER_SETTINGS, focusArgv, parseAgentFile, findConflicts, randomId,
17  selfPidArgv, parsePidLine, pidNameArgv, killArgv, RESTART_MAX, restartDelayMs, needsRestart, restartTask,
18  rosterEntry, rosterKey, lastRosterKey, planRoster, validRosterName, modelAlias,
19} from './lib.js'
20
21const MAIN = 'swarm'
22const WIZARD = 'swarm-spawn'
23const DETAIL = 'swarm-a-'
24const ROSTERS = 'swarm-rosters'
25const STATUS_TOOL = 'swarm_status'
26const TEAMMATE_HOLD_MS = 15 * 60 * 1000 // then the normal permission prompt
27const WORKER_HOLD_MS = 3 * 60 * 1000 // then the worker's own prompt
28const STALE_MS = 20000
29const LAUNCH_TIMEOUT_MS = 90000
30const LOG_MAX = 40
31const NAMES = ['scout', 'forge', 'atlas', 'echo', 'nova', 'pixel', 'rook', 'sage', 'vega', 'zephyr', 'orion', 'quill']
32
33// ---- lead state (module variables; snapshot kept in $.state across reloads) ----
34let agents = {} // key -> agent record
35let order = [] // keys, spawn order
36let platform = null // 'windows' | 'mac' | 'linux'
37let homeDir = ''
38let leadId = ''
39let callInfo = {} // tool_use_id -> { key, tool, input, workerMain }
40let decisions = {} // reqId -> decision, for holds in this process
41let agentTypes = {} // agent type -> description
42let draft = null // the spawn form
43let wizardError = ''
44let openPick = null // the spawn-form field whose option list is open
45let qDraft = {} // reqId -> { [question]: answer }
46let bandOn = true
47let expanded = {}
48let snapshotDirty = false
49let ticking = false
50let seenAttention = {}
51let seenConflicts = {}
52let conflicts = []
53let killArmed = false // kill-all asks for a second press
54let rosterList = [] // saved rosters, loaded when the roster pane opens
55let rosterNameDraft = ''
56let rosterError = ''
57let lastRoster = null // this workspace's last swarm, offered after a restart of Claude Code
58let lastSavedSig = ''
59let dismissed = {} // agentId -> true: subagents you removed, never adopted again
60let missUntil = {} // agentId -> time: loops no agent list names (workflow agents, forks), not looked up again until then
61
62// ---- worker state (only when this session was launched by a lead) ----
63let worker = null // { id, lead, name, approval }
64let w = null // what the worker reports
65let wDirty = false
66let wLastFlush = 0
67let wSeenAbort = 0
68
69// ======================= helpers that take $ =======================
70
71async function detectPlatform($) {
72  if (platform) return platform
73  let isWin = false
74  try {
75    const cwd = await $.session.cwd()
76    isWin = /^[A-Za-z]:[\\/]/.test(cwd) || cwd.startsWith('\\\\')
77  } catch {}
78  if (!isWin) {
79    try {
80      isWin = (await $.env.get('OS')) === 'Windows_NT'
81    } catch {}
82  }
83  if (isWin) {
84    platform = 'windows'
85  } else {
86    platform = 'linux'
87    try {
88      const r = await $.process.run(['uname', '-s'], { timeoutMs: 5000 })
89      if (String(r.stdout).trim() === 'Darwin') platform = 'mac'
90    } catch {}
91  }
92  return platform
93}
94
95function sep() {
96  return platform === 'windows' ? '\\' : '/'
97}
98
99async function toast($, text) {
100  try {
101    await $.ui.toast(text)
102  } catch {}
103}
104
105function changed($) {
106  snapshotDirty = true
107  $.ui.invalidate('ui.render')
108}
109
110async function persist($) {
111  if (!snapshotDirty) return
112  snapshotDirty = false
113  try {
114    await $.state.set({ plugin: 'swarm-mod', key: 'snapshot' }, { agents, order, dismissed: Object.keys(dismissed) })
115  } catch {}
116}
117
118async function restore($) {
119  try {
120    const { value } = await $.state.get({ plugin: 'swarm-mod', key: 'snapshot' })
121    if (value && Array.isArray(value.order) && value.agents) {
122      agents = { ...value.agents }
123      order = value.order.filter((k) => agents[k])
124    }
125    if (value && Array.isArray(value.dismissed)) for (const id of value.dismissed) dismissed[id] = true
126  } catch {}
127}
128
129// Waits about a second without a timer (hook budgets exclude time in $ calls)
130async function waitTick($) {
131  const argv = platform === 'windows' ? ['ping', '-n', '2', '127.0.0.1'] : ['sleep', '1']
132  try {
133    await $.process.run(argv, { timeoutMs: 5000 })
134  } catch {
135    await $.clock.sleep(250)
136  }
137}
138
139function pushLog(a, text, now) {
140  a.log = [...(a.log || []), { t: now, text: clip(text, 160) }].slice(-LOG_MAX)
141}
142
143function addFile(a, path) {
144  if (!path) return
145  const files = a.files || []
146  if (!files.includes(path)) a.files = [...files, path].slice(-200)
147}
148
149function keyOfAgentId(agentId) {
150  if (!agentId) return null
151  for (const k of order) if (agents[k] && agents[k].agentId === agentId) return k
152  return null
153}
154
155// Matches a loop id to a teammate whose spawn has not resolved yet, or adopts the
156// subagent it belongs to
157async function resolveKey($, agentId) {
158  const k = keyOfAgentId(agentId)
159  if (k || !agentId || worker || dismissed[agentId]) return k
160  const now = await $.clock.now()
161  if (missUntil[agentId] > now) return null
162  const waiting = order.filter((x) => agents[x].transport === 'teammate' && !agents[x].agentId && agents[x].status === 'pending')
163  try {
164    const list = await $.agent.list()
165    const hit = list.find((x) => x.id === agentId)
166    if (!hit) {
167      missUntil[agentId] = now + 10000
168      return null
169    }
170    const kk = waiting.find((x) => agents[x].name === hit.name || String(hit.teammateId || '').startsWith(agents[x].name + '@'))
171    if (kk) {
172      agents[kk].agentId = agentId
173      return kk
174    }
175    if (hit.spawnedBy !== 'swarm-mod') {
176      const ak = adopt({ agentId, name: hit.name, description: hit.description, type: hit.type, status: hit.status, teammateId: hit.teammateId, parentAgentId: hit.parentId }, now)
177      if (ak) changed($)
178      return ak
179    }
180  } catch {}
181  return null
182}
183
184function liveColors(exceptKey) {
185  return order.filter((k) => k !== exceptKey && isLive(agents[k])).map((k) => agents[k].color)
186}
187
188// Takes a subagent or teammate the swarm did not spawn (the model's Agent calls, another
189// plugin's) into the swarm, so it can be watched, renamed and saved in a roster.
190// info: { agentId, name, description, type, model, prompt, status, teammateId, parentAgentId }
191// Already adopted (its loop's events came first): fills in what the spawn tells.
192function adopt(info, now) {
193  if (worker || !info.agentId || dismissed[info.agentId]) return null
194  const known = keyOfAgentId(info.agentId)
195  if (known) {
196    const a = agents[known]
197    if (!a.adopted) return null
198    if (info.prompt && !a.task) a.task = info.prompt
199    if (info.model && a.model === 'inherit') a.model = info.model
200    if (info.resolvedModel) a.resolvedModel = info.resolvedModel
201    if (info.description && !a.description) a.description = info.description
202    if (info.name && !a.address) a.address = info.name
203    if (info.teammateId && !a.teammateId) a.teammateId = info.teammateId
204    return known
205  }
206  const key = randomId()
207  agents[key] = {
208    key, name: adoptedName(info, order.map((k) => agents[k].name)), color: pickColor(liveColors()),
209    agentType: info.type && !['teammate', 'general-purpose', 'fork'].includes(info.type) ? info.type : 'default', model: info.model || 'inherit',
210    effort: 'default', approval: 'default', transport: 'teammate', autoRestart: false, restarts: 0,
211    status: info.status || 'running', activity: '', tokens: emptyTokens(), ctx: 0, turns: 0, pending: null,
212    log: [{ t: now, text: clip('spawned outside the swarm: ' + (info.description || info.type || 'subagent'), 160) }],
213    files: [], lastAnswer: '', startedAt: now, task: info.prompt || '',
214    adopted: true, description: info.description || '', agentId: info.agentId,
215    teammateId: info.teammateId || null, address: info.name || '', parentAgentId: info.parentAgentId || '',
216    resolvedModel: info.resolvedModel || '',
217  }
218  order = [...order, key]
219  return key
220}
221
222// ======================= worker side =======================
223
224async function workerBoot($) {
225  w = {
226    status: 'idle', activity: '', tokens: emptyTokens(), ctx: 0, turns: 0, pending: null,
227    log: [], files: [], lastAnswer: '', turnId: '', sessionId: '', startedAt: (await $.clock.now()),
228  }
229  try {
230    w.sessionId = await $.session.id()
231  } catch {}
232  try {
233    const r = await $.store.get('r:' + worker.id)
234    wSeenAbort = (r && r.abortSeq) || 0
235  } catch {}
236  await workerFlush($)
237  try {
238    await $.ui.status('swarm worker "' + worker.name + '" · reporting to the lead session')
239  } catch {}
240  // this session's own pid, so the lead can end it (kill, or restart when it hangs)
241  try {
242    const r = await $.process.run(selfPidArgv(await detectPlatform($)), { timeoutMs: 20000 })
243    const p = parsePidLine(r.stdout)
244    if (p) {
245      w.pid = p.pid
246      w.pidName = p.name
247      await workerFlush($)
248    }
249  } catch {}
250}
251
252// The worker's first task, given in the spawn form
253async function submitTask($, text) {
254  try {
255    await $.prompt.submit({ text })
256  } catch (err) {
257    $.ui.log('swarm: could not submit the first task: ' + (err && err.message), { to: 'debug' })
258  }
259}
260
261async function workerFlush($) {
262  if (!worker || !w) return
263  wDirty = false
264  wLastFlush = (await $.clock.now())
265  try {
266    await $.store.set('w:' + worker.id, { ...w, name: worker.name, heartbeat: wLastFlush })
267  } catch {}
268}
269
270function workerLog(text, now) {
271  if (!w) return
272  w.log = [...w.log, { t: now, text: clip(text, 160) }].slice(-LOG_MAX)
273  wDirty = true
274}
275
276async function workerTick($) {
277  let r = null
278  try {
279    r = await $.store.get('r:' + worker.id)
280  } catch {}
281  if (r && r.abortSeq && r.abortSeq > wSeenAbort) {
282    wSeenAbort = r.abortSeq
283    if (w.turnId && w.status === 'working') {
284      try {
285        await $.turn.abort({ turnId: w.turnId })
286        workerLog('interrupted by the lead', (await $.clock.now()))
287      } catch {}
288    }
289  }
290  if (r && r.killed && w.status !== 'killed') {
291    // the lead killed this agent but could not end the process itself
292    w.status = 'killed'
293    w.pending = null
294    await workerFlush($)
295    if (w.pid) {
296      try {
297        await $.process.run(killArgv(await detectPlatform($), w.pid), { timeoutMs: 15000 })
298      } catch {}
299    }
300    return
301  }
302  if (wDirty || (await $.clock.now()) - wLastFlush > 5000) await workerFlush($)
303}
304
305// ======================= lead side: polling =======================
306
307function mergeReport(a, rep) {
308  const fields = ['status', 'activity', 'tokens', 'ctx', 'turns', 'log', 'files', 'lastAnswer', 'sessionId', 'heartbeat', 'pid', 'pidName', 'exitReason']
309  for (const f of fields) if (rep[f] !== undefined) a[f] = rep[f]
310  a.unresponsiveSince = null
311  a.pending = rep.pending && rep.pending.reqId !== a.resolvedReq ? rep.pending : null
312}
313
314async function leadTick($) {
315  let dirty = false
316  const now = (await $.clock.now())
317
318  if (!worker) {
319    let list = null
320    try {
321      list = await $.agent.list()
322    } catch {}
323    if (list) {
324      for (const k of order) {
325        const a = agents[k]
326        if (a.transport !== 'teammate' || a.agentId || a.status !== 'pending') continue
327        const hit = list.find((x) => x.name === a.name || String(x.teammateId || '').startsWith(a.name + '@'))
328        if (hit) {
329          a.agentId = hit.id
330          dirty = true
331        }
332      }
333      // subagents spawned outside the swarm: before this mod loaded, or while it reloaded
334      for (const x of list) {
335        if (x.spawnedBy === 'swarm-mod') continue
336        const isNew = !keyOfAgentId(x.id)
337        if (adopt({ agentId: x.id, name: x.name, description: x.description, type: x.type, status: x.status, teammateId: x.teammateId, parentAgentId: x.parentId }, now) && isNew) dirty = true
338      }
339      for (const k of order) {
340        const a = agents[k]
341        if (a.transport !== 'teammate' || !a.agentId || !isLive(a)) continue
342        const hit = list.find((x) => x.id === a.agentId)
343        const status = hit ? hit.status : 'completed'
344        if (hit && hit.teammateId && a.teammateId !== hit.teammateId) {
345          a.teammateId = hit.teammateId
346          dirty = true
347        }
348        if (status !== a.status) {
349          a.status = status
350          if (status === 'failed') await toast($, a.name + ' failed')
351          dirty = true
352        }
353      }
354    }
355  }
356
357  for (const k of order) {
358    const a = agents[k]
359    if (a.transport !== 'session' || a.killedByUser || a.restartAt || (['exited', 'failed'].includes(a.status) && !a.heartbeat)) continue
360    let rep = null
361    try {
362      rep = await $.store.get('w:' + k)
363    } catch {}
364    if (rep && rep.heartbeat) {
365      if (rep.heartbeat !== a.heartbeat) {
366        mergeReport(a, rep)
367        dirty = true
368      } else if (isLive(a) && a.status !== 'unresponsive' && now - rep.heartbeat > STALE_MS) {
369        a.status = 'unresponsive'
370        a.unresponsiveSince = now
371        dirty = true
372      }
373    } else if (a.status === 'launching' && now - a.startedAt > LAUNCH_TIMEOUT_MS) {
374      fail(a, 'No report from the new session. Is `claude` on PATH there? Script: ' + (a.script || '?'))
375      dirty = true
376    }
377  }
378
379  for (const k of order) {
380    const a = agents[k]
381    if (a.pending && seenAttention[k] !== a.pending.reqId) {
382      seenAttention[k] = a.pending.reqId
383      await toast($, a.name + (a.pending.kind === 'approval' ? ' needs approval' : ' has a question') + ' · open the swarm pane')
384    }
385  }
386
387  conflicts = findConflicts(order.map((k) => agents[k]), platform !== 'linux')
388  for (const c of conflicts) {
389    const id = c.path + '|' + c.keys.join(',')
390    if (!seenConflicts[id]) {
391      seenConflicts[id] = true
392      await toast($, '▲ ' + c.keys.map((k) => agents[k].name).join(' & ') + ' both edited ' + baseName(c.path))
393      dirty = true
394    }
395  }
396
397  // auto-restart: wait the backoff, then bring it back with the same settings
398  for (const k of [...order]) {
399    const a = agents[k]
400    if (!a) continue
401    if (!needsRestart(a, now)) {
402      if (a.restartAt) {
403        a.restartAt = null
404        dirty = true
405      }
406      continue
407    }
408    if (!a.restartAt) {
409      const delay = restartDelayMs(a.restarts || 0)
410      a.restartAt = now + delay
411      a.activity = 'restarting in ' + Math.round(delay / 1000) + 's (' + ((a.restarts || 0) + 1) + '/' + RESTART_MAX + ')'
412      await toast($, a.name + ' ' + (a.status === 'unresponsive' ? 'stopped responding' : a.status) + ' · auto-restart in ' + Math.round(delay / 1000) + 's')
413      dirty = true
414      continue
415    }
416    if (now >= a.restartAt) {
417      await restartAgent($, k)
418      dirty = true
419    }
420  }
421
422  if (dirty) changed($)
423}
424
425async function tick($) {
426  if (ticking) return
427  ticking = true
428  try {
429    if (worker && w) await workerTick($)
430    if (order.length || !worker) await leadTick($)
431    await persist($)
432    await saveLastRoster($)
433  } finally {
434    ticking = false
435  }
436}
437
438// ======================= kill, restart =======================
439
440// What TaskStop knows an in-process agent by
441function taskIdOf(a) {
442  return a.teammateId || (a.adopted ? a.agentId : a.address || a.name)
443}
444
445// Ends a separate session's process, after checking its pid still names the same program
446async function killPid($, a) {
447  if (!a.pid) return false
448  const os = await detectPlatform($)
449  try {
450    const r = await $.process.run(pidNameArgv(os, a.pid), { timeoutMs: 15000 })
451    const name = baseName(String(r.stdout || '').trim())
452    if (!name || (a.pidName && name.toLowerCase() !== String(a.pidName).toLowerCase())) return false
453    const k = await $.process.run(killArgv(os, a.pid), { timeoutMs: 15000 })
454    return k.exitCode === 0
455  } catch {
456    return false
457  }
458}
459
460async function killAgent($, key) {
461  const a = agents[key]
462  if (!a) return false
463  const wasLive = isLive(a) || !!a.restartAt
464  a.killedByUser = true
465  a.restartAt = null
466  // release a request it is holding, so nothing waits on a dead agent
467  if (a.pending) {
468    decisions[a.pending.reqId] = { decision: 'deny' }
469    a.pending = null
470  }
471  if (a.transport === 'teammate') {
472    if (isLive(a)) {
473      try {
474        await $.tool.call({ tool: 'TaskStop', task_id: taskIdOf(a) })
475      } catch (err) {
476        $.ui.log('swarm: TaskStop ' + a.name + ': ' + (err && err.message), { to: 'debug' })
477      }
478    }
479  } else {
480    let cur = null
481    try {
482      cur = await $.store.get('r:' + key)
483    } catch {}
484    try {
485      await $.store.set('r:' + key, { ...(cur || { decisions: {}, abortSeq: 0 }), killed: true })
486    } catch {}
487    const ended = await killPid($, a)
488    pushLog(a, ended ? 'process ' + a.pid + ' ended' : 'asked the session to end itself', await $.clock.now())
489  }
490  a.status = 'killed'
491  a.activity = ''
492  pushLog(a, '■ killed by you', await $.clock.now())
493  changed($)
494  return wasLive
495}
496
497async function killAll($) {
498  killArmed = false
499  let n = 0
500  for (const k of [...order]) if (agents[k] && (await killAgent($, k))) n++
501  await toast($, 'Killed ' + n + ' agent' + (n === 1 ? '' : 's'))
502  changed($)
503  return n
504}
505
506async function restartAgent($, key, manual) {
507  const a = agents[key]
508  if (!a) return
509  a.restartAt = null
510  if (manual) {
511    a.killedByUser = false
512    a.restarts = 0
513    pushLog(a, '↻ respawned by you', await $.clock.now())
514  } else {
515    a.restarts = (a.restarts || 0) + 1
516    pushLog(a, '↻ auto-restart ' + a.restarts + '/' + RESTART_MAX, await $.clock.now())
517  }
518  a.pending = null
519  a.error = ''
520  if (a.transport === 'session') {
521    if (a.status === 'unresponsive' || (manual && isLive(a))) await killPid($, a)
522    try {
523      await $.store.delete('w:' + key)
524    } catch {}
525    a.heartbeat = null
526    a.unresponsiveSince = null
527    a.exitReason = null
528    a.pid = null
529    a.pidName = null
530    a.sessionId = ''
531    a.status = 'launching'
532    a.startedAt = await $.clock.now()
533    await launchWorker($, a, manual ? a.task : restartTask(a.task))
534  } else {
535    a.agentId = null
536    a.teammateId = null
537    a.adopted = false
538    a.status = 'pending'
539    await spawnTeammate($, a, manual ? a.task : restartTask(a.task))
540  }
541  await toast($, a.name + (manual ? ' respawned' : ' restarted (' + a.restarts + '/' + RESTART_MAX + ')'))
542  changed($)
543}
544
545// ======================= saved rosters =======================
546
547function currentRoster(onlyOwn) {
548  return order.filter((k) => !onlyOwn || !agents[k].adopted).map((k) => rosterEntry(agents[k]))
549}
550
551// Keeps this workspace's latest swarm, offered again when Claude Code restarts here.
552// Subagents it only adopted stay out: save a roster to keep them.
553async function saveLastRoster($) {
554  if (worker || !order.length) return
555  const entries = currentRoster(true)
556  if (!entries.length) return
557  const sig = JSON.stringify(entries)
558  if (sig === lastSavedSig) return
559  lastSavedSig = sig
560  try {
561    const cwd = await $.session.cwd()
562    await $.store.set(lastRosterKey(cwd, platform !== 'linux'), { cwd, savedAt: await $.clock.now(), agents: entries })
563  } catch {}
564}
565
566async function loadRosters($) {
567  const list = []
568  let keys = []
569  try {
570    keys = await $.store.keys()
571  } catch {}
572  for (const key of keys) {
573    if (!key.startsWith('roster:')) continue
574    try {
575      const v = await $.store.get(key)
576      if (v && Array.isArray(v.agents)) list.push({ ...v, key, name: key.slice('roster:'.length) })
577    } catch {}
578  }
579  rosterList = list.sort((x, y) => (y.savedAt || 0) - (x.savedAt || 0))
580  return rosterList
581}
582
583async function saveRoster($, rawName) {
584  const name = String(rawName || '').trim()
585  if (!validRosterName(name)) {
586    rosterError = 'Roster name: 1-40 letters, digits, spaces, . _ or -'
587    $.ui.invalidate('ui.render')
588    return false
589  }
590  if (!order.length) {
591    rosterError = 'The swarm is empty; spawn agents first'
592    $.ui.invalidate('ui.render')
593    return false
594  }
595  let cwd = ''
596  try {
597    cwd = await $.session.cwd()
598  } catch {}
599  await loadRosters($)
600  const existed = rosterList.some((r) => r.name === name)
601  await $.store.set(rosterKey(name), { cwd, savedAt: await $.clock.now(), agents: currentRoster() })
602  rosterError = ''
603  rosterNameDraft = ''
604  await loadRosters($)
605  await toast($, (existed ? 'Updated' : 'Saved') + ' roster "' + name + '" (' + order.length + ' agents)')
606  $.ui.invalidate('ui.render')
607  return true
608}
609
610async function deleteRoster($, name) {
611  try {
612    await $.store.delete(rosterKey(name))
613  } catch {}
614  await loadRosters($)
615  $.ui.invalidate('ui.render')
616}
617
618// Spawns every agent of a roster into this workspace, with free names and colors
619async function launchRoster($, entries, label) {
620  const plan = planRoster(entries || [], order.map((k) => agents[k].name), liveColors())
621  lastRoster = null
622  try {
623    await $.ui.open({ id: MAIN, title: 'Swarm' })
624  } catch {}
625  for (const e of plan) await spawnSpec($, e)
626  await toast($, 'Spawned ' + plan.length + ' agent' + (plan.length === 1 ? '' : 's') + (label ? ' from "' + label + '"' : ''))
627  return plan.length
628}
629
630async function openRosters($) {
631  await loadRosters($)
632  rosterError = ''
633  let cwd = ''
634  try {
635    cwd = await $.session.cwd()
636  } catch {}
637  if (!rosterNameDraft) rosterNameDraft = baseName(String(cwd).replace(/[\\/]+$/, '')) || 'my swarm'
638  await $.ui.open({ id: ROSTERS, title: 'Rosters', focus: true, closeOnEscape: true })
639}
640
641// ======================= holds (approvals and questions) =======================
642
643async function setPending($, key, pending) {
644  if (key) {
645    const a = agents[key]
646    a.pending = pending
647    pushLog(a, (pending.kind === 'approval' ? '! approval: ' + pending.summary : '? question'), (await $.clock.now()))
648    if (seenAttention[key] !== pending.reqId) {
649      seenAttention[key] = pending.reqId
650      await toast($, a.name + (pending.kind === 'approval' ? ' needs approval' : ' has a question') + ' · open the swarm pane')
651    }
652    changed($)
653  } else if (w) {
654    w.pending = pending
655    workerLog(pending.kind === 'approval' ? '! approval: ' + pending.summary : '? question', (await $.clock.now()))
656    await workerFlush($)
657    try {
658      await $.ui.status('swarm: waiting for the lead to ' + (pending.kind === 'approval' ? 'approve ' + pending.summary : 'answer a question') + ' (falls back to the prompt here)')
659    } catch {}
660  }
661}
662
663async function clearPending($, key, reqId) {
664  if (key) {
665    if (agents[key] && agents[key].pending && agents[key].pending.reqId === reqId) agents[key].pending = null
666    changed($)
667  } else if (w) {
668    if (w.pending && w.pending.reqId === reqId) w.pending = null
669    await workerFlush($)
670    try {
671      await $.ui.status('swarm worker "' + worker.name + '" · reporting to the lead session')
672    } catch {}
673  }
674}
675
676// Waits for a decision from the pane (this process) or the lead (worker); null on timeout
677async function holdFor($, reqId, ms, signal) {
678  const until = (await $.clock.now()) + ms
679  while ((await $.clock.now()) < until) {
680    if (signal && signal.aborted) return null
681    if (decisions[reqId]) {
682      const d = decisions[reqId]
683      delete decisions[reqId]
684      return d
685    }
686    if (worker) {
687      let r = null
688      try {
689        r = await $.store.get('r:' + worker.id)
690      } catch {}
691      const d = r && r.decisions && r.decisions[reqId]
692      if (d) return d
693    }
694    await waitTick($)
695  }
696  return null
697}
698
699async function holdQuestion($, key, e, signal) {
700  const reqId = randomId()
701  const questions = (e.questions || []).map((q) => ({
702    question: q.question,
703    header: q.header || '',
704    multiSelect: !!q.multiSelect,
705    options: (q.options || []).map((o) => ({ label: o.label, description: o.description || '' })),
706  }))
707  await setPending($, key, { kind: 'question', reqId, tool: 'AskUserQuestion', summary: clip(questions[0] && questions[0].question, 60), questions, since: (await $.clock.now()) })
708  const d = await holdFor($, reqId, key ? TEAMMATE_HOLD_MS : WORKER_HOLD_MS, signal)
709  await clearPending($, key, reqId)
710  if (!d || !d.answers) return null
711  return { questions: e.questions, answers: d.answers }
712}
713
714// The lead resolves an agent's pending request
715async function resolvePending($, key, decision) {
716  const a = agents[key]
717  const p = a && a.pending
718  if (!p) return
719  if (a.transport === 'session') {
720    let cur = null
721    try {
722      cur = await $.store.get('r:' + key)
723    } catch {}
724    cur = cur || { decisions: {}, abortSeq: 0 }
725    const kept = Object.entries(cur.decisions || {}).slice(-20)
726    await $.store.set('r:' + key, { ...cur, decisions: { ...Object.fromEntries(kept), [p.reqId]: decision } })
727  } else {
728    decisions[p.reqId] = decision
729  }
730  a.resolvedReq = p.reqId
731  a.pending = null
732  delete qDraft[p.reqId]
733  const what = decision.answers ? 'answered' : decision.decision === 'allow' ? 'approved' : decision.decision === 'deny' ? 'denied' : 'sent to its own prompt'
734  pushLog(a, 'you ' + what + ': ' + p.summary, (await $.clock.now()))
735  changed($)
736}
737
738// ======================= spawning =======================
739
740async function scanAgentFiles($) {
741  const dirs = ['.claude' + sep() + 'agents']
742  if (homeDir) dirs.unshift(homeDir + sep() + '.claude' + sep() + 'agents')
743  for (const d of dirs) {
744    let entries = []
745    try {
746      entries = await $.fs.list(d)
747    } catch {
748      continue
749    }
750    for (const ent of entries.slice(0, 80)) {
751      if (ent.kind === 'directory' || !/\.md$/i.test(ent.name)) continue
752      try {
753        const parsed = parseAgentFile(await $.fs.read(d + sep() + ent.name))
754        if (parsed && !agentTypes[parsed.name]) agentTypes[parsed.name] = parsed.description
755      } catch {}
756    }
757  }
758}
759
760// The spawn form; with a key, the same form edits that agent instead
761async function openWizard($, editKey) {
762  await scanAgentFiles($)
763  const taken = order.map((k) => agents[k].name)
764  let teamsOn = false
765  try {
766    teamsOn = (await $.env.get('CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS')) === '1'
767  } catch {}
768  let cwd = ''
769  try {
770    cwd = await $.session.cwd()
771  } catch {}
772  draft = {
773    mode: 'teammate',
774    agentType: 'default',
775    model: 'inherit',
776    effort: 'default',
777    approval: 'default',
778    name: suggestName(NAMES.find((n) => !taken.map((t) => t.toLowerCase()).includes(n)) || 'agent', taken),
779    color: pickColor(liveColors()),
780    task: '',
781    teamsOn,
782    autoRestart: false,
783    cwd,
784  }
785  const a = editKey && agents[editKey]
786  if (a) {
787    draft = {
788      ...draft, editKey, mode: a.transport, agentType: a.agentType, model: a.model, effort: a.effort, approval: a.approval,
789      name: a.name, color: a.color, task: a.task || '', autoRestart: !!a.autoRestart,
790    }
791    if (a.agentType !== 'default' && !agentTypes[a.agentType] && !BUILTIN_AGENTS.includes(a.agentType)) agentTypes[a.agentType] = ''
792  }
793  wizardError = ''
794  openPick = null
795  await $.ui.open({ id: WIZARD, title: a ? 'Edit ' + a.name : 'Spawn agent', focus: true, closeOnEscape: true, rows: 36 })
796}
797
798// Saves the form onto the agent it edits. Name, color, effort and approval mode take
799// effect now; type, model, transport and task when it respawns or launches from a roster.
800async function saveEdit($) {
801  const d = draft
802  const a = d && agents[d.editKey]
803  if (!a) return
804  const name = String(d.name || '').trim()
805  const err = validateName(name, order.filter((k) => k !== a.key).map((k) => agents[k].name))
806  if (err) {
807    wizardError = err
808    $.ui.invalidate('ui.render')
809    return
810  }
811  if (d.color !== a.color && liveColors(a.key).includes(d.color) && liveColors(a.key).length < PALETTE.length) {
812    wizardError = 'That color is in use; pick another'
813    $.ui.invalidate('ui.render')
814    return
815  }
816  if (name !== a.name) pushLog(a, 'renamed from ' + a.name, await $.clock.now())
817  Object.assign(a, {
818    name, color: d.color, agentType: d.agentType, model: d.model, effort: d.effort, approval: d.approval,
819    task: d.task || '', autoRestart: !!d.autoRestart,
820  })
821  if (!isLive(a)) a.transport = d.mode
822  if (!a.autoRestart) a.restartAt = null
823  draft = null
824  try {
825    await $.ui.close({ id: WIZARD })
826  } catch {}
827  await toast($, 'Saved ' + name)
828  changed($)
829}
830
831async function spawnTeammate($, a, taskOverride) {
832  let cwd = ''
833  try {
834    cwd = await $.session.cwd()
835  } catch {}
836  const prompt = (taskOverride || a.task || '').trim() ||
837    'You are "' + a.name + '", a member of the user\'s agent swarm, working in ' + cwd + '. Introduce yourself in one line, then wait for instructions.'
838  const args = { prompt, description: 'swarm: ' + a.name, name: a.name }
839  if (a.agentType && a.agentType !== 'default') args.subagentType = a.agentType
840  const alias = a.model && a.model !== 'inherit' ? modelAlias(a.model) : ''
841  if (alias) args.model = alias
842  let r
843  try {
844    r = await $.agent.spawn(args)
845  } catch (err) {
846    fail(a, 'Spawn failed: ' + String((err && err.message) || err))
847    await toast($, a.activity)
848    return
849  }
850  if (!r || r.deny) {
851    fail(a, 'Spawn refused: ' + String((r && r.deny) || 'no answer from the agent spawner'))
852    await toast($, a.activity)
853    return
854  }
855  a.agentId = r.agentId
856  a.teammateId = r.teammateId
857  a.resolvedModel = r.model
858  if (r.teammateId) a.name = String(r.teammateId).split('@')[0] || a.name
859  a.address = a.name
860  // without an id yet, it stays pending and is matched by name from $.agent.list()
861  if (a.agentId && a.status === 'pending') a.status = 'running'
862  a.activity = ''
863  pushLog(a, r.teammateId ? 'joined the team as ' + r.teammateId : 'started as a named background agent', (await $.clock.now()))
864}
865
866async function launchWorker($, a, taskOverride) {
867  const os = await detectPlatform($)
868  let cwd = ''
869  try {
870    cwd = await $.session.cwd()
871  } catch {}
872  if (!homeDir) {
873    fail(a, 'Could not find the home directory to write the launch script')
874    return
875  }
876  const s = sep()
877  const dir = homeDir + s + '.claude' + s + 'swarm-mod' + s + 'launch' + s
878  const script = dir + a.key + (os === 'windows' ? '.ps1' : os === 'mac' ? '.command' : '.sh')
879  const settingsPath = dir + 'worker-settings.json'
880  const ttyPath = os === 'windows' ? '' : dir + a.key + '.tty'
881  const spec = {
882    id: a.key, lead: leadId, name: a.name, cwd, pluginRoot: $.plugin.root, settingsPath, ttyPath,
883    agentType: a.agentType, model: a.model, effort: a.effort, approval: a.approval, task: taskOverride || a.task,
884  }
885  a.script = script
886  a.ttyPath = ttyPath
887  let iterm = false
888  if (os === 'mac') {
889    try {
890      iterm = (await $.env.get('TERM_PROGRAM')) === 'iTerm.app'
891    } catch {}
892  }
893  try {
894    await $.fs.write(settingsPath, WORKER_SETTINGS)
895    await $.fs.write(script, launchScript(os === 'windows' ? 'windows' : 'posix', spec))
896    await $.store.set('r:' + a.key, { decisions: {}, abortSeq: 0 })
897  } catch (err) {
898    fail(a, 'Could not write the launch script: ' + String((err && err.message) || err))
899    return
900  }
901  if (os !== 'windows') {
902    try {
903      await $.process.run(['chmod', '+x', script], { timeoutMs: 5000 })
904    } catch {}
905  }
906  let lastErr = ''
907  for (const { argv, app } of launchCandidates(os, script, spec, { iterm })) {
908    try {
909      const r = await $.process.run(argv, { cwd, timeoutMs: 15000 })
910      if (r.exitCode === 0) {
911        a.termApp = app
912        pushLog(a, 'launched in a new ' + app + ' window', (await $.clock.now()))
913        a.activity = 'waiting for the session to start…'
914        return
915      }
916      lastErr = String(r.stderr || r.stdout || 'exit ' + r.exitCode).trim()
917    } catch (err) {
918      lastErr = String(err && err.message)
919    }
920  }
921  fail(a, 'Could not open a terminal (' + String(lastErr) + '). Run it yourself: ' + script)
922}
923
924async function spawnFromDraft($) {
925  const d = draft
926  if (!d || d.editKey) return
927  const taken = order.map((k) => agents[k].name)
928  const name = String(d.name || '').trim()
929  const err = validateName(name, taken)
930  if (err) {
931    wizardError = err
932    $.ui.invalidate('ui.render')
933    return
934  }
935  if (liveColors().includes(d.color) && liveColors().length < PALETTE.length) {
936    wizardError = 'That color is in use; pick another'
937    $.ui.invalidate('ui.render')
938    return
939  }
940  draft = null
941  try {
942    await $.ui.close({ id: WIZARD })
943  } catch {}
944  try {
945    await $.ui.open({ id: MAIN, title: 'Swarm' })
946  } catch {}
947  await spawnSpec($, {
948    name, color: d.color, agentType: d.agentType, model: d.model, effort: d.effort, approval: d.approval,
949    transport: d.mode, task: d.task || '', autoRestart: !!d.autoRestart,
950  })
951}
952
953// Adds one agent to the swarm and starts it: from the form, a roster, or a restore
954async function spawnSpec($, spec) {
955  const key = randomId()
956  const transport = spec.transport === 'session' ? 'session' : 'teammate'
957  const a = {
958    key, name: spec.name, color: spec.color, agentType: spec.agentType || 'default', model: spec.model || 'inherit',
959    effort: spec.effort || 'default', approval: spec.approval || 'default', transport,
960    autoRestart: !!spec.autoRestart, restarts: 0,
961    status: transport === 'session' ? 'launching' : 'pending', activity: 'spawning…',
962    tokens: emptyTokens(), ctx: 0, turns: 0, pending: null, log: [], files: [], lastAnswer: '',
963    startedAt: await $.clock.now(), task: spec.task || '',
964  }
965  agents[key] = a
966  order = [...order, key]
967  lastRoster = null
968  changed($)
969  if (transport === 'teammate') await spawnTeammate($, a)
970  else await launchWorker($, a)
971  changed($)
972  return key
973}
974
975// ======================= actions on an agent =======================
976
977// Marks an agent failed: the whole error is kept for copying, a short line is shown
978function fail(a, text) {
979  a.status = 'failed'
980  a.error = String(text)
981  a.activity = clip(a.error, 140)
982}
983
984// Copies an agent's whole error (not the clipped line) to the clipboard of the surface pressed on
985async function copyError($, key, press) {
986  const a = agents[key]
987  if (!a) return
988  const text = a.error || a.activity || ''
989  if (!text) return toast($, a.name + ' has no error text to copy')
990  let r
991  try {
992    r = await $.ui.copy({ text, ...(press && press.surface ? { surface: press.surface } : {}) })
993  } catch (err) {
994    r = { isCopied: false, reason: err && err.message }
995  }
996  await toast($, r.isCopied ? 'Copied ' + a.name + "'s error (" + text.length + ' chars)' : 'Could not copy the error: ' + r.reason)
997}
998
999async function sendTo($, key, text) {
1000  const a = agents[key]
1001  const t = String(text || '').trim()
1002  if (!a || !t) return false
1003  let to = null
1004  if (a.transport === 'session') {
1005    if (!a.sessionId) {
1006      await toast($, a.name + ' has not reported its session yet')
1007      return false
1008    }
1009    to = { sessionId: a.sessionId }
1010  } else if (a.agentId) {
1011    to = { agentId: a.agentId }
1012  }
1013  if (!to) return false
1014  try {
1015    let r = await $.session.send({ to, text: t })
1016    if (!r.isDelivered && a.transport === 'teammate' && (a.address || !a.adopted)) r = await $.session.send({ to: a.address || a.name, text: t })
1017    if (r.isDelivered) {
1018      pushLog(a, '→ you: ' + t, (await $.clock.now()))
1019      changed($)
1020      return true
1021    }
1022    await toast($, 'Not delivered to ' + a.name + ': ' + r.reason)
1023  } catch (err) {
1024    await toast($, 'Not delivered to ' + a.name + ': ' + (err && err.message))
1025  }
1026  return false
1027}
1028
1029async function broadcast($, text) {
1030  let n = 0
1031  for (const k of order) if (isLive(agents[k]) && (await sendTo($, k, text))) n++
1032  await toast($, 'Broadcast reached ' + n + ' agent' + (n === 1 ? '' : 's'))
1033}
1034
1035async function stopAgent($, key) {
1036  const a = agents[key]
1037  if (!a) return
1038  if (a.transport === 'session') {
1039    let cur = null
1040    try {
1041      cur = await $.store.get('r:' + key)
1042    } catch {}
1043    cur = cur || { decisions: {}, abortSeq: 0 }
1044    await $.store.set('r:' + key, { ...cur, abortSeq: (cur.abortSeq || 0) + 1 })
1045    pushLog(a, 'interrupt requested', (await $.clock.now()))
1046  } else {
1047    try {
1048      await $.tool.call({ tool: 'TaskStop', task_id: taskIdOf(a) })
1049      pushLog(a, 'stop requested', (await $.clock.now()))
1050    } catch (err) {
1051      await toast($, 'Could not stop ' + a.name + ': ' + (err && err.message))
1052    }
1053  }
1054  changed($)
1055}
1056
1057async function focusWindow($, key) {
1058  const a = agents[key]
1059  if (!a) return
1060  const os = await detectPlatform($)
1061  let tty = ''
1062  if (a.ttyPath) {
1063    try {
1064      tty = String(await $.fs.read(a.ttyPath)).trim()
1065    } catch {}
1066  }
1067  try {
1068    const r = await $.process.run(focusArgv(os, a.name, { tty: /^\/dev\//.test(tty) ? tty : '', app: a.termApp }), { timeoutMs: 10000 })
1069    if (r.exitCode !== 0) throw new Error(String(r.stderr || 'exit ' + r.exitCode).trim())
1070  } catch (err) {
1071    const hint = os === 'mac' ? ' (allow Automation for your terminal in System Settings > Privacy & Security)' : ''
1072    await toast($, 'Could not bring ' + a.name + ' forward' + hint + '; look for its "' + a.name + '" window or tab')
1073  }
1074}
1075
1076async function removeAgent($, key) {
1077  const a = agents[key]
1078  if (!a) return
1079  delete agents[key]
1080  order = order.filter((k) => k !== key)
1081  if (a.agentId) dismissed[a.agentId] = true
1082  try {
1083    await $.store.delete('w:' + key)
1084    await $.store.delete('r:' + key)
1085  } catch {}
1086  try {
1087    await $.ui.close({ id: DETAIL + key })
1088  } catch {}
1089  changed($)
1090}
1091
1092async function openDetail($, key) {
1093  const a = agents[key]
1094  if (!a) return
1095  await $.ui.open({
1096    id: DETAIL + key,
1097    title: a.name,
1098    focus: true,
1099    closeOnEscape: true,
1100    ...(expanded[key] ? { rows: 40, columns: 110 } : {}),
1101  })
1102}
1103
1104function statusText() {
1105  if (!order.length) return 'The swarm is empty. The user spawns agents from the swarm pane (/swarm).'
1106  return order
1107    .map((k) => {
1108      const a = agents[k]
1109      const sv = statusView(a)
1110      return [
1111        a.name + ' (' + (a.adopted ? 'subagent' : a.transport) + ', ' + a.agentType + ', ' + labelOf(MODELS, a.model) + ', effort ' + a.effort + ', approval ' + a.approval + ')',
1112        'status: ' + sv.word + (a.activity ? ' - ' + a.activity : ''),
1113        'tokens: ' + fmtTokens(totalTokens(a.tokens)) + ', turns: ' + (a.turns || 0) + (a.autoRestart ? ', auto-restart on (' + (a.restarts || 0) + '/' + RESTART_MAX + ' used)' : ''),
1114        a.pending ? 'waiting on the user: ' + a.pending.summary : '',
1115        a.lastAnswer ? 'last answer: ' + clip(a.lastAnswer, 300) : '',
1116      ].filter(Boolean).join('\n  ')
1117    })
1118    .join('\n')
1119}
1120
1121// ======================= drawing =======================
1122
1123function counts() {
1124  const list = order.map((k) => agents[k])
1125  return {
1126    list,
1127    working: list.filter((a) => ['running', 'working'].includes(a.status)).length,
1128    attention: list.filter((a) => a.pending).length,
1129    total: list.reduce((s, a) => s + totalTokens(a.tokens), 0),
1130  }
1131}
1132
1133function renderMain($, e) {
1134  const { Box, Text, Button, Input } = $.ui.resolve(e)
1135  const { list, working, attention, total } = counts()
1136  const rows = []
1137  rows.push(
1138    Box({
1139      key: 'head',
1140      flexDirection: 'row',
1141      columnGap: 1,
1142      children: [
1143        Text({ bold: true, color: '#c678dd', children: ['SWARM'] }),
1144        Text({ dimColor: true, children: [list.length + ' agents · ' + working + ' working'] }),
1145        ...(attention ? [Text({ bold: true, color: '#ff5555', children: ['· ' + attention + ' need you'] })] : []),
1146      ],
1147    }),
1148  )
1149  const liveCount = list.filter((a) => isLive(a) || a.restartAt).length
1150  rows.push(
1151    Box({
1152      key: 'toolbar',
1153      flexDirection: 'row',
1154      columnGap: 2,
1155      children: [
1156        Button({ key: 'spawn', label: 'n: + Spawn agent', hotkey: 'n', onPress: () => openWizard($) }),
1157        Button({ key: 'rosters', label: 'Rosters', hotkey: 'r', plain: true, onPress: () => openRosters($) }),
1158        ...(liveCount
1159          ? [Button({
1160              key: 'kill-all',
1161              label: killArmed ? 'k: Press again to kill ' + liveCount : 'Kill all',
1162              hotkey: 'k',
1163              ...(killArmed ? {} : { plain: true }),
1164              onPress: async () => {
1165                if (!killArmed) {
1166                  killArmed = true
1167                  $.ui.invalidate('ui.render')
1168                  $.clock.after(6000, () => {
1169                    killArmed = false
1170                    $.ui.invalidate('ui.render')
1171                  })
1172                  return
1173                }
1174                await killAll($)
1175              },
1176            })]
1177          : []),
1178      ],
1179    }),
1180  )
1181  if (lastRoster && lastRoster.agents && lastRoster.agents.length) {
1182    rows.push(
1183      Button({
1184        key: 'restore-last',
1185        label: 'Restore last swarm here (' + lastRoster.agents.length + ' agents: ' + clip(lastRoster.agents.map((x) => x.name).join(', '), 50) + ')',
1186        onPress: () => launchRoster($, lastRoster.agents, 'last swarm'),
1187      }),
1188    )
1189  }
1190  if (!list.length) {
1191    rows.push(Text({ dimColor: true, children: ['No agents yet. Spawn one, or launch a saved roster (r).'] }))
1192  }
1193  for (const a of list) {
1194    const sv = statusView(a)
1195    rows.push(
1196      Box({
1197        key: 'row-' + a.key,
1198        flexDirection: 'column',
1199        children: [
1200          Box({
hooks/lib.js 517 lines
1// Pure helpers for swarm-mod: no mods API calls here, so they can be imported
2// and unit tested freely.
3
4// Distinct, readable on dark and light themes. Hex works on both surfaces.
5export const PALETTE = [
6  { hex: '#e06c75', name: 'coral' },
7  { hex: '#98c379', name: 'green' },
8  { hex: '#e5c07b', name: 'gold' },
9  { hex: '#61afef', name: 'blue' },
10  { hex: '#c678dd', name: 'violet' },
11  { hex: '#56b6c2', name: 'teal' },
12  { hex: '#d19a66', name: 'orange' },
13  { hex: '#ff79c6', name: 'pink' },
14  { hex: '#8be9fd', name: 'sky' },
15  { hex: '#50fa7b', name: 'mint' },
16  { hex: '#bd93f9', name: 'lavender' },
17  { hex: '#f1fa8c', name: 'lemon' },
18]
19
20export function colorName(hex) {
21  const hit = PALETTE.find((c) => c.hex === hex)
22  return hit ? hit.name : hex
23}
24
25// A random palette color no live agent uses; any color once all are taken
26export function pickColor(used, rand = Math.random) {
27  const free = PALETTE.filter((c) => !used.includes(c.hex))
28  const pool = free.length ? free : PALETTE
29  return pool[Math.floor(rand() * pool.length) % pool.length].hex
30}
31
32export const MODES = [
33  { value: 'teammate', label: 'Teammate (agent team, in this session)' },
34  { value: 'session', label: 'Separate Claude Code session (own window)' },
35]
36
37export const MODELS = [
38  { value: 'inherit', label: "Inherit (lead's model)" },
39  { value: 'claude-opus-5-5', label: 'Opus 5.5' },
40  { value: 'claude-sonnet-5-5', label: 'Sonnet 5.5' },
41  { value: 'claude-haiku-4-5-20251001', label: 'Haiku 4.5' },
42  { value: 'claude-fable-5-1', label: 'Fable 5.1' },
43]
44
45// $.agent.spawn only takes family aliases; `claude --model` takes full ids.
46// Maps a stored model value to its alias, or '' when it has none.
47export function modelAlias(model) {
48  const m = String(model || '').toLowerCase()
49  return ['opus', 'sonnet', 'haiku', 'fable'].find((f) => m === f || m.includes('-' + f + '-') || m.startsWith(f + '-')) || ''
50}
51
52export const EFFORTS = [
53  { value: 'default', label: 'Default' },
54  { value: 'low', label: 'Low' },
55  { value: 'medium', label: 'Medium' },
56  { value: 'high', label: 'High' },
57  { value: 'xhigh', label: 'Extra high' },
58  { value: 'max', label: 'Max' },
59]
60
61export const APPROVALS = [
62  { value: 'default', label: 'Ask me (default)' },
63  { value: 'acceptEdits', label: 'Accept edits' },
64  { value: 'auto', label: 'Auto' },
65  { value: 'plan', label: 'Plan / read-only' },
66  { value: 'dontAsk', label: "Don't ask (deny unless pre-approved)" },
67  { value: 'bypassPermissions', label: 'Bypass all checks (dangerous)' },
68]
69
70export const BUILTIN_AGENTS = ['general-purpose', 'Explore', 'Plan']
71
72export const EDIT_TOOLS = ['Edit', 'Write', 'NotebookEdit', 'MultiEdit']
73
74export const NAME_RE = /^[A-Za-z0-9_-]{1,40}$/
75
76export function labelOf(list, value) {
77  const hit = list.find((o) => o.value === value)
78  return hit ? hit.label : String(value)
79}
80
81// "scout", "scout-2", ... the first one nobody has
82export function suggestName(base, taken) {
83  const clean = String(base || 'agent').replace(/[^A-Za-z0-9_-]/g, '-').replace(/^-+|-+$/g, '').slice(0, 30) || 'agent'
84  const lower = taken.map((t) => t.toLowerCase())
85  if (!lower.includes(clean.toLowerCase())) return clean
86  for (let i = 2; i < 1000; i++) {
87    const n = clean + '-' + i
88    if (!lower.includes(n.toLowerCase())) return n
89  }
90  return clean + '-' + Date.now()
91}
92
93// A swarm name for a subagent someone else spawned: its own name, else a slug of
94// its description ("Game UI / HUD cards" -> "game-ui-hud-cards"), else its type
95export function adoptedName(info, taken) {
96  const slug = (s) => String(s || '').toLowerCase().replace(/[^a-z0-9_]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 30).replace(/-+$/, '')
97  return suggestName(slug(info.name) || slug(info.description) || slug(info.type) || 'subagent', taken)
98}
99
100export function validateName(name, taken) {
101  if (!NAME_RE.test(name)) return 'Name: 1-40 letters, digits, - or _'
102  if (taken.map((t) => t.toLowerCase()).includes(name.toLowerCase())) return 'Name "' + name + '" is taken in this swarm'
103  return null
104}
105
106export function fmtTokens(n) {
107  const v = Number(n) || 0
108  if (v < 1000) return String(v)
109  if (v < 1e6) return (v / 1000).toFixed(v < 1e4 ? 1 : 0) + 'k'
110  return (v / 1e6).toFixed(2) + 'M'
111}
112
113export function emptyTokens() {
114  return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
115}
116
117// Adds one API response's usage; returns that response's context size
118export function addUsage(tokens, usage) {
119  if (!usage) return 0
120  tokens.input += usage.input_tokens || 0
121  tokens.output += usage.output_tokens || 0
122  tokens.cacheRead += usage.cache_read_input_tokens || 0
123  tokens.cacheWrite += usage.cache_creation_input_tokens || 0
124  return (usage.input_tokens || 0) + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0)
125}
126
127export function totalTokens(t) {
128  if (!t) return 0
129  return (t.input || 0) + (t.output || 0) + (t.cacheRead || 0) + (t.cacheWrite || 0)
130}
131
132function clip(s, n) {
133  const one = String(s ?? '').replace(/\s+/g, ' ').trim()
134  return one.length > n ? one.slice(0, n - 1) + '…' : one
135}
136export { clip }
137
138// One line saying what a tool call does, for the activity column
139export function summarizeTool(tool, input) {
140  const i = input || {}
141  if (tool === 'Bash' || tool === 'PowerShell') return tool + ': ' + clip(i.command, 60)
142  if (i.file_path) return tool + ': ' + baseName(i.file_path)
143  if (i.notebook_path) return tool + ': ' + baseName(i.notebook_path)
144  if (tool === 'Grep' || tool === 'Glob') return tool + ': ' + clip(i.pattern, 40)
145  if (tool === 'WebFetch') return 'WebFetch: ' + clip(i.url, 50)
146  if (tool === 'WebSearch') return 'WebSearch: ' + clip(i.query, 50)
147  if (tool === 'Agent') return 'Agent: ' + clip(i.description || i.name, 40)
148  if (tool === 'SendMessage') return 'SendMessage → ' + clip(i.to, 30)
149  if (tool === 'AskUserQuestion') return 'Asking a question'
150  return tool
151}
152
153// The detail of a held tool call, as shown in the approval box
154export function describeCall(tool, input) {
155  const i = input || {}
156  if (i.command) return String(i.command)
157  if (i.file_path && i.old_string !== undefined) return i.file_path + '\n- ' + clip(i.old_string, 300) + '\n+ ' + clip(i.new_string, 300)
158  if (i.file_path && i.content !== undefined) return i.file_path + '\n' + clip(i.content, 400)
159  try {
160    return clip(JSON.stringify(i), 600)
161  } catch {
162    return tool
163  }
164}
165
166export function baseName(p) {
167  const parts = String(p).split(/[\\/]/)
168  return parts[parts.length - 1] || String(p)
169}
170
171export function normPath(p, isWindows) {
172  const s = String(p || '').replace(/\\/g, '/')
173  return isWindows ? s.toLowerCase() : s
174}
175
176// The decision a teammate's approval mode gives, from the engine's own
177export function decide(mode, tool, engine) {
178  if (engine === 'deny') return 'deny'
179  const isEdit = EDIT_TOOLS.includes(tool)
180  switch (mode) {
181    case 'bypassPermissions':
182      return 'allow'
183    case 'acceptEdits':
184      return isEdit ? 'allow' : engine
185    case 'plan':
186      if (isEdit) return 'deny'
187      return engine === 'ask' ? 'deny' : engine
188    case 'dontAsk':
189      return engine === 'ask' ? 'deny' : engine
190    default:
191      return engine
192  }
193}
194
195// Status → glyph, word and color. Single-width glyphs only.
196export function statusView(a) {
197  if (a.pending && a.pending.kind === 'approval') return { glyph: '!', word: 'needs approval', color: '#ff5555', bold: true }
198  if (a.pending && a.pending.kind === 'question') return { glyph: '?', word: 'has a question', color: '#ff79c6', bold: true }
199  switch (a.status) {
200    case 'launching':
201    case 'pending':
202    case 'starting':
203      return { glyph: '○', word: 'starting', color: 'gray' }
204    case 'running':
205    case 'working':
206      return { glyph: '↯', word: 'working', color: '#50fa7b' }
207    case 'waiting':
208      return { glyph: '…', word: 'waiting', color: '#e5c07b' }
209    case 'idle':
210      return { glyph: '○', word: 'idle', color: '#61afef' }
211    case 'completed':
212      return { glyph: '✓', word: 'done', color: '#98c379' }
213    case 'failed':
214      return { glyph: '✕', word: 'failed', color: '#ff5555' }
215    case 'killed':
216      return { glyph: '✕', word: 'stopped', color: 'gray' }
217    case 'exited':
218      return { glyph: '✕', word: 'exited', color: 'gray' }
219    case 'unresponsive':
220      return { glyph: '▲', word: 'no heartbeat', color: '#e5c07b' }
221    default:
222      return { glyph: '·', word: String(a.status || 'unknown'), color: 'gray' }
223  }
224}
225
226export function isLive(a) {
227  return !['completed', 'failed', 'killed', 'exited'].includes(a.status)
228}
229
230// ---------- launching a separate Claude Code session ----------
231
232export function psQuote(s) {
233  return "'" + String(s).replace(/'/g, "''") + "'"
234}
235
236export function shQuote(s) {
237  return "'" + String(s).replace(/'/g, "'\\''") + "'"
238}
239
240// The claude CLI arguments for a worker session
241export function claudeArgs(spec) {
242  const args = ['--name', spec.name, '--plugin-dir', spec.pluginRoot]
243  if (spec.agentType && spec.agentType !== 'default' && !BUILTIN_AGENTS.includes(spec.agentType)) args.push('--agent', spec.agentType)
244  if (spec.model && spec.model !== 'inherit') args.push('--model', spec.model)
245  if (spec.effort && spec.effort !== 'default') args.push('--effort', spec.effort)
246  if (spec.approval === 'bypassPermissions') args.push('--dangerously-skip-permissions')
247  else if (spec.approval && spec.approval !== 'default') args.push('--permission-mode', spec.approval)
248  // Let the lead's messages through whatever the worker's permission mode. A file, not
249  // inline JSON: Windows PowerShell 5.1 mangles quotes inside native arguments.
250  if (spec.settingsPath) args.push('--settings', spec.settingsPath)
251  // The first task is not an argument either: it travels in SWARM_MOD_TASK and the
252  // worker submits it, so no quoting of free text reaches a command line.
253  return args
254}
255
256export function windowTitle(name) {
257  return 'swarm: ' + name
258}
259
260// The script a new terminal runs: identity in env, cd to the lead's workspace, start claude
261export function launchScript(os, spec) {
262  const args = claudeArgs(spec)
263  if (os === 'windows') {
264    return [
265      '# swarm-mod worker launcher (generated)',
266      '$env:SWARM_MOD_WORKER = ' + psQuote(spec.id),
267      '$env:SWARM_MOD_LEAD = ' + psQuote(spec.lead),
268      '$env:SWARM_MOD_NAME = ' + psQuote(spec.name),
269      '$env:SWARM_MOD_APPROVAL = ' + psQuote(spec.approval || 'default'),
270      '$env:SWARM_MOD_TASK = ' + psQuote((spec.task || '').trim()),
271      'Set-Location -LiteralPath ' + psQuote(spec.cwd),
272      'try { $Host.UI.RawUI.WindowTitle = ' + psQuote(windowTitle(spec.name)) + ' } catch {}',
273      '& claude ' + args.map(psQuote).join(' '),
274      '',
275    ].join('\r\n')
276  }
277  return [
278    '#!/bin/sh',
279    '# swarm-mod worker launcher (generated)',
280    'export SWARM_MOD_WORKER=' + shQuote(spec.id),
281    'export SWARM_MOD_LEAD=' + shQuote(spec.lead),
282    'export SWARM_MOD_NAME=' + shQuote(spec.name),
283    'export SWARM_MOD_APPROVAL=' + shQuote(spec.approval || 'default'),
284    'export SWARM_MOD_TASK=' + shQuote((spec.task || '').trim()),
285    'cd ' + shQuote(spec.cwd) + ' || exit 1',
286    // which terminal tab this is, so the lead can bring it forward later
287    ...(spec.ttyPath ? ['tty > ' + shQuote(spec.ttyPath) + ' 2>/dev/null || :'] : []),
288    "printf '\\033]0;%s\\007' " + shQuote(windowTitle(spec.name)),
289    // through the login shell, so PATH (claude, node) is what the user's own shell has,
290    // whichever app started this script; fish and other non-POSIX shells fall back to zsh/bash
291    'case "${SHELL##*/}" in bash|zsh|ksh|sh|dash) LSH="$SHELL" ;; *) LSH=/bin/zsh; [ -x "$LSH" ] || LSH=/bin/bash ;; esac',
292    `exec "$LSH" -lic 'exec claude "$@"' claude ` + args.map(shQuote).join(' '),
293    '',
294  ].join('\n')
295}
296
297// AppleScript string literal
298function asQuote(s) {
299  return '"' + String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"'
300}
301
302// Ways to open a terminal running the script, best first: [{ argv, app }]
303export function launchCandidates(os, scriptPath, spec, prefs = {}) {
304  if (os === 'windows') {
305    const ps = ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-NoExit', '-File', scriptPath]
306    return [
307      // one Windows Terminal window named "swarm", one tab per agent
308      { app: 'wt', argv: ['wt.exe', '-w', 'swarm', 'new-tab', '--title', windowTitle(spec.name), '-d', spec.cwd, ...ps] },
309      // plain console window; start's first quoted argument is the title
310      { app: 'console', argv: ['cmd', '/d', '/c', 'start', windowTitle(spec.name) + ' ', '/D', spec.cwd, ...ps] },
311    ]
312  }
313  if (os === 'mac') {
314    const list = []
315    if (prefs.iterm) {
316      // the lead runs in iTerm2: a new iTerm2 window (asks once for Automation permission)
317      list.push({
318        app: 'iTerm',
319        argv: ['osascript', '-e', 'tell application "iTerm"', '-e', 'activate', '-e',
320          'create window with default profile command ' + asQuote('/bin/sh ' + shQuote(scriptPath)), '-e', 'end tell'],
321      })
322    }
323    // Terminal.app runs a .command file in a new window; needs no Automation permission
324    list.push({ app: 'Terminal', argv: ['open', '-a', 'Terminal', scriptPath] })
325    return list
326  }
327  return [
328    { app: 'x-terminal-emulator', argv: ['x-terminal-emulator', '-e', '/bin/sh', scriptPath] },
329    { app: 'gnome-terminal', argv: ['gnome-terminal', '--', '/bin/sh', scriptPath] },
330    { app: 'konsole', argv: ['konsole', '-e', '/bin/sh', scriptPath] },
331    { app: 'xterm', argv: ['xterm', '-e', '/bin/sh', scriptPath] },
332  ]
333}
334
335// Bring a worker's window to the front (best effort). Claude Code retitles its
336// terminal, so on macOS the tab is found by the tty the launch script recorded.
337export function focusArgv(os, name, where = {}) {
338  const title = windowTitle(name)
339  if (os === 'windows') {
340    return ['powershell', '-NoProfile', '-NonInteractive', '-Command',
341      '$s = New-Object -ComObject WScript.Shell; if (-not $s.AppActivate(' + psQuote(title) + ')) { [void]$s.AppActivate(' + psQuote(name) + ') }']
342  }
343  if (os === 'mac') {
344    const tty = where.tty ? asQuote(where.tty) : null
345    if (where.app === 'iTerm') {
346      return ['osascript',
347        '-e', 'tell application "iTerm"',
348        '-e', 'activate',
349        ...(tty ? [
350          '-e', 'repeat with w in windows',
351          '-e', 'repeat with t in tabs of w',
352          '-e', 'repeat with s in sessions of t',
353          '-e', 'if tty of s is ' + tty + ' then',
354          '-e', 'select w',
355          '-e', 'select t',
356          '-e', 'select s',
357          '-e', 'return "ok"',
358          '-e', 'end if',
359          '-e', 'end repeat',
360          '-e', 'end repeat',
361          '-e', 'end repeat',
362        ] : []),
363        '-e', 'end tell']
364    }
365    return ['osascript',
366      '-e', 'tell application "Terminal"',
367      '-e', 'activate',
368      ...(tty ? [
369        '-e', 'repeat with w in windows',
370        '-e', 'repeat with t in tabs of w',
371        '-e', 'if tty of t is ' + tty + ' then',
372        '-e', 'set selected tab of w to t',
373        '-e', 'set index of w to 1',
374        '-e', 'return "ok"',
375        '-e', 'end if',
376        '-e', 'end repeat',
377        '-e', 'end repeat',
378      ] : []),
379      '-e', 'try',
380      '-e', 'set index of (first window whose name contains ' + asQuote(name) + ') to 1',
381      '-e', 'end try',
382      '-e', 'end tell']
383  }
384  return ['wmctrl', '-a', title]
385}
386
387// Parses `name:` and `description:` from an agent file's frontmatter
388export function parseAgentFile(text) {
389  const m = /^?---\r?\n([\s\S]*?)\r?\n---/.exec(String(text))
390  if (!m) return null
391  const field = (k) => {
392    const r = new RegExp('^' + k + ':\\s*(.*)$', 'm').exec(m[1])
393    return r ? r[1].trim().replace(/^["']|["']$/g, '') : ''
394  }
395  const name = field('name')
396  return name ? { name, description: field('description') } : null
397}
398
399// Files two or more agents have edited: [{ path, keys }]
400// caseInsensitive: Windows, and macOS (APFS is case-insensitive by default)
401export function findConflicts(agents, caseInsensitive) {
402  const byPath = new Map()
403  for (const a of agents) {
404    for (const f of a.files || []) {
405      const k = normPath(f, caseInsensitive)
406      if (!byPath.has(k)) byPath.set(k, { path: f, keys: [] })
407      const entry = byPath.get(k)
408      if (!entry.keys.includes(a.key)) entry.keys.push(a.key)
409    }
410  }
411  return [...byPath.values()].filter((e) => e.keys.length > 1)
412}
413
414export function randomId(rand = Math.random) {
415  let s = ''
416  for (let i = 0; i < 10; i++) s += Math.floor(rand() * 36).toString(36)
417  return s
418}
419
420// The settings file a worker starts with
421export const WORKER_SETTINGS = JSON.stringify({ crossSessionInbound: 'accept' }, null, 2) + '\n'
422
423// ---------- process ids (kill a separate session) ----------
424
425// Run from inside a session: prints "<claude pid> <process name>" (the caller's parent)
426export function selfPidArgv(os) {
427  if (os === 'windows') {
428    return ['powershell', '-NoProfile', '-NonInteractive', '-Command',
429      "$p = (Get-CimInstance Win32_Process -Filter ('ProcessId=' + $PID)).ParentProcessId; Write-Output ('' + $p + ' ' + (Get-Process -Id $p).ProcessName)"]
430  }
431  return ['/bin/sh', '-c', 'echo "$PPID $(ps -o comm= -p $PPID)"']
432}
433
434export function parsePidLine(text) {
435  const m = /^\s*(\d+)\s+(.+?)\s*$/m.exec(String(text || ''))
436  if (!m) return null
437  return { pid: Number(m[1]), name: baseName(m[2]) }
438}
439
440// Prints the name of a process now, to check a pid was not reused before killing it
441export function pidNameArgv(os, pid) {
442  if (os === 'windows') {
443    return ['powershell', '-NoProfile', '-NonInteractive', '-Command', '(Get-Process -Id ' + Number(pid) + ' -ErrorAction SilentlyContinue).ProcessName']
444  }
445  return ['ps', '-o', 'comm=', '-p', String(Number(pid))]
446}
447
448export function killArgv(os, pid) {
449  if (os === 'windows') return ['taskkill', '/PID', String(Number(pid)), '/T', '/F']
450  return ['kill', '-TERM', String(Number(pid))]
451}
452
453// ---------- auto-restart ----------
454
455export const RESTART_MAX = 3
456export const UNRESPONSIVE_RESTART_MS = 60000
457
458// Seconds to wait before restart n (0-based): 5, 15, 45
459export function restartDelayMs(n) {
460  return 5000 * Math.pow(3, Math.max(0, n))
461}
462
463// Session-end reasons that mean the person ended the worker on purpose
464export const DELIBERATE_EXITS = ['prompt_input_exit', 'logout']
465
466// Whether an agent ended in a way auto-restart should undo. Stopping it yourself
467// (Kill, /exit, or the agent panel's stop) never counts. `now` is the lead's clock:
468// a worker counts as hung once the lead has seen it silent for a full minute, so a
469// laptop waking from sleep does not restart everything.
470export function needsRestart(a, now) {
471  if (!a.autoRestart || a.killedByUser || (a.restarts || 0) >= RESTART_MAX) return false
472  if (a.transport === 'teammate') return a.status === 'failed'
473  if (a.status === 'exited') return !DELIBERATE_EXITS.includes(a.exitReason)
474  if (a.status === 'failed') return true
475  return a.status === 'unresponsive' && !!a.unresponsiveSince && now - a.unresponsiveSince > UNRESPONSIVE_RESTART_MS
476}
477
478export function restartTask(task) {
479  const note = '(You were restarted after your previous run ended unexpectedly. Check the current state of the workspace before continuing.)'
480  return String(task || '').trim() ? note + '\n\n' + String(task).trim() : note
481}
482
483// ---------- saved rosters ----------
484
485export const ROSTER_FIELDS = ['name', 'color', 'agentType', 'model', 'effort', 'approval', 'transport', 'task', 'autoRestart']
486
487export function rosterEntry(a) {
488  const e = {}
489  for (const f of ROSTER_FIELDS) if (a[f] !== undefined) e[f] = a[f]
490  return e
491}
492
493export function rosterKey(name) {
494  return 'roster:' + String(name).trim()
495}
496
497export function lastRosterKey(cwd, caseInsensitive) {
498  return 'last:' + normPath(cwd, caseInsensitive).replace(/\/+$/, '')
499}
500
501// A roster's entries made to fit beside the agents already here: free names and colors
502export function planRoster(entries, takenNames, usedColors, rand = Math.random) {
503  const names = [...takenNames]
504  const colors = [...usedColors]
505  return entries.map((e) => {
506    const name = suggestName(e.name, names)
507    names.push(name)
508    const color = e.color && !colors.includes(e.color) ? e.color : pickColor(colors, rand)
509    colors.push(color)
510    return { ...e, name, color }
511  })
512}
513
514export function validRosterName(name) {
515  return /^[A-Za-z0-9 _.-]{1,40}$/.test(String(name || '').trim())
516}
517
types/index.d.ts 8 lines
1declare module 'claude-code' {
2  interface PluginState {
3    'swarm-mod': {
4      snapshot: { agents: Record<string, unknown>; order: string[]; dismissed?: string[] }
5    }
6  }
7}
8