SLOPSHOPPER

helm

Active-work tracking for Claude Code fleets: forge state, a work ledger of who owns which issue, event delivery to agents, model routing per issue, and a live…

panebandguardcommandstatusprompt
v0.10.0MITupdated 2026-10-23octalide/helm
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · helm
│ ┃ helm ✕ › fix the failing auth test and add an audit log call │ ┃ helm is connecting to helmd │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · helm
helm is connecting to helmd
README

helm

Active-work tracking for Claude Code fleets. helm watches GitHub and your local checkouts, keeps a ledger of which session and agent owns which issue, delivers repository events to the agent that asked for them, routes each issue to a model and effort, and shows all of it live, in the terminal and on a local web page with a decision inbox.

It is built for one way of working: a coordinator session, a session per repository that owns that repository's issues, and an issue agent per issue spawned by the repository session. Every piece is useful on its own too.

Install

/plugin install helm --marketplace octalide/helm@main

or from a shell:

claude plugin marketplace add octalide/helm@main
claude plugin install helm@helm

helm is a function-hook plugin, which is early access. Turn on CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 in the env block of settings.json. It needs node 24 or newer and gh logged in (gh auth login). helmd uses the token gh holds and keeps none of its own.

How it fits together

GitHub ──(etag probes, graphql)──┐
local git (worktrees, branches) ─┤
                                 ▼
                       helmd (one per user)
                 forge cache · ledger · subscriptions
                   │ unix socket          │ 127.0.0.1:7468
       ┌───────────┼───────────┐          ▼
   session      session     session    web page
 (coordinator)  (repo A)    (repo B)   live fleet, decision inbox
                  │ dispatch
            issue agents ── report, watch, view, log

helmd is the only process that talks to GitHub. The first session to need it starts it, and a session that finds an older one replaces it. Either way the session runs the newest helmd installed beside its mod that speaks its protocol, so whichever session starts or replaces it lands on the newest. It polls each repository in use: those a live session works in, those with unfinished work or a subscription, and any a tool asked about lately. Two conditional probes per poll cost nothing when nothing moved, and the snapshot (open and recent issues and PRs, every check on each PR head, last comment and review) is read only when a probe moved. Active repositories poll every 20 s, the rest every 3 minutes. Jobs and their steps are read live while a run is in flight. Everything helmd holds survives a restart.

The mod binds each session to helmd. It registers the session and its agents, streams the session's deliveries, serves the tools, draws the pane, and tells repository and coordinator sessions how to work with helm through a section of their system prompt, so no instruction file has to.

Roles

Set the role with HELM_ROLE=coordinator|repo|other at launch, or with /helm role coordinator. A role asked for wins, and helmd keeps it for that session and for the session it goes on as after a /clear or a resume. Any other role is a default, worked out again each time a session registers: the repo session of the repository it runs in, else other. So a session started, continued or resumed in a checkout is that repository's repo session with no step of its own, and takes over what the gone repo sessions there left (see Succession). The mod takes its role and repository from helmd's answer.

helm registers a session once its conversation starts. A claude --resume <term> still showing its picker has not started one, so its repository has no repo session until a conversation is picked. A repository with unfinished work, or that had a repo session, and no live repo session now is listed as having none in view with what: fleet, in the coordinator's pane and on the web page's Overview, and each issue opened in it reaches the coordinator at once. Start or resume a session in its checkout, or run /helm role repo in one, to give it one.

helmd also reads the session file Claude keeps for each interactive process (~/.claude/sessions/<pid>.json, under CLAUDE_CONFIG_DIR when set). A live process in a checkout of a watched repository that has gone a minute without registering is listed on that repository's entry, by pid and directory, as a session waiting on input, so a picker reads as a session waiting on the person rather than as none.

  • Repo session. Owns a repository's issues. It queues them with backlog, starts agents with dispatch, and hears its own work move ([helm work] deliveries) without polling.
  • Coordinator. Sees the fleet (view with what: fleet or what: tree), hears only what needs it (its own work and work no session owns when it is blocked, failing or stalled, every decision for the person and its answer, adopted, returned and leftover work, each epic as it completes, and each new issue no session owns), and talks to repository sessions with SendMessage.
  • Issue agent. Started only by dispatch. It reports as it goes, its plan with each step's progress among it, waits on CI by subscribing and ending its turn, and stops with a question that goes to the session that owns its work, which answers it or escalates it to the person. The answer resumes it.

Tools

tooldoes
statusthis session's role, work, the decisions addressed to it and its own waiting on the person, subscriptions and letters in flight
viewwork, fleet, tree (epics and sub-issues with progress rolled up), issues, issue, prs, pr (with live jobs), runs, worktrees, branches, decisions, sessions, from the shared cache
loga CI job's log trimmed to its errors, a grep or a tail; or every failed job of a run
watchsubscribe to a repository, issue, PR, branch, run or tag. A subagent's subscription delivers to that subagent
reportwhere an agent's work stands: working (claims the issue), waiting, blocked with a question, ready, stopped, abandoned, plus its plan and choices made without the person, recorded for review
dispatchstart an issue agent per issue: claim, route to a tier, spawn, log the pick. An issue a live agent holds is refused, naming it
backlogthe session's queue of issues
decidelist, answer, escalate to the person or dismiss decisions

/helm shows the session's binding, and /helm pane, /helm web, /helm role … and /helm restart do what they say.

Pane

/helm pane opens a dashboard beside the transcript, with four tabs. Each tab key works while the pane has the focus.

keytabshows
1Workthe session's work, or for a coordinator every session's: a bar of it by phase, then each item with its plan progress and next step, its checks with the running step or the failed checks, and its agent, tier and PR
2Epicseach epic touching the session, with its percent, rollup bar and counts, and the work moving under it
3CIruns in flight with their job bar and running steps, then runs finished in the last half hour
4Inboxwhat is addressed to this session: its agents' questions and its stalls, and for a coordinator the person's decisions too; an option answers one in place, escalate hands it to the person and dismiss closes it. A written answer goes on the web page

Above the prompt, one line appears while something needs you, and the status line counts work in progress.

Delivery

Events reach whoever subscribed. A letter for the main loop rides the next tool result while a turn runs. Between turns, every letter waiting goes as one prompt that starts a turn, and what lands before that turn ends rides it or waits for its end. A letter for a subagent rides that agent's next tool call. After 60 s without one, or once the agent has ended its turn, it goes as a message that resumes the agent. If the engine refuses the message, the letter is relayed to the main loop and the agent's subscriptions are retired. Letters that go together read as one, a work item's older phases folded into its newest (working → draft → ci). helmd hands each letter out once. After a plugin reload, the module instance it replaced stands down at its next frame, so only the live one delivers.

An issue agent answers only to the session that dispatched it. The engine resolves a SendMessage recipient against every session on the machine, so an agent replying to "the coordinator" its parent's message names would reach a session called that. A SendMessage from an issue agent, or from an agent it started, that names no other agent of its own session goes to that session's main loop instead, as a [helm message] letter naming the agent, its issue and the recipient it wrote.

CI arrives as one verdict per PR head (ci settled success or failure, naming each failed check with the run to read), one stall notice when checks have not finished within an hour, and run completions on branches and tags.

Phases

Work moves through queued → working → draft → ci → ready → done, with failing, blocked, stalled and parked beside them. Work is held by one agent at a time: the one dispatched on it, or the agent that claimed it by reporting working once nobody held it. While that agent is live and has not reported stopped, nothing takes the work from it: a dispatch, or a working report from another agent, is refused and names the holder. A subagent the holder started claims and reports as the holder. Phases are derived, not set: from the agent's reports, whether its agent is alive, the PR that closes the issue or sits on its branch, that PR's checks, and the issue's labels and dependencies. A stalled item (no live agent, work not done) and a stalled or failing CI raise a decision on their own, and clear it once the condition passes. A stall goes to the session that owns the work, and to the person once that session is gone with no successor (see Succession), and a failing long-lived branch goes to the person. A dismissed one stays dismissed until its condition changes (a new PR head, a different agent, a different phase) or ends. Work set aside on purpose, labelled blocked or parked or blocked by an open issue, is parked while nobody is on it: it raises nothing and needs no attention. Work whose agent reported stopped is parked too, and what its subscriptions deliver goes to the session that owns the work instead of resuming the agent, until the issue is dispatched again (the new agent takes over the subscriptions), the agent reports working, or its session messages it back to work. Releasing it from the backlog keeps the stop. A PR out of draft with green CI is ready whether or not anyone is still on it, since all it waits on is its merge. An issue whose open PR another work item is on, as when one PR closes several issues, moves with that PR and is never a stall of its own while someone is on it. An epic is never a stall either: its phase rolls up from its sub-issues, ready once all are done, working while any is moving or needs attention, queued or parked when that is all that is left, unless the epic itself is done, blocked on a question or set aside. A report polls its repository at once, so the phase keeps up with what the agent just did.

Succession

A repo session that registers in a repository whose other repo sessions are all gone, or is the one live repo session left when another goes, takes over their unfinished work: the backlog in its order, the claims, the subscriptions, and the open decisions addressed to them or handed to the person only because their session was gone. A decision a session escalated itself stays the person's. Each item records adopted: { from, at }, and the new session hears it as one [helm adopted] delivery listing what it took and which items to dispatch again. An agent that came with adopted work is gone with its old session: what its subscriptions deliver goes to the new session's main loop, and the agent a new dispatch starts takes the subscriptions over. Nothing is taken from a live session, and a coordinator or an other session never adopts repository work. A session resumed under its own id keeps everything, as before, and takes back the open decisions about its own work that helm handed to the person while it was gone, heard as one [helm decisions back] delivery. A session marked gone whose heartbeat comes back returns the same way, and succeeds the gone repo sessions of its repository as one registering would. After a /clear or an in-process resume the process goes on under a new id, and the mod names the old one when it registers, so helmd hands it over whole and at once.

The adopting session records what it took. Once it is no longer the repo session of that repository (it takes another role or another repository), it gives back what it has not acted on: work whose owner is unchanged, whose agent is the one it came with and that nobody has reported on since, with the subscriptions and open decisions that came with it and the open decisions addressed to it about that work. They go back to the session they came from and on from there by the same succession, to a live repo session of the repository or, for a decision, to the person. The session hears it as one [helm gave back] delivery.

Hierarchy

GitHub's sub-issues draw the tree. Every open issue with sub-issues that no other issue in a watched repository holds is a root epic, and each node joins its work item: phase, agent, tier and plan progress. Sub-issues in other repositories nest under their parent, and a sub-epic in a repository helm does not poll is counted from its summary. Each epic rolls up its leaves: done, active, in CI, ready, needing attention, queued, parked and unowned. Sub-issues are read again only when their parent moved, or every 10 minutes.

Each work item keeps when it entered each phase, and finished work stays 30 days, so the page can draw a timeline. helm builds one [helm epic] event whenever anything under an epic moves, carrying its rollup and every phase change under it in that batch. A coordinator's fleet subscription takes by default only what needs it: its own work and work no session owns entering blocked, failing or stalled, decisions and their answers, adopted, returned and leftover work, and an epic's event once the epic completes. The phases of work another session owns are that session's to hear, and what such work needs from the person reaches the coordinator as a decision. Routine phases and epic progress stay on the web page and in view. A fleet subscription that names its own tags as phase and progress hears the routine phases of work in no epic and every epic's progress event, which carries the routine phases under that epic. Only work in an epic has its routine phases left out, since its epic event already holds them.

An issue is unowned when it opened in a repository helm polls and no session queued or claimed it within 30 minutes of its opening. When that repository had no live repo session as the issue opened, it is unowned at once. The coordinator hears each one once, as an issue event tagged unowned, and the ledger records the delivery, so a restart or a later poll never repeats it. Only issues helm saw open while it watched the repository count: the first poll of a repository, or of helmd after a restart, takes what is already open as it finds it. An issue queued, claimed or closed within its window is never delivered. unowned is in the fleet's default tags, so a fleet subscription with its own tags names it or leaves it out.

When an issue agent's loop ends, helmd looks for live processes whose working directory is inside that work's worktree (Linux /proc, and a host without it reports nothing). What it finds goes on the work item as leftovers and to the owner as a [helm work] delivery tagged leftovers, shown in the pane and the drawer. Each local scan drops a listed process that has exited or left the worktree. helm never kills them: whoever owns the work decides.

Routing

dispatch sends each issue to a tier: a model and an effort with a description of the work that belongs there. The judge (claude-haiku-5-5 by default) reads the issue against the tiers and answers a tier, a confidence and a reason. Each pick is recorded for review, a record that waits on nobody, and answering it with another tier reroutes the issue. Name a tier in dispatch to skip the judge. A session registers an agent type for every tier and for the model and effort of every work item it owns, so an agent dispatched on a tier since removed can still be resumed. A session picks up a changed tier table on /reload-plugins.

The default tiers:

tiermodeleffortfor
mechanicalclaude-haiku-5-5highversion and pin bumps, renames, moves, docs, pattern-following data rows, finishing a done PR, one-file fixes with a stated cause
lightclaude-sonnet-5-5mediumsmall contained work in one module with a stated design
standardclaude-opus-5-5mediumordinary work in one subsystem with clear acceptance
deepclaude-opus-5-5highcross-subsystem or contract changes, codegen, concurrency, soundness, design-heavy work, unknown root causes
frontierclaude-fable-5-1highreserved for decision-heavy work: architecture, contract or language design, research-grade problems, what earlier tiers failed on. Never an implementation workhorse. Caller-only

A tier with "judge": false is caller-only: the judge is never shown it, and only a dispatch that names it runs on it. frontier is caller-only by default, so a dispatch with no tier never lands on it. A judge answer that names no tier, or names a caller-only one, falls back to routing.fallback, standard by default. The fallback can't be caller-only.

Web page

http://127.0.0.1:7468/, or /helm web. It is a dashboard with a view per question, and each view updates live:

viewshows
Overviewactive work as the headline, tiles for what waits on you, what needs attention, what is in CI, ready and done this week; the attention queue, runs in flight, every epic's progress, the pipeline by phase, throughput per day and each session
Boardwork as cards in phase columns (queued, working, draft, in ci, ready, attention, parked, done), each with its agent, tier, plan progress and checks; lanes by session, epic, repository or tier
Epicsthe sub-issue tree across repositories, each epic with its rollup bar, each leaf with its phase, plan and agent; drill into any epic
Timelinea lane per work item of the phases it went through over 6 hours to 30 days, and the median time work spends in each phase
CIruns in flight with every job and step, pass rate and run length, each workflow's recent outcomes, and failed runs with their logs
Agentseach live session's agents, their model and effort, and the work and tier each is on; below, every dispatch of the last 7 days with its tier and model, live or ended
Routingpicks per tier by outcome, the judge's confidence, and every pick with its reason
Inboxwhat is yours to decide, each card marked for you: questions sessions hand on or ask themselves, stalls and failures nobody else owns, answered or dismissed in place. Below, muted and never counted, what sessions are handling, each naming its session, so you can read it or step in
Reviewrecords of what was decided without you, newest first: choices agents and sessions made, which take feedback or are marked reviewed, and routing picks, which can still be rerouted
Reposeach repository's PRs, issues, runs, worktrees and branches, and the GitHub budget left
Activityevery event by day, by kind
Settingsthe config, every field marked as set in your file or helm's default, editable and saved to ~/.config/helm/config.json; and the routing picks per tier over the last day and week

Clicking a work item opens its detail: its phases with how long each took, its plan, CI, routing, decisions and worktree. Filters for repository, session, epic and tier, plus a search, apply to every view and live in the URL, so a filtered view can be bookmarked. ctrl k opens a palette that jumps to any view, issue, epic, repository or session. The digits open the views, r opens Review and s Settings, / searches, j and k walk the cards, t toggles the theme, and ? lists the keys.

The page is served on 127.0.0.1 only. A request must name this server as its Host, and a write must come from this page.

Config

~/.config/helm/config.json, every field optional:

{
  "roots": ["~/dev/src"],
  "repos": ["owner/name"],
  "web": { "port": 7468 },
  "poll": { "active": 20, "idle": 180, "local": 15, "stallHours": 1, "goneSeconds": 120 },
  "routing": { "judge": "claude-haiku-5-5", "review": 0.7, "fallback": "standard", "tiers": [ ... ] }
}

roots are searched for checkouts by their origin remote. repos are polled whether or not anything references them. routing.tiers replaces the table whole, and routing.fallback must name one of its tiers. A repository can set its own routing in .helm/config.json.

A tier is { "name", "model", "effort", "when" }, plus "judge": false to make it caller-only (see Routing). Tier names are unique.

helmd watches the file and applies an edit live, with no restart. An edit that fails to parse or check is logged to the daemon log and the running config kept.

The Settings view on the web page edits this file. It shows the config helmd is running, with each field marked user when your file sets it and default when it doesn't. You can edit every field, add, remove and reorder tiers, change each tier's model, effort, when and whether the judge may pick it, and reset a field to drop it from your file. Saving checks the whole file by the rules helmd applies at start. A bad edit is refused with the reason and the file is left as it was. A good one is written whole and applied before the page shows it, and no field needs a restart. A save is also refused when the file changed on disk after the page read it. The page edits only the machine's file, not a repository's .helm/config.json.

State lives under $XDG_STATE_HOME/helm and the socket under $XDG_RUNTIME_DIR/helm. HELM_HOME puts everything under one directory, which is how a second daemon runs beside the real one.

helmd

helmd start | stop | restart | status | serve | stream <session> | version

bin/helmd runs it from a checkout. Sessions start it on their own. restart hands over without a gap: the new daemon takes the lock and the socket while the old one still answers, then stops it and serves once it has saved.

Development

npm ci
npm run typecheck
npm test
claude plugin validate .
claude --plugin-dir .

The engine follows $ into the hooks module alone, so everything that reaches the engine is in hooks/helm.tsx. Logic lives in plain modules under src/mod (the session side), src/daemon (helmd) and src/core (the contract both sides share).

Source 23 files
hooks/helm.tsx 523 lines
1import { atom, read, update } from 'claude-code';
2import type { EngineInterface, Register } from 'claude-code';
3import { helmPaths, type PathEnv } from '../src/core/paths.ts';
4import { daemonAction, PROTOCOL, type StreamFrame } from '../src/core/protocol.ts';
5import { isRepoName, repoOfRemote } from '../src/core/repo.ts';
6import type { AgentRecord, AgentStatus, Effort, Fleet, RepoName, SessionRole } from '../src/core/types.ts';
7import { HelmClient, HelmError } from '../src/mod/client.ts';
8import { type Install, newestInstall } from '../src/mod/install.ts';
9import { type DispatchPort, dispatchTool, issueAgentName } from '../src/mod/dispatch.ts';
10import { Mailbox } from '../src/mod/mailbox.ts';
11import { sendRoute } from '../src/mod/send.ts';
12import { type Tool, TOOLS } from '../src/mod/tools.ts';
13import { bandRow, isTab, paneRows, type Row, type Self, statusText, type Tab } from '../src/mod/view.ts';
14import { PLUGIN, ROLES, type Runtime, toolEnv } from './runtime.ts';
15
16type $ = EngineInterface;
17
18// what a tool that reaches the engine is handed: plain functions over $, built here per call
19type Port = DispatchPort;
20
21const HEARTBEAT_MS = 15_000;
22const RECONNECT_MS = 3_000;
23// the pane redraws from helmd at most this often, however fast changes come
24const REFRESH_MS = 1_500;
25const PANE = 'helm';
26const isIssueType = (type: string) => type.startsWith(`${PLUGIN}:issue-`);
27
28// the fleet itself stays in the module, since the state contract holds only self-contained data; the atom is the
29// stamp that tells a drawing to read it again
30// the role prompts, read at session start: the coordinator's, and the repository session's with {{repo}} in it
31let rolePrompts: { coordinator: string; repo: string } | undefined;
32
33function rolePrompt(r: Runtime): string | undefined {
34  if (!rolePrompts) return undefined;
35  if (r.role === 'coordinator') return rolePrompts.coordinator;
36  if (r.role === 'repo') return rolePrompts.repo.replaceAll('{{repo}}', r.repo ?? 'its repository');
37  return undefined;
38}
39
40const fleetAt = atom({ plugin: 'helm', key: 'fleetAt' } as const, 0);
41const paneTab = atom({ plugin: 'helm', key: 'paneTab' } as const, 'work' as Tab);
42// the module instance that holds the session's binding. a reload swaps the hooks but can leave the replaced
43// instance's stream running, its mailbox deaf to turns, so each instance stamps itself here at session.start and
44// one that finds another stamp stands down
45const binder = atom({ plugin: 'helm', key: 'binder' } as const, '');
46let fleet: Fleet | undefined;
47
48let rt: Runtime | undefined;
49
50async function pathEnv($: $): Promise<PathEnv> {
51  const env: PathEnv = { HOME: (await $.env.get('HOME')) ?? '/' };
52  const set = (k: keyof PathEnv, v: string | undefined) => {
53    if (v) env[k] = v;
54  };
55  set('XDG_RUNTIME_DIR', await $.env.get('XDG_RUNTIME_DIR'));
56  set('XDG_STATE_HOME', await $.env.get('XDG_STATE_HOME'));
57  set('XDG_CONFIG_HOME', await $.env.get('XDG_CONFIG_HOME'));
58  set('XDG_CACHE_HOME', await $.env.get('XDG_CACHE_HOME'));
59  set('HELM_SOCKET', await $.env.get('HELM_SOCKET'));
60  set('HELM_HOME', await $.env.get('HELM_HOME'));
61  return env;
62}
63
64async function clientFor($: $): Promise<HelmClient> {
65  const paths = helmPaths(await pathEnv($));
66  return new HelmClient(async (url, init) => {
67    const res = await $.http.fetch(url, init);
68    return { status: res.status, ok: res.ok, text: res.text };
69  }, paths.socket);
70}
71
72function daemonArgv(root: string, cmd: string, ...rest: string[]): string[] {
73  return ['node', '--disable-warning=ExperimentalWarning', `${root}/src/daemon/main.ts`, cmd, ...rest];
74}
75
76// the install whose helmd this mod starts or replaces helmd with, read again each time, since a newer one can be
77// installed while the session runs
78function daemonInstall($: $, own: Install): Promise<Install> {
79  return newestInstall(own, {
80    dirs: async (path) => (await $.fs.list(path)).filter((e) => e.kind === 'dir').map((e) => e.name),
81    read: (path) => $.fs.read(path),
82  });
83}
84
85let reloadSaid = false;
86
87// helmd answering at the newest installed version or newer; an older one is replaced, a newer one is used as it is
88async function ensureDaemon($: $, client: HelmClient, own: Install): Promise<void> {
89  const up = await client.health().catch(() => undefined);
90  const install = await daemonInstall($, own);
91  const cmd = daemonAction(up, install.version);
92  if (cmd === 'use') return;
93  if (cmd === 'reload') {
94    if (!reloadSaid) $.ui.log(`helm: helmd ${up?.version} speaks protocol ${up?.protocol}, newer than this session's mod (${PROTOCOL}): run /reload-plugins`);
95    reloadSaid = true;
96    return;
97  }
98  const r = await $.process.run(daemonArgv(install.root, cmd), { timeoutMs: 30_000 });
99  if (r.exitCode !== 0) throw new Error(`helmd ${cmd} failed: ${(r.stderr || r.stdout).trim()}`);
100}
101
102async function sessionRepo($: $): Promise<RepoName | undefined> {
103  const r = await $.session.repo();
104  return r?.remote ? repoOfRemote(r.remote) : undefined;
105}
106
107async function agentRecords($: $): Promise<AgentRecord[]> {
108  return (await $.agent.list()).map((a) => ({
109    id: a.id,
110    type: a.type,
111    description: a.description,
112    status: a.status as AgentStatus,
113    ...(a.name ? { name: a.name } : {}),
114    ...(a.parentId ? { parentId: a.parentId } : {}),
115  }));
116}
117
118// from: the session this process went on from, which helmd hands over to this one whole. the role goes only when one
119// was asked for, and the role and repository are what helmd answers, which keeps a known session's own
120async function bind($: $, r: Runtime, from?: string): Promise<void> {
121  r.session = await $.session.id();
122  const s = await r.client.register({
123    id: r.session,
124    cwd: await $.session.cwd(),
125    protocol: PROTOCOL,
126    ...(r.asked ? { role: r.asked } : {}),
127    ...(r.checkout ? { repo: r.checkout } : {}),
128    ...(from && from !== r.session ? { from } : {}),
129  });
130  r.role = s.role;
131  if (s.repo) r.repo = s.repo;
132  else delete r.repo;
133}
134
135// issue agent types registered by this load of the module, by name
136const issueTypes = new Set<string>();
137let issuePrompt: string | undefined;
138
139async function issueAgentType($: $, model: string, effort: Effort): Promise<string> {
140  const name = issueAgentName(model, effort);
141  if (!issueTypes.has(name)) {
142    issuePrompt ??= await $.fs.read(`${$.plugin.root}/prompts/issue.md`);
143    await $.agent.register({
144      name,
145      description: `Implements one GitHub issue to a merge-ready PR on ${model} at ${effort} effort. Started by helm dispatch only.`,
146      prompt: issuePrompt,
147      model,
148      effort,
149      disallowedTools: ['AskUserQuestion'],
150    });
151    issueTypes.add(name);
152  }
153  return `${PLUGIN}:${name}`;
154}
155
156// every tier this session can route to, plus the model and effort of every work item it owns, registered up front so a
157// dispatch in its first turn finds them and an agent on a tier since removed can still be resumed
158async function registerTiers($: $, client: HelmClient, repo: RepoName | undefined, session: string): Promise<void> {
159  const { routing } = await client.config(repo);
160  for (const t of routing.tiers) await issueAgentType($, t.model, t.effort);
161  const { work } = await client.fleet(true);
162  for (const w of work) if (w.owner === session && w.routing) await issueAgentType($, w.routing.model, w.routing.effort);
163}
164
165function port($: $): Port {
166  return {
167    now: Date.now,
168    agentType: (model, effort) => issueAgentType($, model, effort),
169    spawn: async (a) => {
170      const r = await $.agent.spawn(a);
171      return r.deny !== undefined ? { deny: r.deny } : r.agentId ? { agentId: r.agentId } : {};
172    },
173    complete: async (a) => {
174      const r = await $.model.complete({ ...a, maxTokens: 400, effort: 'low', timeoutMs: 45_000 });
175      return r.isAnswered ? { text: r.text } : { failed: r.reason };
176    },
177  };
178}
179
180// false once a later instance of this module holds the binding, which this one learns of here and stands down for:
181// its timers and mailbox stop, and the stream it reads ends. a stamp that cannot be read is another's
182async function holds($: $, r: Runtime): Promise<boolean> {
183  if (!r.alive) return false;
184  const stamp = await read($, binder).catch(() => undefined);
185  if (stamp === '' || stamp === r.instance) return true;
186  r.alive = false;
187  r.timers.forEach((t) => t.cancel());
188  r.mailbox.stop();
189  $.ui.log(`helm: instance ${r.instance} stood down for ${stamp ?? 'an unreadable binding'}`, { to: 'debug' });
190  return false;
191}
192
193// letters and change notices from helmd, for the life of this module; reconnects whenever helmd goes away
194function pump($: $, r: Runtime): void {
195  const run = async () => {
196    try {
197      let buf = '';
198      const session = r.session;
199      // a stream reads one session's letters: once the process goes on under another id, it is opened again for that one
200      for await (const piece of $.process.spawn({ argv: daemonArgv(r.install.root, 'stream', session) })) {
201        if (!(await holds($, r)) || r.session !== session) break;
202        if (piece.stream !== 'stdout') continue;
203        buf += piece.text;
204        for (let i = buf.indexOf('\n'); i >= 0; i = buf.indexOf('\n')) {
205          const line = buf.slice(0, i);
206          buf = buf.slice(i + 1);
207          if (line) await frame($, r, JSON.parse(line) as StreamFrame);
208        }
209      }
210    } catch (e) {
211      $.ui.log(`helm: stream ended: ${(e as Error).message}`, { to: 'debug' });
212    }
213    if (!(await holds($, r))) return;
214    r.timers.push(
215      $.clock.after(RECONNECT_MS, () => {
216        void ensureDaemon($, r.client, r.install)
217          .then(() => bind($, r))
218          .catch((e: Error) => $.ui.log(`helm: helmd unavailable: ${e.message}`, { to: 'debug' }))
219          .finally(() => r.alive && pump($, r));
220      }),
221    );
222  };
223  void run();
224}
225
226async function frame($: $, r: Runtime, f: StreamFrame): Promise<void> {
227  if (f.type === 'letter') await r.mailbox.receive(f.letter);
228  if (f.type === 'changed' || f.type === 'hello') refresh($, r);
229}
230
231const selfOf = (r: Runtime): Self => ({ session: r.session, role: r.role, ...(r.repo ? { repo: r.repo } : {}) });
232
233let refreshTimer: { cancel: () => void } | undefined;
234let lastRefresh = 0;
235
236// the fleet for the pane, band and status line, read once per window however many changes land in it
237function refresh($: $, r: Runtime): void {
238  if (refreshTimer || !r.alive) return;
239  const wait = Math.max(0, lastRefresh + REFRESH_MS - Date.now());
240  refreshTimer = $.clock.after(wait, () => {
241    refreshTimer = undefined;
242    lastRefresh = Date.now();
243    void (async () => {
244      const f = await r.client.fleet(true);
245      fleet = f;
246      await update($, fleetAt, () => f.at);
247      $.ui.status(statusText(f, selfOf(r)));
248    })().catch((e: Error) => $.ui.log(`helm: refresh failed: ${e.message}`, { to: 'debug' }));
249  });
250}
251
252// a row of plain segments is one line of text; a row holding a control lays its segments out side by side, each
253// control a Button whose press the ui.press hook routes by its key
254function rowsOf($: $, e: Parameters<$['ui']['resolve']>[0], rows: Row[]) {
255  const { Box, Text, Button } = $.ui.resolve(e);
256  const text = (s: Row[number]) => <Text {...(s.color ? { color: s.color } : {})} dimColor={s.dim ?? false} bold={s.bold ?? false}>{s.text}</Text>;
257  return (
258    <Box flexDirection="column">
259      {rows.map((row) =>
260        row.some((s) => s.press) ? (
261          <Box flexDirection="row">
262            {row.map((s) =>
263              s.press ? (
264                <Button key={s.press} {...(s.boxed ? {} : { plain: true as const })} {...(s.hotkey ? { hotkey: s.hotkey } : {})} dimColor={s.dim ?? false} onPress={() => {}}>
265                  {text(s)}
266                </Button>
267              ) : (
268                text(s)
269              ),
270            )}
271          </Box>
272        ) : (
273          <Text wrap="truncate-end">{row.length ? row.map(text) : ' '}</Text>
274        ),
275      )}
276    </Box>
277  );
278}
279
280async function helpText(r: Runtime): Promise<string> {
281  const h = await r.client.health().catch(() => undefined);
282  return [
283    `helm ${r.version} · session ${r.session} · role ${r.role}${r.repo ? ` · ${r.repo}` : ''}`,
284    h ? `helmd ${h.version} pid ${h.pid} · ${h.web ?? ''}` : 'helmd not answering',
285    'commands: /helm pane · /helm role coordinator|repo|other [owner/name] · /helm web · /helm restart',
286  ].join('\n');
287}
288
289export const register: Register = (on) => {
290  const tools: Tool<Port>[] = [...TOOLS, dispatchTool()];
291
292  // outermost on every tool: letters waiting for the calling loop ride the result
293  on('tool.call', async ($, e, next) => {
294    const out = await next(e);
295    const r = rt;
296    if (!r?.alive || out.deny !== undefined) return out;
297    const text = await r.mailbox.attach(e.agentId).catch(() => undefined);
298    return text === undefined ? out : { ...out, context: [...(out.context ?? []), text] };
299  }).catch(($, e, next) => next(e));
300
301  on('session.start', async ($, e, next) => {
302    const started = await next(e);
303    if (rt) {
304      rt.alive = false;
305      rt.timers.forEach((t) => t.cancel());
306      rt.mailbox.stop();
307    }
308    const client = await clientFor($);
309    rolePrompts = { coordinator: await $.fs.read(`${$.plugin.root}/prompts/coordinator.md`), repo: await $.fs.read(`${$.plugin.root}/prompts/repo.md`) };
310    const manifest = JSON.parse(await $.fs.read(`${$.plugin.root}/package.json`)) as { name: string; version: string };
311    const install: Install = { root: $.plugin.root, name: manifest.name, version: manifest.version, protocol: PROTOCOL };
312    const repo = await sessionRepo($);
313    const env = (await $.env.get('HELM_ROLE')) as SessionRole | undefined;
314    const asked = env && ROLES.includes(env) ? env : undefined;
315    const r: Runtime = {
316      client,
317      version: install.version,
318      install,
319      home: (await $.env.get('HOME')) ?? '',
320      session: await $.session.id(),
321      // until helmd answers
322      role: asked ?? 'other',
323      ...(asked ? { asked } : {}),
324      ...(repo ? { checkout: repo } : {}),
325      instance: crypto.randomUUID(),
326      alive: true,
327      timers: [],
328      ...(repo ? { repo } : {}),
329      mailbox: new Mailbox({
330        now: Date.now,
331        take: (id) => client.take(id),
332        submit: async (text) => (await $.prompt.submit({ text })).drop === undefined,
333        send: async (agent, text) => {
334          const sent = await $.session.send({ to: { agentId: agent }, text });
335          return sent.isDelivered ? undefined : sent.reason;
336        },
337        retire: async (agent) => void (await client.retire(r.session, agent)),
338        status: async (agent) => (await $.agent.list()).find((a) => a.id === agent)?.status as AgentStatus | undefined,
339        after: (ms, fn) => $.clock.after(ms, () => void fn()),
340        log: (line) => $.ui.log(line, { to: 'debug' }),
341      }),
342    };
343    rt = r;
344    await update($, binder, () => r.instance);
345
346    for (const t of tools) await $.tool.register({ name: t.name, description: t.description, inputSchema: t.inputSchema, isDeferred: !t.eager });
347    await $.command.register({ name: PLUGIN, description: 'helm: status, role, web page' });
348    try {
349      await ensureDaemon($, client, install);
350      await bind($, r);
351      r.web = (await client.health()).web;
352      issueTypes.clear();
353      await registerTiers($, client, repo, r.session).catch((err: Error) => $.ui.log(`helm: issue agents not registered: ${err.message}`));
354    } catch (err) {
355      $.ui.log(`helm: ${(err as Error).message}`);
356    }
357    pump($, r);
358    if (r.role !== 'other') void $.ui.open({ id: PANE, title: 'helm' });
359    r.timers.push(
360      $.clock.every(HEARTBEAT_MS, () => {
361        void (async () => {
362          if (!(await holds($, r))) return;
363          await r.client.heartbeat(r.session, await agentRecords($)).catch(async (err: unknown) => {
364            if (err instanceof HelmError && err.status === 404) await bind($, r);
365          });
366        })().catch(() => {});
367      }),
368    );
369    return started;
370  });
371
372  on('session.end', async ($, e, next) => {
373    const out = await next(e);
374    const r = rt;
375    if (!r) return out;
376    if (e.reason === 'clear' || e.reason === 'resume') {
377      // the process goes on under another session id, with no session.start, and this instance keeps the binding; the
378      // new id takes over what the ended one held
379      await update($, binder, () => r.instance).catch(() => {});
380      r.timers.push($.clock.after(500, () => void bind($, r, e.sessionId).catch(() => {})));
381      return out;
382    }
383    r.alive = false;
384    r.timers.forEach((t) => t.cancel());
385    r.mailbox.stop();
386    await r.client.end(e.sessionId).catch(() => {});
387    return out;
388  });
389
390  on('turn.start', ($, e, next) => {
391    rt?.mailbox.turnStarted();
392    return next(e);
393  });
394
395  on('turn.complete', async ($, e, next) => {
396    const out = await next(e);
397    const r = rt;
398    if (r?.alive) {
399      if (e.agentId === undefined) await r.mailbox.turnEnded();
400      else await r.mailbox.agentEnded(e.agentId);
401    }
402    return out;
403  });
404
405  for (const t of tools) {
406    on('tool.call', { tool: `mcp__${PLUGIN}__${t.name}` }, async ($, e) => {
407      const r = rt;
408      if (!r) return { deny: 'helm is starting; call it again in a moment' };
409      if (t.mainOnly && e.agentId !== undefined) return { deny: `helm ${t.name} is the session's own: report to whoever spawned you instead` };
410      try {
411        const text = await t.run(toolEnv(r), e as unknown as Record<string, unknown>, e.agentId, port($));
412        return { result: [{ type: 'text', text }] };
413      } catch (err) {
414        return { deny: `helm ${t.name}: ${(err as Error).message}` };
415      }
416    }).catch(() => ({ deny: `helm ${t.name} failed inside its hook` }));
417  }
418
419  // a repository session and a coordinator each read how helm works in their role, so no instruction file has to
420  on('prompt.compose', async ($, e, next) => {
421    const out = await next(e);
422    const text = rt ? rolePrompt(rt) : undefined;
423    return text ? { sections: [...out.sections, { id: `${PLUGIN}:role`, text, scope: 'session' as const }] } : out;
424  });
425
426  // issue agents start through dispatch, which claims and routes them, so the model never starts one itself. the guard is
427  // on the spawn, not the offer: an offer is also asked when a message resumes an agent, and refusing it strands the agent
428  on('agent.spawn', ($, e, next) =>
429    isIssueType(e.subagentType) && next.origin.plugin !== PLUGIN ? { deny: 'issue agents start through mcp__helm__dispatch, which claims and routes the issue' } : next(e),
430  ).catch(($, e, next) => (next.called ? next(e) : { deny: 'the helm spawn guard failed' }));
431
432  // an issue agent answers to the session that dispatched it. the engine resolves a recipient against every session on
433  // the machine, so a send of an issue agent's that names no other agent of this session goes to this session's main
434  // loop through helmd instead, as a letter like any other
435  on('session.send', async ($, e, next) => {
436    const r = rt;
437    if (e.agentId === undefined || !r) return next(e);
438    if (sendRoute(e.to, e.agentId, await $.agent.list(), isIssueType) === 'engine') return next(e);
439    try {
440      await r.client.message({ session: r.session, agent: e.agentId, to: e.to, text: e.text });
441      return { isDelivered: true };
442    } catch (err) {
443      return { isDelivered: false, reason: `helm could not hand this to the session that dispatched you (${(err as Error).message}): put it in your final message instead` };
444    }
445  }).catch(($, e, next) => (next.called ? next(e) : { isDelivered: false, reason: 'the helm send guard failed: put this in your final message instead' }));
446
447  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
448    const r = rt;
449    await read($, fleetAt);
450    const tab = await read($, paneTab);
451    const f = fleet;
452    const { Text } = $.ui.resolve(e);
453    if (!r || !f) return <Text dimColor>helm is connecting to helmd</Text>;
454    return rowsOf($, e, paneRows(f, selfOf(r), { rows: Math.max(6, (e.viewport?.rows ?? 24) - 2), cols: e.viewport?.columns ?? 80, tab, ...(r.web ? { web: r.web } : {}) }));
455  });
456
457  // the pane's controls: a tab, an option that answers a decision, an escalation to the person, or a dismissal
458  on('ui.press', async ($, e, next) => {
459    if (e.requestId !== PANE) return next(e);
460    const r = rt;
461    const [kind, id, index] = e.element.split(':');
462    if (kind === 'tab' && isTab(id)) await update($, paneTab, () => id);
463    if (r && id && kind === 'answer') {
464      const option = fleet?.decisions.find((d) => d.id === id)?.options?.[Number(index)];
465      if (option) await r.client.answer(id, { text: '', option, by: 'pane' }).then(() => refresh($, r), (err: Error) => $.ui.log(`helm: answer failed: ${err.message}`, { to: 'debug' }));
466    }
467    if (r && id && kind === 'escalate') await r.client.escalate(id, { by: 'pane' }).then(() => refresh($, r), (err: Error) => $.ui.log(`helm: escalate failed: ${err.message}`, { to: 'debug' }));
468    if (r && id && kind === 'dismiss') await r.client.dismiss(id).then(() => refresh($, r), (err: Error) => $.ui.log(`helm: dismiss failed: ${err.message}`, { to: 'debug' }));
469    return next(e);
470  }).catch(($, e, next) => next(e));
471
472  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
473    const r = rt;
474    await read($, fleetAt);
475    const f = fleet;
476    const band = r && f && !e.props.hasSurvey ? bandRow(f, selfOf(r)) : undefined;
477    if (!band) return next(e);
478    const { Box } = $.ui.resolve(e);
479    return (
480      <Box flexDirection="column">
481        {await next(e)}
482        {rowsOf($, e, [band])}
483      </Box>
484    );
485  });
486
487  on('command.run', { command: PLUGIN }, async ($, e) => {
488    const r = rt;
489    if (!r) return { text: 'helm is starting' };
490    const [head = '', ...rest] = e.args.trim().split(/\s+/).filter(Boolean);
491    try {
492      if (head === 'role') {
493        const role = rest[0] as SessionRole;
494        if (!ROLES.includes(role)) return { text: 'usage: /helm role coordinator|repo|other [owner/name]' };
495        const repo = rest[1] && isRepoName(rest[1]) ? rest[1] : r.repo;
496        const s = await r.client.role(r.session, role, repo);
497        r.asked = s.role;
498        r.role = s.role;
499        if (s.repo) r.repo = s.repo;
500        return { text: `this session is now ${s.role}${s.repo && s.role === 'repo' ? ` for ${s.repo}` : ''}` };
501      }
502      if (head === 'pane') {
503        const opened = await $.ui.open({ id: PANE, title: 'helm', focus: true });
504        refresh($, r);
505        return { text: opened.isPlaced ? 'helm pane open' : `helm pane waits: ${opened.reason}` };
506      }
507      if (head === 'web') {
508        const url = (await r.client.health()).web ?? '';
509        await $.process.run(['xdg-open', url]).catch(() => undefined);
510        return { text: url };
511      }
512      if (head === 'restart') {
513        const res = await $.process.run(daemonArgv((await daemonInstall($, r.install)).root, 'restart'), { timeoutMs: 30_000 });
514        if (res.exitCode !== 0) throw new Error(`helmd restart failed: ${(res.stderr || res.stdout).trim()}`);
515        return { text: 'helmd restarted' };
516      }
517      return { text: await helpText(r) };
518    } catch (err) {
519      return { text: `helm: ${(err as Error).message}` };
520    }
521  });
522};
523
src/core/paths.ts 43 lines
1export type PathEnv = {
2  HOME: string;
3  XDG_RUNTIME_DIR?: string;
4  XDG_STATE_HOME?: string;
5  XDG_CONFIG_HOME?: string;
6  XDG_CACHE_HOME?: string;
7  HELM_SOCKET?: string;
8  HELM_HOME?: string;
9};
10
11export type HelmPaths = {
12  socket: string;
13  state: string;
14  config: string;
15  cache: string;
16  ledger: string;
17  repos: string;
18  logs: string;
19  lock: string;
20  daemonLog: string;
21};
22
23// where helmd keeps everything, resolved the same way by the daemon and by every session's mod. HELM_HOME puts it
24// all under one directory, for tests and for running a second daemon beside the real one
25export function helmPaths(env: PathEnv): HelmPaths {
26  const root = env.HELM_HOME;
27  const state = root ? `${root}/state` : `${env.XDG_STATE_HOME || `${env.HOME}/.local/state`}/helm`;
28  const config = root ? `${root}/config` : `${env.XDG_CONFIG_HOME || `${env.HOME}/.config`}/helm`;
29  const cache = root ? `${root}/cache` : `${env.XDG_CACHE_HOME || `${env.HOME}/.cache`}/helm`;
30  const runtime = root ? `${root}/run` : env.XDG_RUNTIME_DIR ? `${env.XDG_RUNTIME_DIR}/helm` : `${state}/run`;
31  return {
32    socket: env.HELM_SOCKET || `${runtime}/helmd.sock`,
33    state,
34    config,
35    cache,
36    ledger: `${state}/ledger.json`,
37    repos: `${state}/repos`,
38    logs: `${cache}/logs`,
39    lock: `${runtime}/helmd.lock`,
40    daemonLog: `${state}/helmd.log`,
41  };
42}
43
src/core/protocol.ts 141 lines
1import type { Config, Field } from './config.ts';
2import { compareVersions } from './repo.ts';
3import type { AgentRecord, CiFilter, Decision, DecisionKind, Effort, Letter, PlanStep, ReportState, RepoName, Routing, Scope, SessionRole, Tier, Until } from './types.ts';
4
5// bumped when a route or a body changes shape; a mod that finds an older daemon replaces it
6export const PROTOCOL = 4;
7
8export type Health = { version: string; protocol: number; pid: number; startedAt: number; web?: string };
9
10// what a mod does about the helmd it finds: start one, replace an older one, use one as new or newer, or, when that one
11// speaks a newer protocol, wait for this session to reload onto a mod that speaks it. a newer helmd is never replaced
12export function daemonAction(up: Pick<Health, 'version' | 'protocol'> | undefined, version: string, protocol = PROTOCOL): 'start' | 'restart' | 'use' | 'reload' {
13  if (!up) return 'start';
14  if (up.protocol > protocol) return 'reload';
15  if (up.protocol < protocol || compareVersions(up.version, version) < 0) return 'restart';
16  return 'use';
17}
18
19// from: the session this one goes on from in the same process, as a /clear or a resume ended it. role is the role the
20// session was asked to take; repo is its checkout's, a default for a session helmd does not know. protocol is the mod's:
21// before 3 a mod sent the role it guessed, which only defaults a new session
22export type RegisterBody = { id: string; cwd: string; role?: SessionRole; repo?: RepoName; title?: string; from?: string; protocol?: number };
23
24export type HeartbeatBody = { agents: AgentRecord[] };
25
26export type RoleBody = { role: SessionRole; repo?: RepoName };
27
28export type SubscribeBody = {
29  repo?: RepoName;
30  scope: Scope;
31  ci?: CiFilter;
32  tags?: string[];
33  bots?: boolean;
34  until?: Until;
35  // a pr subscription's head as the caller pushed it: ci on a head strictly behind it is not delivered
36  sha?: string;
37  session: string;
38  agent?: string;
39};
40
41export type QueueBody = { session: string; repo: RepoName; issues: number[] };
42
43// title: what the caller read of the issue, for when the forge cache has not seen it yet
44export type ClaimBody = { session: string; repo: RepoName; issue: number; title?: string; agent?: string; routing?: Routing; force?: boolean };
45
46export type ReportBody = {
47  session: string;
48  agent?: string;
49  repo: RepoName;
50  issue: number;
51  state: ReportState;
52  note?: string;
53  // a question that stops the agent until answered
54  question?: { title: string; body: string; options?: string[] };
55  // choices made without the person, recorded for review
56  choices?: { title: string; body: string }[];
57  // the plan as it stands, every step with whether it is done
58  plan?: PlanStep[];
59};
60
61export type ReleaseBody = { session: string; repo: RepoName; issue: number; how?: 'abandoned' };
62
63export type OrderBody = { session: string; keys: string[] };
64
65export type DecisionBody = {
66  kind: DecisionKind;
67  repo?: RepoName;
68  issue?: number;
69  title: string;
70  body: string;
71  options?: string[];
72  blocking: boolean;
73  from?: { session: string; agent?: string };
74};
75
76// a message an agent of session sent to: helmd hands it to that session's main loop, whatever to names
77export type MessageBody = { session: string; agent: string; to: string; text: string };
78
79export type AnswerBody = { text: string; option?: string; by: string };
80
81export type EscalateBody = { by: string; note?: string };
82
83export type RoutingConfig = { judge: string; review: number; tiers: Tier[]; fallback: string };
84
85export type ConfigView = { routing: RoutingConfig; web?: string };
86
87// the machine's config as the settings page shows and edits it
88export type SettingsView = {
89  file: string;
90  // the user layer as the file holds it: {} when there is no file, null when the file is not json
91  layer: Record<string, unknown> | null;
92  // why helmd could not apply the file as it stands; config is then the one still running
93  error?: string;
94  config: Config;
95  defaults: Config;
96  sources: Record<Field, 'user' | 'default'>;
97  restart: readonly Field[];
98};
99
100// layer: the whole user layer to write. base: the layer as the page read it, so a save over a file changed since is refused
101export type SettingsBody = { layer: Record<string, unknown>; base: Record<string, unknown> | null };
102
103// what a session's stream carries, one json object a line
104export type StreamFrame =
105  | { type: 'hello'; version: string; protocol: number }
106  | { type: 'letter'; letter: Letter }
107  | { type: 'changed'; at: number }
108  | { type: 'ping'; at: number };
109
110export type IssueDetail = {
111  repo: RepoName;
112  number: number;
113  title: string;
114  state: string;
115  url: string;
116  pr: boolean;
117  author: string;
118  labels: string[];
119  body: string;
120  comments: { author: string; at: string; url: string; body: string }[];
121};
122
123export type Problem = { error: string; detail?: unknown };
124
125export type ClaimRefused = Problem & { owner: string };
126
127export type Answered = { decision: Decision; delivered: boolean };
128
129export function workKey(repo: RepoName, issue: number): string {
130  return `${repo}#${issue}`;
131}
132
133export function parseWorkKey(key: string): { repo: RepoName; issue: number } | undefined {
134  const m = /^([^/\s#]+\/[^/\s#]+)#(\d+)$/.exec(key);
135  return m ? { repo: m[1]!, issue: Number(m[2]) } : undefined;
136}
137
138export function isEffort(v: unknown): v is Effort {
139  return v === 'low' || v === 'medium' || v === 'high' || v === 'xhigh' || v === 'max';
140}
141
src/core/repo.ts 20 lines
1import type { RepoName } from './types.ts';
2
3// owner/name of a github remote url in any of its spellings
4export function repoOfRemote(url: string): RepoName | undefined {
5  const m = /github\.com[:/]+([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(url.trim());
6  return m ? `${m[1]}/${m[2]}` : undefined;
7}
8
9export function isRepoName(v: unknown): v is RepoName {
10  return typeof v === 'string' && /^[\w.-]+\/[\w.-]+$/.test(v);
11}
12
13// a strict semver comparison of x.y.z, prerelease ignored; negative when a is older
14export function compareVersions(a: string, b: string): number {
15  const pa = a.split(/[.-]/).slice(0, 3).map(Number);
16  const pb = b.split(/[.-]/).slice(0, 3).map(Number);
17  for (let i = 0; i < 3; i++) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) - (pb[i] ?? 0);
18  return 0;
19}
20
src/core/types.ts 466 lines
1// the contract between helmd, the mod and the web page. plain json data only: everything here crosses a socket
2
3export type RepoName = string;
4
5export type Author = { login: string; bot: boolean };
6
7export type Note = { author: Author; at: string; url: string; text: string };
8
9export type IssueRef = { repo: RepoName; number: number };
10
11// one sub-issue as its parent lists it; its repository may be one helm does not poll
12export type Child = IssueRef & { title: string; url: string; state: 'open' | 'closed'; subIssues?: { total: number; done: number } };
13
14export type Issue = {
15  number: number;
16  title: string;
17  url: string;
18  state: 'open' | 'closed';
19  // why it closed, as the forge says it (completed, not_planned, duplicate)
20  reason?: string;
21  author: Author;
22  labels: string[];
23  assignees: string[];
24  parent?: IssueRef;
25  subIssues?: { total: number; done: number };
26  // open issues it is blocked by, as github's issue dependencies record them; read for open issues only
27  blockedBy?: number;
28  comments: number;
29  lastComment?: Note;
30  createdAt: string;
31  updatedAt: string;
32  closedAt?: string;
33};
34
35export type CheckState = 'queued' | 'running' | 'success' | 'failure' | 'neutral' | 'skipped' | 'cancelled';
36
37// one check on a commit: a check run (with its actions job and run when it has one) or a commit status
38export type Check = {
39  name: string;
40  state: CheckState;
41  url?: string;
42  job?: number;
43  run?: number;
44  workflow?: string;
45  startedAt?: string;
46  completedAt?: string;
47};
48
49export type Verdict = 'pending' | 'success' | 'failure' | 'none';
50
51export type Pull = {
52  number: number;
53  title: string;
54  url: string;
55  state: 'open' | 'closed' | 'merged';
56  draft: boolean;
57  author: Author;
58  head: string;
59  sha: string;
60  // the head branch lives in a fork, so this machine's origin/<head> is not it
61  fork?: boolean;
62  base: string;
63  closes: number[];
64  review?: string;
65  mergeable?: string;
66  comments: number;
67  lastComment?: Note;
68  reviews: number;
69  lastReview?: Note & { state: string };
70  checks: Check[];
71  createdAt: string;
72  updatedAt: string;
73  closedAt?: string;
74};
75
76export type Step = { number: number; name: string; state: CheckState };
77
78export type Job = {
79  id: number;
80  run: number;
81  name: string;
82  state: CheckState;
83  url: string;
84  steps: Step[];
85  startedAt?: string;
86  completedAt?: string;
87};
88
89export type Run = {
90  id: number;
91  workflow: string;
92  branch: string;
93  sha: string;
94  event: string;
95  state: CheckState;
96  url: string;
97  actor: string;
98  // ref is a tag, not a branch
99  tag?: boolean;
100  createdAt: string;
101  updatedAt: string;
102  // jobs are read only while the run is in flight and once when it completes
103  jobs?: Job[];
104};
105
106// what the forge holds for one repository, as of the last poll
107export type ForgeState = {
108  repo: RepoName;
109  defaultBranch: string;
110  issues: Issue[];
111  pulls: Pull[];
112  runs: Run[];
113  // issue number -> its sub-issues, for every issue here that has any
114  children: Record<number, Child[]>;
115  polledAt: number;
116};
117
118export type Worktree = {
119  path: string;
120  branch?: string;
121  sha: string;
122  main: boolean;
123  dirty: number;
124  ahead?: number;
125  behind?: number;
126  upstream?: string;
127  locked?: boolean;
128};
129
130export type Branch = {
131  name: string;
132  sha: string;
133  upstream?: string;
134  ahead?: number;
135  behind?: number;
136  gone?: boolean;
137  committedAt: number;
138};
139
140// what the machine holds for one repository: its checkouts, their worktrees and the local branches
141export type LocalState = {
142  repo: RepoName;
143  checkouts: string[];
144  worktrees: Worktree[];
145  branches: Branch[];
146  scannedAt: number;
147};
148
149export type SessionRole = 'coordinator' | 'repo' | 'other';
150
151// the engine's agent statuses, and gone for one no live session lists
152export type AgentStatus = 'pending' | 'running' | 'waiting' | 'idle' | 'completed' | 'failed' | 'killed' | 'gone';
153
154export type AgentRecord = {
155  id: string;
156  name?: string;
157  type: string;
158  description: string;
159  status: AgentStatus;
160  parentId?: string;
161};
162
163export type Session = {
164  id: string;
165  role: SessionRole;
166  // the role was asked for, at launch or with /helm role, and is kept; without it the role is a default
167  asked?: boolean;
168  repo?: RepoName;
169  cwd: string;
170  title?: string;
171  agents: AgentRecord[];
172  startedAt: number;
173  seenAt: number;
174  // set once a heartbeat is overdue; a session that comes back clears it
175  gone?: boolean;
176  // what this session took over by succession and has not given back, oldest first
177  adoptions?: AdoptionRecord[];
178};
179
180// one succession: what moved to the adopting session and what each thing was before, so it can be given back exactly.
181// a work item is still the adoption's while its owner is unchanged, its agent is the one it came with and nobody has
182// reported on it since
183export type AdoptionRecord = {
184  at: number;
185  repo: RepoName;
186  work: { key: string; agent?: string; was: Pick<Work, 'owner' | 'order' | 'report' | 'adopted'> }[];
187  subscriptions: { id: string; agent?: string; was: string }[];
188  decisions: { id: string; was: Pick<Decision, 'to' | 'session' | 'escalated'> }[];
189};
190
191export type Tier = {
192  name: string;
193  model: string;
194  effort: Effort;
195  // when an issue belongs on this tier, read by the routing judge
196  when: string;
197  // false: caller-only, never shown to the routing judge and used only when a caller names it
198  judge?: boolean;
199};
200
201export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
202
203export const EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh', 'max'];
204
205export type Routing = {
206  tier?: string;
207  model: string;
208  effort: Effort;
209  by: 'judge' | 'caller' | 'human';
210  confidence?: number;
211  reason?: string;
212  at: number;
213};
214
215// one dispatch's routing as logged when its agent started, kept after the work's own routing moves on
216export type RoutingPick = Routing & { repo: RepoName; issue: number; agent?: string };
217
218// what an agent says about its own work: the states only it can know
219export type ReportState = 'working' | 'waiting' | 'blocked' | 'ready' | 'stopped' | 'abandoned';
220
221export type Report = { state: ReportState; note?: string; at: number };
222
223export type PlanStep = { text: string; done: boolean };
224
225// a live process an ended agent left in its worktree; helm reports it and never kills it
226export type Leftover = { pid: number; command: string };
227
228// one issue in the ledger: queued in a session's backlog, then worked by one agent at a time
229export type Work = {
230  repo: RepoName;
231  issue: number;
232  title: string;
233  owner?: string;
234  order: number;
235  agent?: string;
236  routing?: Routing;
237  report?: Report;
238  // the agent's plan as it last reported it
239  plan?: PlanStep[];
240  // what was still running in its worktree when its agent last ended
241  leftovers?: Leftover[];
242  // when the work entered each phase, oldest first
243  history?: { phase: Phase; at: number }[];
244  queuedAt: number;
245  claimedAt?: number;
246  updatedAt: number;
247  finished?: { at: number; how: 'merged' | 'closed' | 'abandoned' | 'gone' | 'pull' };
248  // taken over from a gone session; agent is the one it had then, gone with that session and so never resumed
249  adopted?: { from: string; at: number; agent?: string };
250};
251
252// parked: set aside on purpose, by a stopped report or, with nobody on it, a blocked or parked label or an open blocked-by
253export type Phase = 'queued' | 'working' | 'draft' | 'ci' | 'failing' | 'ready' | 'blocked' | 'stalled' | 'parked' | 'done';
254
255// a work item joined with what the forge, the machine and the ledger say about it now
256export type WorkView = Work & {
257  phase: Phase;
258  agentStatus?: AgentStatus;
259  pull?: Pick<Pull, 'number' | 'url' | 'draft' | 'state' | 'head' | 'sha'>;
260  verdict: Verdict;
261  checks: Check[];
262  jobs: Job[];
263  worktree?: Worktree;
264  decisions: number;
265  issueState?: 'open' | 'closed';
266  issueUrl?: string;
267};
268
269// what a subtree of the hierarchy adds up to, counted over its leaves
270export type Rollup = {
271  total: number;
272  done: number;
273  // worked by an agent: working, draft, ci or ready
274  active: number;
275  // blocked, failing or stalled
276  attention: number;
277  ci: number;
278  // ready to merge, also counted active
279  ready: number;
280  queued: number;
281  // set aside on purpose; neither active nor attention
282  parked: number;
283  // open with nobody on it
284  unowned: number;
285};
286
287export type TreeNode = IssueRef & {
288  title: string;
289  url: string;
290  state: 'open' | 'closed';
291  // the work item's phase when the ledger has one, done when closed, absent when open and unowned
292  phase?: Phase;
293  owner?: string;
294  agent?: string;
295  tier?: string;
296  plan?: { done: number; total: number };
297  // a sub-epic in a repository helm does not poll: counted from its summary, its children unknown
298  external?: boolean;
299  children: TreeNode[];
300  rollup: Rollup;
301};
302
303export type DecisionKind = 'routing' | 'question' | 'choice' | 'stall' | 'failure';
304
305export type Answer = { text: string; option?: string; by: string; at: number };
306
307// who a decision is for: the person, or the session that owns the work it concerns
308export type Audience = 'person' | 'session';
309
310export type Decision = {
311  id: string;
312  kind: DecisionKind;
313  repo?: RepoName;
314  issue?: number;
315  title: string;
316  body: string;
317  options?: string[];
318  // true when someone is stopped until it is answered
319  blocking: boolean;
320  from?: { session: string; agent?: string };
321  to: Audience;
322  // the session it is addressed to, set exactly when to is session
323  session?: string;
324  // handed on to the person: by the session it was addressed to, or by helm once that session is gone
325  escalated?: { by: string; note?: string; at: number };
326  state: 'open' | 'answered' | 'dismissed' | 'resolved';
327  answer?: Answer;
328  // a condition helmd raised and clears itself once it no longer holds
329  key?: string;
330  // what held when it was raised; a dismissal holds against it until the condition changes or ends
331  condition?: string;
332  createdAt: number;
333  updatedAt: number;
334};
335
336export type Scope =
337  | { kind: 'repo' }
338  | { kind: 'issue'; number: number }
339  | { kind: 'pr'; number: number }
340  | { kind: 'branch'; name: string }
341  | { kind: 'run'; id: number }
342  | { kind: 'tag'; glob: string }
343  // the work items the subscriber's session owns, across repositories
344  | { kind: 'work' }
345  // every work item, decision and session, across the machine
346  | { kind: 'fleet' };
347
348export type CiFilter = 'settled' | 'failures' | 'all' | 'none';
349
350export type Until = 'settled' | 'merged' | 'closed' | { at: string };
351
352export type Subscription = {
353  id: string;
354  // absent for the work and fleet scopes, which span repositories
355  repo?: RepoName;
356  scope: Scope;
357  ci: CiFilter;
358  // the item tags delivered; absent takes the defaults
359  tags?: string[];
360  bots: boolean;
361  until?: Until;
362  // a pr subscription's expected head. named by the caller, ci on a head that is neither it nor past it is not its
363  // verdict; guessed from the local checkout, which can itself be stale, only ci on a head strictly behind it is not
364  head?: string;
365  named?: boolean;
366  // the pr head whose settled ci this subscription held back, seen again by a later poll once that head stays: the
367  // verdict it waits on can then no longer come, and the wait no longer counts as work going on
368  held?: { sha: string; seen?: true };
369  session: string;
370  agent?: string;
371  createdAt: number;
372};
373
374export type EventKind = 'issue' | 'pr' | 'ci' | 'work' | 'decision' | 'epic';
375
376export type HelmEvent = {
377  id: string;
378  kind: EventKind;
379  repo?: RepoName;
380  at: number;
381  // what the event is about, matched against scopes
382  issue?: number;
383  pr?: number;
384  branch?: string;
385  run?: number;
386  sha?: string;
387  tag?: string;
388  // tags a filter reads: opened, closed, merged, comment, review, ready, draft, edited, labeled, settled, stalled,
389  // completed, success, failure, phase, decision, answered, progress, complete, leftovers, unowned
390  tags: string[];
391  author?: Author;
392  // one line, then detail lines
393  text: string;
394  detail?: string[];
395  url?: string;
396  // the session whose work it is, for the work scope
397  owner?: string;
398  // the root epic a work event rolls up into, whose progress event speaks for it on the fleet scope
399  epic?: string;
400  // a work event's phase change, which a later one of the same item supersedes
401  phase?: { from: Phase | 'new'; to: Phase; title: string };
402};
403
404// one event of a letter: the group it is listed under, [helm <head>], absent for a letter of its own words; its
405// lines; and for a phase change, the item and the phases it went through, which a newer part of the item extends
406export type LetterPart = {
407  head?: string;
408  lines: string[];
409  phase?: { key: string; path: string[]; title: string };
410};
411
412// one delivery to a session, or to one agent of it
413export type Letter = {
414  id: string;
415  session: string;
416  agent?: string;
417  // the parts rendered whole, what a reader without the parts shows
418  text: string;
419  // absent on a letter posted before letters carried parts
420  parts?: LetterPart[];
421  events: string[];
422  subs: string[];
423  at: number;
424};
425
426// a lite view carries only polling and the runs in flight or just finished, what a pane draws its ci from
427export type RepoView = { forge?: ForgeState; local?: LocalState; polling: PollStatus; runs?: Run[] };
428
429export type PollStatus = {
430  active: boolean;
431  interval: number;
432  lastPoll?: number;
433  lastChange?: number;
434  error?: string;
435  failures: number;
436};
437
438// a claude process running in a checkout of a repository that never registered with helm: one waiting on input
439// before its conversation starts, such as a `claude --resume <term>` in its picker
440export type Waiting = { pid: number; cwd: string; since?: number };
441
442// a repository with unfinished work, or that had a repo session, or with a claude process waiting in its checkout,
443// where no repo session is live: nobody dispatches its work, and each issue opened in it reaches the coordinator at
444// once. last is its repo session seen most recently
445export type Unattended = { repo: RepoName; open: number; last?: { session: string; seenAt: number }; waiting?: Waiting[] };
446
447export type Fleet = {
448  version: string;
449  sessions: Session[];
450  unattended: Unattended[];
451  work: WorkView[];
452  decisions: Decision[];
453  subscriptions: Subscription[];
454  repos: Record<RepoName, RepoView>;
455  // every epic in the watched repositories that no other epic here holds, with its subtree
456  tree: TreeNode[];
457  // the newest events, newest last; absent from a lite answer
458  events?: HelmEvent[];
459  rates: Record<string, { remaining: number; limit: number; resetAt: number }>;
460  // the phases where work needs someone, for the page to mark without its own copy
461  attention: Phase[];
462  // the routing picks the ledger keeps, oldest first
463  picks: RoutingPick[];
464  at: number;
465};
466
src/mod/client.ts 113 lines
1import type {
2  AnswerBody,
3  Answered,
4  ClaimBody,
5  ConfigView,
6  DecisionBody,
7  EscalateBody,
8  Health,
9  IssueDetail,
10  MessageBody,
11  OrderBody,
12  QueueBody,
13  RegisterBody,
14  ReleaseBody,
15  ReportBody,
16  SubscribeBody,
17} from '../core/protocol.ts';
18import type { AgentRecord, Decision, Fleet, Letter, RepoName, RepoView, Session, SessionRole, Subscription, Work } from '../core/types.ts';
19
20export type HttpLike = (url: string, init: { method?: string; headers?: Record<string, string>; body?: string; socketPath: string }) => Promise<{ status: number; ok: boolean; text: string }>;
21
22export class HelmError extends Error {
23  status: number;
24  detail?: unknown;
25  constructor(status: number, message: string, detail?: unknown) {
26    super(message);
27    this.status = status;
28    this.detail = detail;
29  }
30}
31
32const enc = encodeURIComponent;
33
34// helmd's socket api as typed calls. every failure is a HelmError with the daemon's own words
35export class HelmClient {
36  readonly socket: string;
37  private readonly http: HttpLike;
38
39  constructor(http: HttpLike, socket: string) {
40    this.http = http;
41    this.socket = socket;
42  }
43
44  async call<T>(method: string, path: string, body?: unknown): Promise<T> {
45    let res;
46    try {
47      res = await this.http(`http://helmd${path}`, {
48        method,
49        socketPath: this.socket,
50        ...(body === undefined ? {} : { body: JSON.stringify(body), headers: { 'content-type': 'application/json' } }),
51      });
52    } catch (e) {
53      throw new HelmError(0, `helmd unreachable on ${this.socket}: ${(e as Error).message}`);
54    }
55    const parsed = res.text ? safeJson(res.text) : null;
56    if (!res.ok) {
57      const p = parsed as { error?: string; detail?: unknown } | null;
58      throw new HelmError(res.status, p?.error ?? `http ${res.status}`, p?.detail);
59    }
60    return (parsed ?? res.text) as T;
61  }
62
63  async text(path: string): Promise<string> {
64    const res = await this.http(`http://helmd${path}`, { socketPath: this.socket }).catch((e: Error) => {
65      throw new HelmError(0, `helmd unreachable: ${e.message}`);
66    });
67    if (!res.ok) throw new HelmError(res.status, (safeJson(res.text) as { error?: string } | null)?.error ?? `http ${res.status}`);
68    return res.text;
69  }
70
71  health = () => this.call<Health>('GET', '/v1/health');
72  shutdown = () => this.call<unknown>('POST', '/v1/shutdown');
73  fleet = (lite = false) => this.call<Fleet>('GET', `/v1/fleet${lite ? '?lite=1' : ''}`);
74  config = (repo?: RepoName) => this.call<ConfigView>('GET', `/v1/config${repo ? `?repo=${enc(repo)}` : ''}`);
75  register = (b: RegisterBody) => this.call<Session>('POST', '/v1/sessions', b);
76  heartbeat = (id: string, agents: AgentRecord[]) => this.call<Session>('POST', `/v1/sessions/${enc(id)}/heartbeat`, { agents });
77  role = (id: string, role: SessionRole, repo?: RepoName) => this.call<Session>('POST', `/v1/sessions/${enc(id)}/role`, { role, ...(repo ? { repo } : {}) });
78  end = (id: string) => this.call<unknown>('POST', `/v1/sessions/${enc(id)}/end`);
79  letters = (session: string, agent?: string) => this.call<Letter[]>('GET', `/v1/letters?session=${enc(session)}${agent ? `&agent=${enc(agent)}` : ''}`);
80  // undefined once another taker had it
81  take = (id: string) =>
82    this.call<Letter>('POST', `/v1/letters/${enc(id)}/take`).catch((e: unknown) => {
83      if (e instanceof HelmError && e.status === 404) return undefined;
84      throw e;
85    });
86  message = (b: MessageBody) => this.call<Letter>('POST', '/v1/messages', b);
87  subscribe = (b: SubscribeBody) => this.call<Subscription>('POST', '/v1/subscriptions', b);
88  unsubscribe = (id: string) => this.call<{ removed: boolean }>('DELETE', `/v1/subscriptions/${enc(id)}`);
89  retire = (session: string, agent: string) => this.call<{ retired: string[] }>('POST', '/v1/subscriptions/retire', { session, agent });
90  queue = (b: QueueBody) => this.call<Work[]>('POST', '/v1/work/queue', b);
91  claim = (b: ClaimBody) => this.call<Work>('POST', '/v1/work/claim', b);
92  report = (b: ReportBody) => this.call<{ work: Work; decisions: Decision[] }>('POST', '/v1/work/report', b);
93  release = (b: ReleaseBody) => this.call<Work | null>('POST', '/v1/work/release', b);
94  order = (b: OrderBody) => this.call<{ ordered: number }>('POST', '/v1/work/order', b);
95  decide = (b: DecisionBody) => this.call<Decision>('POST', '/v1/decisions', b);
96  answer = (id: string, b: AnswerBody) => this.call<Answered>('POST', `/v1/decisions/${enc(id)}/answer`, b);
97  escalate = (id: string, b: EscalateBody) => this.call<Decision>('POST', `/v1/decisions/${enc(id)}/escalate`, b);
98  dismiss = (id: string) => this.call<Decision>('POST', `/v1/decisions/${enc(id)}/dismiss`);
99  repo = (repo: RepoName) => this.call<RepoView>('GET', `/v1/repos/${repo}`);
100  poll = (repo: RepoName) => this.call<RepoView>('POST', `/v1/repos/${repo}/poll`);
101  issue = (repo: RepoName, n: number) => this.call<IssueDetail>('GET', `/v1/repos/${repo}/issues/${n}`);
102  log = (repo: RepoName, job: number, q: { tail?: number; grep?: string; errors?: boolean }) =>
103    this.text(`/v1/repos/${repo}/jobs/${job}/log?${[q.tail ? `tail=${q.tail}` : '', q.grep ? `grep=${enc(q.grep)}` : '', q.errors ? 'errors=1' : ''].filter(Boolean).join('&')}`);
104}
105
106function safeJson(text: string): unknown {
107  try {
108    return JSON.parse(text);
109  } catch {
110    return text;
111  }
112}
113
src/mod/install.ts 40 lines
1import { compareVersions } from '../core/repo.ts';
2
3// one copy of helm on the machine: where it is, its version, and the protocol its helmd speaks
4export type Install = { root: string; name: string; version: string; protocol: number };
5
6export type InstallFs = { dirs: (path: string) => Promise<string[]>; read: (path: string) => Promise<string> };
7
8type Manifest = { name?: unknown; version?: unknown; helm?: { protocol?: unknown } };
9
10// what a package.json says of the install at root, when it declares the protocol its helmd speaks
11export function installOf(root: string, text: string): Install | undefined {
12  let m: Manifest;
13  try {
14    m = JSON.parse(text) as Manifest;
15  } catch {
16    return undefined;
17  }
18  const protocol = m.helm?.protocol;
19  if (typeof m.name !== 'string' || typeof m.version !== 'string' || typeof protocol !== 'number') return undefined;
20  return { root, name: m.name, version: m.version, protocol };
21}
22
23// the helmd a mod starts: the newest install beside its own that speaks its protocol. the plugin cache keeps every
24// installed version side by side, each in a directory named for it; a root laid out otherwise (a dev checkout,
25// --plugin-dir) has only itself
26export async function newestInstall(own: Install, fs: InstallFs): Promise<Install> {
27  const root = own.root.replace(/\/+$/, '');
28  const cut = root.lastIndexOf('/');
29  if (cut <= 0 || root.slice(cut + 1) !== own.version) return own;
30  const parent = root.slice(0, cut);
31  let best = own;
32  for (const name of await fs.dirs(parent).catch(() => [])) {
33    if (!/^\d+\.\d+\.\d+/.test(name) || compareVersions(name, best.version) <= 0) continue;
34    const text = await fs.read(`${parent}/${name}/package.json`).catch(() => undefined);
35    const it = text === undefined ? undefined : installOf(`${parent}/${name}`, text);
36    if (it && it.name === own.name && it.version === name && it.protocol === own.protocol) best = it;
37  }
38  return best;
39}
40
src/mod/dispatch.ts 110 lines
1import { isRepoName } from '../core/repo.ts';
2import { workKey } from '../core/protocol.ts';
3import type { Effort, RepoName, Routing } from '../core/types.ts';
4import { HelmError } from './client.ts';
5import { asRouting, parseRouting, routingPrompt } from './routing.ts';
6import type { Tool, ToolEnv } from './tools.ts';
7
8// what dispatch needs of the engine, built by the hooks module
9export type DispatchPort = {
10  // the issue agent type for one model at one effort, registered on first use
11  agentType: (model: string, effort: Effort) => Promise<string>;
12  spawn: (a: { subagentType: string; description: string; prompt: string }) => Promise<{ agentId?: string; deny?: string }>;
13  complete: (a: { model: string; prompt: string }) => Promise<{ text: string } | { failed: string }>;
14  now: () => number;
15};
16
17export type DispatchInput = { repo?: RepoName; issues: number[]; tier?: string; context?: string };
18
19// the agent type an issue runs as: a spawn takes neither a full model id nor an effort, an agent type takes both, so
20// each model and effort a tier names is a type of its own
21export function issueAgentName(model: string, effort: Effort): string {
22  return `issue-${model.replace(/[^\w-]/g, '-')}-${effort}`.slice(0, 64);
23}
24
25export async function dispatchIssues(env: ToolEnv, port: DispatchPort, input: DispatchInput): Promise<string> {
26  const repo = env.repo(input.repo);
27  const cfg = (await env.client.config(repo)).routing;
28  const named = input.tier ? cfg.tiers.find((t) => t.name === input.tier) : undefined;
29  if (input.tier && !named) throw new HelmError(400, `no tier ${input.tier}: ${cfg.tiers.map((t) => t.name).join(', ')}`);
30  const lines: string[] = [];
31  for (const issue of input.issues) {
32    const key = workKey(repo, issue);
33    try {
34      const detail = await env.client.issue(repo, issue);
35      if (detail.pr || detail.state !== 'open') {
36        lines.push(`${key}: ${detail.pr ? 'a pull request' : detail.state}, not dispatched`);
37        continue;
38      }
39      await env.client.claim({ session: env.session(), repo, issue, title: detail.title });
40      let routing: Routing;
41      if (named) routing = asRouting(named, 'caller', port.now());
42      else {
43        const work = (await env.client.fleet(true)).work.find((w) => w.repo === repo && w.issue === issue);
44        const answer = await port.complete({ model: cfg.judge, prompt: routingPrompt(detail, cfg.tiers, work) });
45        const fallback = cfg.tiers.find((t) => t.name === cfg.fallback)!;
46        routing = 'text' in answer ? parseRouting(answer.text, cfg, port.now()) : { ...asRouting(fallback, 'judge', port.now()), confidence: 0, reason: `the judge did not answer (${answer.failed}); fell back to ${fallback.name}` };
47      }
48      const spawned = await port.spawn({
49        subagentType: await port.agentType(routing.model, routing.effort),
50        description: `#${issue} ${detail.title}`.slice(0, 60),
51        prompt: [`Issue ${key}: ${detail.title}`, detail.url, ...(input.context ? ['', input.context] : [])].join('\n'),
52      });
53      if (spawned.deny !== undefined || !spawned.agentId) {
54        lines.push(`${key}: the agent did not start: ${spawned.deny ?? 'no agent id'}; it stays queued`);
55        continue;
56      }
57      await env.client.claim({ session: env.session(), repo, issue, title: detail.title, agent: spawned.agentId, routing });
58      const low = routing.by === 'judge' && (routing.confidence ?? 0) < cfg.review;
59      await env.client.decide({
60        kind: 'routing',
61        repo,
62        issue,
63        title: `#${issue} routed to ${routing.tier} (${routing.model}/${routing.effort})${low ? ', low confidence' : ''}`,
64        body: [detail.title, routing.by === 'caller' ? 'tier named by the session' : `judge ${cfg.judge}, confidence ${(routing.confidence ?? 0).toFixed(2)}: ${routing.reason ?? ''}`, 'Answer with another tier to reroute.'].join('\n'),
65        options: cfg.tiers.map((t) => t.name),
66        blocking: false,
67        from: { session: env.session() },
68      });
69      lines.push(`${key} → ${routing.tier} ${routing.model}/${routing.effort}, agent ${spawned.agentId}${routing.reason ? `: ${routing.reason}` : ''}`);
70    } catch (e) {
71      lines.push(`${key}: ${(e as Error).message}`);
72    }
73  }
74  return lines.join('\n');
75}
76
77const ints = (v: unknown): number[] => (Array.isArray(v) ? v : [v]).map((x) => (typeof x === 'string' ? Number(x.replace('#', '')) : x)).filter((n): n is number => typeof n === 'number' && Number.isInteger(n) && n > 0);
78
79export function dispatchTool(): Tool<DispatchPort> {
80  return {
81    name: 'dispatch',
82    eager: true,
83    mainOnly: true,
84    description:
85      'Start an issue agent on each issue, the only way to start one. Claims the issue for this session, routes it to a tier of model and effort (the routing judge reads the issue unless you name a tier, and every pick is logged for the person to review or override), and spawns the agent in the background. The agent resumes an existing branch and PR when there is one. An issue a live agent still holds is refused, naming that agent: wait for it to end, message it, or release the issue first. Its progress arrives as work deliveries, and its final report arrives when it ends.',
86    inputSchema: {
87      type: 'object',
88      properties: {
89        issues: { type: 'array', items: { type: 'number' } },
90        repo: { type: 'string', description: 'owner/name; defaults to the session repository' },
91        tier: { type: 'string', description: 'a routing tier by name, skipping the judge' },
92        context: { type: 'string', description: 'what the agent should know beyond the issue: an answer to its question, a constraint, where to resume' },
93      },
94      required: ['issues'],
95    },
96    async run(env, input, _agent, port) {
97      const issues = ints(input.issues);
98      if (!issues.length) throw new HelmError(400, 'issues is required');
99      const repo = typeof input.repo === 'string' && input.repo ? input.repo : undefined;
100      if (repo !== undefined && !isRepoName(repo)) throw new HelmError(400, `repo ${repo} is not owner/name`);
101      return dispatchIssues(env, port, {
102        issues,
103        ...(repo ? { repo } : {}),
104        ...(typeof input.tier === 'string' && input.tier ? { tier: input.tier } : {}),
105        ...(typeof input.context === 'string' && input.context ? { context: input.context } : {}),
106      });
107    },
108  };
109}
110
src/mod/mailbox.ts 156 lines
1import { deliveryText } from '../core/letter.ts';
2import type { AgentStatus, Letter } from '../core/types.ts';
3
4export type Timer = { cancel: () => void };
5
6export type MailHost = {
7  now: () => number;
8  // claims a letter from helmd; undefined when another environment or session took it first
9  take: (id: string) => Promise<Letter | undefined>;
10  // a turn of the main loop's own; false when a hook dropped it, so no turn comes of it
11  submit: (text: string) => Promise<boolean>;
12  // undefined once the engine queued it, else why it refused
13  send: (agent: string, text: string) => Promise<string | undefined>;
14  // retires every subscription the agent owns, once nothing can reach it
15  retire: (agent: string) => Promise<void>;
16  // the agent as the engine lists it now; undefined when it is not listed
17  status: (agent: string) => Promise<AgentStatus | undefined>;
18  after: (ms: number, fn: () => Promise<void>) => Timer;
19  log: (line: string) => void;
20};
21
22// how long a letter waits for its agent's next tool call before it goes by message
23export const GRACE_MS = 60_000;
24
25const FINISHED: ReadonlySet<string> = new Set(['completed', 'failed', 'killed']);
26
27// where a letter lands. one for the main loop rides its next tool call while a turn runs; between turns, every letter
28// waiting goes as one prompt, which starts a turn. one for an agent rides that agent's next tool call; after the grace,
29// or at once when the agent has ended, it goes as a message, which resumes an ended agent. a message the engine refuses
30// goes to the main loop as a relay and the agent's subscriptions are retired. letters that go together are one text,
31// a work item's older phases folded into its newest. helmd hands each letter out once, so two environments never both
32// deliver it
33export class Mailbox {
34  private readonly waiting = new Map<string, Letter>();
35  private readonly timers = new Map<string, Timer>();
36  // a main-loop turn runs, or a prompt this mailbox submitted is on its way to one: either ends at turn.complete
37  private busy = false;
38  // main-loop turn events seen, so a submission can tell whether they took over the busy flag while it waited
39  private moves = 0;
40  private readonly host: MailHost;
41
42  constructor(host: MailHost) {
43    this.host = host;
44  }
45
46  async receive(l: Letter): Promise<void> {
47    if (this.waiting.has(l.id)) return;
48    this.waiting.set(l.id, l);
49    if (l.agent === undefined) return this.prompt();
50    const status = await this.host.status(l.agent);
51    if (status === undefined || FINISHED.has(status)) return this.flush(l.agent);
52    this.arm(l.agent, Math.max(0, l.at + GRACE_MS - this.host.now()));
53  }
54
55  // the text that rides a tool call's result, the calling loop's letters taken from helmd as they go
56  async attach(agent: string | undefined): Promise<string | undefined> {
57    const key = agent ?? '';
58    const mine = this.mine(key);
59    if (!mine.length) return undefined;
60    this.disarm(key);
61    const taken: Letter[] = [];
62    for (const l of mine) {
63      this.waiting.delete(l.id);
64      const t = await this.host.take(l.id);
65      if (t) taken.push(t);
66    }
67    return taken.length ? deliveryText(taken) : undefined;
68  }
69
70  turnStarted(): void {
71    this.busy = true;
72    this.moves++;
73  }
74
75  // a main-loop turn ended: what is still waiting starts the next one
76  async turnEnded(): Promise<void> {
77    this.busy = false;
78    this.moves++;
79    await this.prompt();
80  }
81
82  // an agent's loop ended: what waits for it goes now, as a message that resumes it
83  async agentEnded(agent: string): Promise<void> {
84    if (this.mine(agent).length) await this.flush(agent);
85  }
86
87  pending(): { to: string; count: number }[] {
88    const counts = new Map<string, number>();
89    for (const l of this.waiting.values()) counts.set(l.agent ?? 'main', (counts.get(l.agent ?? 'main') ?? 0) + 1);
90    return [...counts].map(([to, count]) => ({ to, count }));
91  }
92
93  stop(): void {
94    for (const t of this.timers.values()) t.cancel();
95    this.timers.clear();
96  }
97
98  private mine(key: string): Letter[] {
99    return [...this.waiting.values()].filter((l) => (l.agent ?? '') === key).sort((a, b) => a.at - b.at);
100  }
101
102  private arm(key: string, ms: number): void {
103    if (this.timers.has(key)) return;
104    this.timers.set(
105      key,
106      this.host.after(ms, async () => {
107        this.timers.delete(key);
108        await this.flush(key);
109      }),
110    );
111  }
112
113  private disarm(key: string): void {
114    this.timers.get(key)?.cancel();
115    this.timers.delete(key);
116  }
117
118  // the main loop's waiting letters as one prompt, unless a turn runs or one is on its way. the loop is busy from the
119  // first take, so a letter that lands meanwhile waits for that turn instead of making a prompt of its own
120  private async prompt(): Promise<void> {
121    while (!this.busy && this.mine('').length) {
122      this.busy = true;
123      const moves = this.moves;
124      const text = await this.attach(undefined);
125      if (text !== undefined) await this.submit(text, false);
126      else if (moves === this.moves) this.busy = false;
127    }
128  }
129
130  // a prompt holds the loop busy until its turn ends; one a hook dropped starts no turn, so the loop goes back to how
131  // it was, unless a turn started or ended meanwhile and the turn events hold the flag
132  private async submit(text: string, was: boolean): Promise<void> {
133    this.busy = true;
134    const moves = this.moves;
135    const entered = await this.host.submit(text);
136    if (entered) return;
137    this.host.log('helm: a prompt of letters was dropped by a hook');
138    if (moves === this.moves) this.busy = was;
139  }
140
141  private async flush(agent: string): Promise<void> {
142    const text = await this.attach(agent);
143    if (text === undefined) return;
144    let refused: string | undefined;
145    try {
146      refused = await this.host.send(agent, text);
147    } catch (e) {
148      refused = (e as Error).message;
149    }
150    if (refused === undefined) return;
151    this.host.log(`helm: a message to agent ${agent} was refused (${refused}); relayed to the main loop`);
152    await this.submit([`[helm relay] for agent ${agent}, which a message could not reach: ${refused}`, text].join('\n'), this.busy);
153    await this.host.retire(agent);
154  }
155}
156
src/mod/send.ts 21 lines
1import type { AgentRecord } from '../core/types.ts';
2
3type Listed = Pick<AgentRecord, 'id' | 'type' | 'parentId'> & { name?: string | undefined };
4
5// where an agent's SendMessage goes: through the engine as addressed, or to this session's main loop. the engine
6// resolves a name across every session on the machine, so an issue agent answering "the coordinator" its parent's
7// message speaks of reaches the session that carries that name, not its own. an issue agent, and any agent it
8// started, answers only to the session that dispatched it: a send of theirs that names no other agent of this
9// session goes to the main loop
10export function sendRoute(to: string, sender: string, agents: readonly Listed[], isIssue: (type: string) => boolean): 'engine' | 'session' {
11  const byId = new Map(agents.map((a) => [a.id, a]));
12  const seen = new Set<string>();
13  let a = byId.get(sender);
14  while (a && !isIssue(a.type) && a.parentId !== undefined && !seen.has(a.id)) {
15    seen.add(a.id);
16    a = byId.get(a.parentId);
17  }
18  if (!a || !isIssue(a.type)) return 'engine';
19  return agents.some((x) => x.id !== sender && (x.id === to || x.name === to)) ? 'engine' : 'session';
20}
21
src/mod/tools.ts 333 lines
1import { forPerson, forSession, isOpen, isRecord } from '../core/decision.ts';
2import { workKey } from '../core/protocol.ts';
3import { describeScope, parseScope } from '../core/scope.ts';
4import { findNode } from '../core/tree.ts';
5import type { CiFilter, Decision, ReportState, RepoName, Until } from '../core/types.ts';
6import type { HelmClient } from './client.ts';
7import { HelmError } from './client.ts';
8import { decisionLine, fleetBlock, forgeBlock, jobLines, localBlock, pullLine, sessionLine, subscriptionLine, treeBlock, workBlock } from './format.ts';
9
10export type ToolEnv = {
11  client: HelmClient;
12  session: () => string;
13  home?: string;
14  now: () => number;
15  // the repository a call is about: the one it names, else the session's
16  repo: (given: unknown) => RepoName;
17  pending: () => { to: string; count: number }[];
18  version: string;
19};
20
21// one tool the model calls as mcp__helm__<name>. H is what the hooks layer hands a tool that needs the engine
22export type Tool<H = unknown> = {
23  name: string;
24  description: string;
25  inputSchema: Record<string, unknown>;
26  // listed with its schema from the first turn, for the tools agents reach for unprompted
27  eager: boolean;
28  // only the main loop may call it
29  mainOnly?: boolean;
30  run: (env: ToolEnv, input: Record<string, unknown>, agent: string | undefined, host: H) => Promise<string>;
31};
32
33const repoProp = { type: 'string', description: 'owner/name; defaults to the session repository' };
34
35const str = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
36const int = (v: unknown): number | undefined => (typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : typeof v === 'string' && /^#?\d+$/.test(v) ? Number(v.replace('#', '')) : undefined);
37const ints = (v: unknown): number[] => (Array.isArray(v) ? v.map(int).filter((n): n is number => n !== undefined) : int(v) !== undefined ? [int(v)!] : []);
38
39function needInt(v: unknown, what: string): number {
40  const n = int(v);
41  if (n === undefined) throw new HelmError(400, `${what} must be a positive number`);
42  return n;
43}
44
45// the open decisions, those for this session first
46function inbox(decisions: readonly Decision[], self: string, now: number): string {
47  const open = decisions.filter(isOpen);
48  return [...open.filter((d) => forSession(d, self)), ...open.filter((d) => !forSession(d, self))].map((d) => decisionLine(d, now, self)).join('\n');
49}
50
51const STATES: readonly ReportState[] = ['working', 'waiting', 'blocked', 'ready', 'stopped', 'abandoned'];
52
53export const TOOLS: Tool[] = [
54  {
55    name: 'status',
56    eager: true,
57    description:
58      'helm status for this session: its role and repository, its work with phases (queued, working, draft, ci, failing, ready, blocked, stalled, parked, done), the decisions addressed to it and its own waiting on the person, its subscriptions, letters waiting for its agents, and the web page. Call it at session start.',
59    inputSchema: { type: 'object', properties: {} },
60    async run(env) {
61      const f = await env.client.fleet();
62      const me = f.sessions.find((s) => s.id === env.session());
63      const mine = f.work.filter((w) => w.owner === env.session());
64      const subs = f.subscriptions.filter((s) => s.session === env.session());
65      const forMe = f.decisions.filter((d) => forSession(d, env.session()));
66      const asked = f.decisions.filter((d) => forPerson(d) && (d.from?.session === env.session() || mine.some((w) => w.repo === d.repo && w.issue === d.issue)));
67      const health = await env.client.health();
68      return [
69        `helm ${env.version} · helmd ${health.version} · ${health.web ?? ''}`,
70        me ? sessionLine(me, f.at, env.session()) : `session ${env.session()} not registered`,
71        '',
72        'work:',
73        workBlock(mine.filter((w) => w.phase !== 'done'), env.home),
74        '',
75        `decisions for this session (${forMe.length}):`,
76        ...forMe.map((d) => decisionLine(d, f.at, env.session())),
77        ...(asked.length ? ['', `waiting on the person (${asked.length}):`, ...asked.map((d) => decisionLine(d, f.at, env.session()))] : []),
78        '',
79        'subscriptions:',
80        ...subs.map((s) => subscriptionLine(s, describeScope)),
81        ...env.pending().map((p) => `letters waiting for ${p.to}: ${p.count}`),
82      ].join('\n');
83    },
84  },
85  {
86    name: 'view',
87    eager: true,
88    description:
89      'Read forge and machine state from helm instead of running gh or git: work (this session, or fleet for every session), tree (epics and their sub-issues with progress rolled up, across repositories; number narrows it to one subtree), issues (open, optional label), issue (one, with body and comments), prs (open, with checks), pr (one, with its jobs live), runs (recent workflow runs), worktrees, branches, decisions, sessions. Answers from a shared cache that one poller per repository keeps fresh, so it costs no rate limit.',
90    inputSchema: {
91      type: 'object',
92      properties: {
93        what: { type: 'string', enum: ['work', 'fleet', 'tree', 'issues', 'issue', 'prs', 'pr', 'runs', 'worktrees', 'branches', 'decisions', 'sessions'] },
94        repo: repoProp,
95        number: { type: 'number', description: 'issue or pr number, for issue and pr' },
96        label: { type: 'string', description: 'issues: only those with this label' },
97      },
98      required: ['what'],
99    },
100    async run(env, input) {
101      const what = str(input.what) ?? 'work';
102      const now = env.now();
103      if (what === 'tree') {
104        const f = await env.client.fleet(true);
105        const n = int(input.number);
106        if (n === undefined) return treeBlock(input.repo ? f.tree.filter((t) => t.repo === env.repo(input.repo)) : f.tree);
107        const hit = findNode(f.tree, env.repo(input.repo), n);
108        if (!hit) return `${env.repo(input.repo)}#${n} is in no epic helm sees`;
109        return [...(hit.path.length ? [`under ${hit.path.map((p) => `${p.repo}#${p.number}`).join(' › ')}`] : []), treeBlock([hit.node])].join('\n');
110      }
111      if (what === 'work' || what === 'fleet' || what === 'decisions' || what === 'sessions') {
112        const f = await env.client.fleet();
113        if (what === 'fleet') return fleetBlock(f, env.session(), env.home);
114        if (what === 'work') return workBlock(f.work.filter((w) => w.owner === env.session() && w.phase !== 'done'), env.home);
115        if (what === 'sessions') return f.sessions.map((s) => sessionLine(s, now, env.session())).join('\n') || 'no sessions';
116        return inbox(f.decisions, env.session(), now) || 'no open decisions';
117      }
118      const repo = env.repo(input.repo);
119      if (what === 'issue') {
120        const i = await env.client.issue(repo, needInt(input.number, 'number'));
121        return [`${i.pr ? 'pr' : 'issue'} ${repo}#${i.number} [${i.state}] ${i.title}`, `by ${i.author} · ${i.labels.join(', ') || 'no labels'} · ${i.url}`, '', i.body || '(no body)', ...i.comments.flatMap((c) => ['', `--- ${c.author} ${c.at}`, c.body])].join('\n');
122      }
123      const view = await env.client.repo(repo);
124      if (what === 'pr') {
125        const n = needInt(input.number, 'number');
126        const p = view.forge?.pulls.find((x) => x.number === n);
127        if (!p) return `pr #${n} is not among ${repo}'s open or recently closed pull requests`;
128        const runs = new Set(p.checks.map((c) => c.run));
129        const jobs = (view.forge?.runs ?? []).filter((r) => runs.has(r.id)).flatMap((r) => r.jobs ?? []);
130        return [pullLine(p), p.url, ...jobLines(jobs).map((l) => `  ${l}`), ...(p.lastReview ? [`last review ${p.lastReview.state} by ${p.lastReview.author.login}: ${p.lastReview.text}`] : []), ...(p.lastComment ? [`last comment by ${p.lastComment.author.login}: ${p.lastComment.text}`] : [])].join('\n');
131      }
132      const polled = view.polling.lastPoll ? `polled ${Math.round((now - view.polling.lastPoll) / 1000)}s ago${view.polling.error ? `, last error: ${view.polling.error}` : ''}` : 'not polled yet';
133      if (what === 'issues' || what === 'prs' || what === 'runs') return `${repo} ${what} (${polled})\n${forgeBlock(what, view.forge, now, str(input.label))}`;
134      if (what === 'worktrees' || what === 'branches') return localBlock(what, view.local, now, env.home);
135      throw new HelmError(400, `unknown view ${what}`);
136    },
137  },
138  {
139    name: 'log',
140    eager: false,
141    description:
142      'A CI job log, trimmed: by default the error lines with what led up to them. Name a job, or a run to read every failed job of it. GitHub serves a log only once its job completes; a running job shows its live steps in view pr.',
143    inputSchema: {
144      type: 'object',
145      properties: {
146        repo: repoProp,
147        run: { type: 'number', description: 'a workflow run id: reads the log of each of its failed jobs' },
148        job: { type: 'number', description: 'one job id' },
149        grep: { type: 'string', description: 'only lines matching this regular expression' },
150        tail: { type: 'number', description: 'the last n lines instead of the errors' },
151        errors: { type: 'boolean', description: 'error lines with context (default true unless grep or tail is given)' },
152      },
153    },
154    async run(env, input) {
155      const repo = env.repo(input.repo);
156      const tail = int(input.tail);
157      const grep = str(input.grep);
158      const errors = typeof input.errors === 'boolean' ? input.errors : !grep && !tail;
159      const q = { ...(tail ? { tail } : {}), ...(grep ? { grep } : {}), errors };
160      const job = int(input.job);
161      if (job) return env.client.log(repo, job, q);
162      const runId = needInt(input.run, 'run or job');
163      const view = await env.client.repo(repo);
164      const jobs = view.forge?.runs.find((r) => r.id === runId)?.jobs ?? [];
165      const failed = jobs.filter((j) => j.state === 'failure' || j.state === 'cancelled');
166      if (!failed.length) return jobs.length ? `run ${runId} has no failed job: ${jobLines(jobs).join('; ')}` : `run ${runId} is not among ${repo}'s recent runs, or its jobs are not read yet; pass a job id`;
167      const out: string[] = [];
168      for (const j of failed.slice(0, 4)) out.push(`=== ${j.name} (job ${j.id}) ${j.url}`, await env.client.log(repo, j.id, q).catch((e: Error) => e.message));
169      if (failed.length > 4) out.push(`… ${failed.length - 4} more failed jobs: ${failed.slice(4).map((j) => `${j.name} (${j.id})`).join(', ')}`);
170      return out.join('\n');
171    },
172  },
173  {
174    name: 'watch',
175    eager: true,
176    description:
177      'Subscribe to repository events, delivered to you as they happen instead of polling. subscribe: scope is repo, issue <n>, pr <n>, branch <name>, run <id> or tag <glob>; ci is settled (every verdict), failures, all or none; until settled, merged, closed or an ISO time removes it once reached. A subagent that subscribes owns the subscription: the delivery rides its next tool call, or after 60 s, or once it has ended its turn, arrives as a message that resumes it. So subscribe, then carry on or end your turn: never sleep or poll. To wait for CI on your PR: subscribe with scope "pr <n>", ci "settled", until "settled", and sha set to the head you pushed. unsubscribe takes the id; list shows this session\'s.',
178    inputSchema: {
179      type: 'object',
180      properties: {
181        action: { type: 'string', enum: ['subscribe', 'unsubscribe', 'list'] },
182        repo: repoProp,
183        scope: { type: 'string', description: 'repo (default), issue <n>, pr <n>, branch <name>, run <id>, tag <glob>, work or fleet' },
184        ci: { type: 'string', enum: ['settled', 'failures', 'all', 'none'] },
185        until: { type: 'string', description: 'settled, merged, closed or an ISO time' },
186        sha: { type: 'string', description: 'pr scope: the head you pushed, so a verdict on an older head is not taken for yours' },
187        tags: { type: 'array', items: { type: 'string' }, description: 'item events to take: opened, closed, reopened, merged, ready, draft, comment, review, pushed, edited, labeled, unowned' },
188        bots: { type: 'boolean', description: 'take events from bot accounts too' },
189        id: { type: 'string', description: 'unsubscribe: the subscription id' },
190      },
191      required: ['action'],
192    },
193    async run(env, input, agent) {
194      const action = str(input.action);
195      if (action === 'list') {
196        const f = await env.client.fleet();
197        return f.subscriptions.filter((s) => s.session === env.session()).map((s) => subscriptionLine(s, describeScope)).join('\n') || 'no subscriptions';
198      }
199      if (action === 'unsubscribe') return (await env.client.unsubscribe(str(input.id) ?? '')).removed ? `removed ${String(input.id)}` : `no subscription ${String(input.id)}`;
200      if (action !== 'subscribe') throw new HelmError(400, 'action is subscribe, unsubscribe or list');
201      const scope = parseScope(str(input.scope));
202      const spans = scope.kind === 'work' || scope.kind === 'fleet';
203      const untilText = str(input.until);
204      const until: Until | undefined = untilText === undefined ? undefined : untilText === 'settled' || untilText === 'merged' || untilText === 'closed' ? untilText : Number.isNaN(Date.parse(untilText)) ? undefined : { at: new Date(Date.parse(untilText)).toISOString() };
205      if (untilText !== undefined && until === undefined) throw new HelmError(400, `until ${untilText} is not settled, merged, closed or a time`);
206      const sub = await env.client.subscribe({
207        session: env.session(),
208        scope,
209        ...(spans ? {} : { repo: env.repo(input.repo) }),
210        ...(str(input.ci) ? { ci: str(input.ci) as CiFilter } : {}),
211        ...(Array.isArray(input.tags) ? { tags: input.tags.map(String) } : {}),
212        ...(typeof input.bots === 'boolean' ? { bots: input.bots } : {}),
213        ...(until ? { until } : {}),
214        ...(str(input.sha) ? { sha: str(input.sha)! } : {}),
215        ...(agent ? { agent } : {}),
216      });
217      const who = agent ? `for this agent (${agent}). A delivery arrives with the result of your next tool call; if you make none within 60 s or have ended your turn, it arrives as a message that resumes you. Do not wait or poll: carry on, or end your turn.` : 'for the main loop. Deliveries arrive as prompts, or with the next tool result while a turn runs.';
218      return `${subscriptionLine(sub, describeScope)}\nsubscribed ${who}`;
219    },
220  },
221  {
222    name: 'report',
223    eager: true,
224    description:
225      'Tell helm where your work on an issue stands, so the person and the session that owns it can track it. Call it with working when you start an issue (this claims it for you), waiting when you end your turn to wait for CI, ready when the PR is ready and green, blocked with a question when you cannot continue without a decision (a question from an agent goes to the session that owns the work, which answers it or escalates it to the person, and one from a session itself goes to the person; the answer resumes you), stopped when you stop for any other reason (this parks the work, and nothing helm delivers resumes you until the issue is dispatched again or your session messages you), abandoned when told to. choices lists decisions you made that the issue did not settle: records for the person to review, which need no answer. plan is your plan as it stands, every step with whether it is done: send it whole each time it changes, so the person sees your progress.',
226    inputSchema: {
227      type: 'object',
228      properties: {
229        issue: { type: 'number' },
230        repo: repoProp,
231        state: { type: 'string', enum: STATES },
232        note: { type: 'string', description: 'one line on where it stands' },
233        question: {
234          type: 'object',
235          properties: { title: { type: 'string' }, body: { type: 'string', description: 'what you found, the options and what you would do' }, options: { type: 'array', items: { type: 'string' } } },
236          required: ['title', 'body'],
237        },
238        choices: { type: 'array', items: { type: 'object', properties: { title: { type: 'string' }, body: { type: 'string' } }, required: ['title', 'body'] } },
239        plan: {
240          type: 'array',
241          description: 'the whole plan, in order, each step one short line',
242          items: { type: 'object', properties: { text: { type: 'string' }, done: { type: 'boolean' } }, required: ['text', 'done'] },
243        },
244      },
245      required: ['issue', 'state'],
246    },
247    async run(env, input, agent) {
248      const repo = env.repo(input.repo);
249      const issue = needInt(input.issue, 'issue');
250      const state = str(input.state) as ReportState;
251      if (!STATES.includes(state)) throw new HelmError(400, `state is one of ${STATES.join(', ')}`);
252      if (state === 'blocked' && !input.question) throw new HelmError(400, 'blocked needs a question: what decision you need, with the options');
253      // a report from an agent claims the issue for it; the session's own report claims it for the session
254      if (state === 'working') await env.client.claim({ session: env.session(), repo, issue, ...(agent ? { agent } : {}) });
255      const q = input.question as { title?: unknown; body?: unknown; options?: unknown } | undefined;
256      const choices = Array.isArray(input.choices) ? (input.choices as { title?: unknown; body?: unknown }[]) : [];
257      const plan = Array.isArray(input.plan) ? (input.plan as { text?: unknown; done?: unknown }[]).map((p) => ({ text: String(p.text ?? ''), done: p.done === true })).filter((p) => p.text) : undefined;
258      const out = await env.client.report({
259        session: env.session(),
260        repo,
261        issue,
262        state,
263        ...(agent ? { agent } : {}),
264        ...(str(input.note) ? { note: str(input.note)! } : {}),
265        ...(q ? { question: { title: String(q.title ?? ''), body: String(q.body ?? ''), ...(Array.isArray(q.options) ? { options: q.options.map(String) } : {}) } } : {}),
266        ...(choices.length ? { choices: choices.map((c) => ({ title: String(c.title ?? ''), body: String(c.body ?? '') })) } : {}),
267        ...(plan ? { plan } : {}),
268      });
269      const asked = out.decisions.filter((d) => d.blocking);
270      return [
271        `${workKey(repo, issue)} reported ${state}`,
272        ...out.decisions.map((d) => (isRecord(d) ? `recorded ${d.id} for review (${d.kind}): ${d.title}` : `asked ${d.id} of ${d.to === 'person' ? 'the person' : `session ${d.session}`}: ${d.title}`)),
273        ...(asked.length ? ['End your turn now. The answer arrives as a message that resumes you.'] : []),
274      ].join('\n');
275    },
276  },
277  {
278    name: 'backlog',
279    eager: false,
280    mainOnly: true,
281    description: "This session's backlog of issues, kept in helm so the person sees what the session owns. list, add (issues, queued in order), remove (released), order (issues in the order to work them).",
282    inputSchema: {
283      type: 'object',
284      properties: { action: { type: 'string', enum: ['list', 'add', 'remove', 'order'] }, repo: repoProp, issues: { type: 'array', items: { type: 'number' } } },
285      required: ['action'],
286    },
287    async run(env, input) {
288      const action = str(input.action);
289      const issues = ints(input.issues);
290      if (action === 'list') {
291        const f = await env.client.fleet();
292        return workBlock(f.work.filter((w) => w.owner === env.session() && w.phase !== 'done'), env.home);
293      }
294      if (!issues.length) throw new HelmError(400, 'issues is required');
295      const repo = env.repo(input.repo);
296      if (action === 'add') return (await env.client.queue({ session: env.session(), repo, issues })).map((w) => `queued ${workKey(w.repo, w.issue)} ${w.title}`).join('\n');
297      if (action === 'remove') {
298        for (const issue of issues) await env.client.release({ session: env.session(), repo, issue });
299        return `released ${issues.map((n) => `#${n}`).join(' ')}`;
300      }
301      if (action === 'order') {
302        await env.client.order({ session: env.session(), keys: issues.map((n) => workKey(repo, n)) });
303        return `ordered ${issues.map((n) => `#${n}`).join(' ')}`;
304      }
305      throw new HelmError(400, 'action is list, add, remove or order');
306    },
307  },
308  {
309    name: 'decide',
310    eager: false,
311    description: 'The decision inbox. list shows the open decisions, each with who it is for: those for this session first (its agents\' questions and its stalls), then the person\'s and other sessions\'. answer one (text and, where it has options, an option; a routing record takes a tier name to reroute), escalate one addressed to this session to the person when its answer is not within this session\'s authority (text is an optional note), or dismiss one. The answer goes to the agent or session waiting on it. Choices and routing picks are records for the person to review, not decisions.',
312    inputSchema: {
313      type: 'object',
314      properties: { action: { type: 'string', enum: ['list', 'answer', 'escalate', 'dismiss'] }, id: { type: 'string' }, text: { type: 'string' }, option: { type: 'string' } },
315      required: ['action'],
316    },
317    async run(env, input) {
318      const action = str(input.action);
319      const id = str(input.id);
320      if (action === 'list') {
321        const f = await env.client.fleet();
322        return inbox(f.decisions, env.session(), f.at) || 'no open decisions';
323      }
324      if (!id) throw new HelmError(400, 'id is required');
325      if (action === 'dismiss') return `dismissed ${(await env.client.dismiss(id)).id}`;
326      if (action === 'escalate') return `escalated ${(await env.client.escalate(id, { by: `session ${env.session()}`, ...(str(input.text) ? { note: str(input.text)! } : {}) })).id} to the person`;
327      if (action !== 'answer') throw new HelmError(400, 'action is list, answer, escalate or dismiss');
328      const out = await env.client.answer(id, { text: str(input.text) ?? '', ...(str(input.option) ? { option: str(input.option)! } : {}), by: `session ${env.session()}` });
329      return `answered ${out.decision.id}${out.delivered ? ', delivered' : ', but nobody live was waiting on it'}`;
330    },
331  },
332];
333
src/mod/view.ts 324 lines
1import { isDone, isPassing } from '../core/checks.ts';
2import { forPerson, forSession } from '../core/decision.ts';
3import { percent } from '../core/tree.ts';
4import type { Decision, Fleet, Job, Phase, Rollup, Run, SessionRole, TreeNode, WorkView } from '../core/types.ts';
5import { selfWorked } from '../core/work.ts';
6import { ago, unattendedLine } from './format.ts';
7
8// what a surface draws: rows of styled segments, so the drawing is plain data the hooks module maps onto elements.
9// a segment with press is a control: its press is the address the hooks module routes, its hotkey one key
10export type Seg = { text: string; color?: string; dim?: boolean; bold?: boolean; press?: string; hotkey?: string; boxed?: boolean };
11export type Row = Seg[];
12
13export type Self = { session: string; role: SessionRole; repo?: string };
14
15export type Tab = 'work' | 'epics' | 'ci' | 'inbox';
16export const TABS: readonly { id: Tab; label: string; hotkey: string }[] = [
17  { id: 'work', label: 'Work', hotkey: '1' },
18  { id: 'epics', label: 'Epics', hotkey: '2' },
19  { id: 'ci', label: 'CI', hotkey: '3' },
20  { id: 'inbox', label: 'Inbox', hotkey: '4' },
21];
22export const isTab = (t: unknown): t is Tab => TABS.some((x) => x.id === t);
23
24export type PaneOpts = { rows: number; cols: number; tab: Tab; web?: string };
25
26const PHASE_COLOR: Record<Phase, string> = {
27  queued: 'inactive',
28  working: 'claude',
29  draft: 'claude',
30  ci: 'warning',
31  failing: 'error',
32  ready: 'suggestion',
33  blocked: 'error',
34  stalled: 'warning',
35  parked: 'planMode',
36  done: 'success',
37};
38
39const PHASE_GLYPH: Record<Phase, string> = { queued: '○', working: '●', draft: '◐', ci: '◔', ready: '◆', failing: '✗', blocked: '■', stalled: '◌', parked: '‖', done: '✓' };
40
41// the order work is listed in: what needs someone first, then what moves, then what waits
42const PHASE_RANK: Record<Phase, number> = { blocked: 0, failing: 1, stalled: 2, ready: 3, ci: 4, draft: 5, working: 6, queued: 7, parked: 8, done: 9 };
43const byRank = (a: WorkView, b: WorkView) => PHASE_RANK[a.phase] - PHASE_RANK[b.phase] || a.order - b.order;
44
45const short = (model: string) => model.replace(/^claude-/, '').replace(/-(\d+)-(\d+)$/, ' $1.$2');
46const repoShort = (r: string) => r.split('/')[1] ?? r;
47const clamp = (n: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, n));
48
49// decisions are the open ones in scope
50export function counts(work: readonly WorkView[], decisions: readonly Decision[]) {
51  const open = work.filter((w) => w.phase !== 'done');
52  return {
53    active: open.filter((w) => w.phase !== 'queued' && w.phase !== 'parked').length,
54    queued: open.filter((w) => w.phase === 'queued').length,
55    parked: open.filter((w) => w.phase === 'parked').length,
56    ci: open.filter((w) => w.phase === 'ci').length,
57    attention: open.filter((w) => w.phase === 'blocked' || w.phase === 'failing' || w.phase === 'stalled').length,
58    waiting: decisions.filter((d) => d.blocking).length,
59    open: decisions.filter((d) => !d.blocking).length,
60  };
61}
62
63function summary(c: ReturnType<typeof counts>): Row {
64  const row: Row = [{ text: `${c.active} active`, bold: true }];
65  if (c.queued) row.push({ text: ` · ${c.queued} queued`, dim: true });
66  if (c.parked) row.push({ text: ` · ${c.parked} parked`, dim: true });
67  if (c.ci) row.push({ text: ` · ${c.ci} in ci`, color: 'warning' });
68  if (c.attention) row.push({ text: ` · ${c.attention} need attention`, color: 'error' });
69  if (c.waiting) row.push({ text: ` · ${c.waiting} waiting on a decision`, color: 'error', bold: true });
70  if (c.open) row.push({ text: ` · ${c.open} to decide`, dim: true });
71  return row;
72}
73
74// what this session sees: its own work and the decisions addressed to it, or for a coordinator all work and the
75// person's decisions besides its own
76function scope(f: Fleet, self: Self) {
77  const fleet = self.role === 'coordinator';
78  const work = f.work.filter((w) => w.phase !== 'done' && (fleet || w.owner === self.session));
79  const decisions = f.decisions.filter((d) => forSession(d, self.session) || (fleet && forPerson(d)));
80  const repos = fleet ? Object.keys(f.repos) : [...new Set([...(self.repo ? [self.repo] : []), ...work.map((w) => w.repo)])];
81  return { fleet, work, decisions, repos };
82}
83
84// a bar of parts over a total, `width` cells: each part with any count gets at least one cell, the rest is track
85export function bar(parts: readonly { n: number; color: string }[], total: number, width: number): Seg[] {
86  if (total <= 0 || width <= 0) return [{ text: '─'.repeat(Math.max(0, width)), dim: true }];
87  const shown = parts.filter((p) => p.n > 0);
88  const exact = shown.map((p) => (p.n / total) * width);
89  const cells = exact.map((x) => Math.max(1, Math.floor(x)));
90  let left = Math.round((shown.reduce((a, p) => a + p.n, 0) / total) * width) - cells.reduce((a, b) => a + b, 0);
91  const order = exact.map((x, i) => ({ i, r: x - Math.floor(x) })).sort((a, b) => b.r - a.r);
92  for (let k = 0; left > 0 && k < order.length; k++, left--) cells[order[k]!.i]!++;
93  while (cells.reduce((a, b) => a + b, 0) > width) {
94    const i = cells.indexOf(Math.max(...cells));
95    cells[i]!--;
96  }
97  const out: Seg[] = shown.map((p, i) => ({ text: '━'.repeat(cells[i]!), color: p.color }));
98  const used = cells.reduce((a, b) => a + b, 0);
99  if (used < width) out.push({ text: '─'.repeat(width - used), dim: true });
100  return out;
101}
102
103export function meter(done: number, total: number, width: number, color = 'success'): Seg[] {
104  const on = total ? Math.round((done / total) * width) : 0;
105  return [
106    { text: '▰'.repeat(on), color },
107    { text: '▱'.repeat(width - on), dim: true },
108  ];
109}
110
111export function rollupParts(r: Rollup): { n: number; color: string }[] {
112  return [
113    { n: r.done, color: 'success' },
114    { n: r.ready, color: 'suggestion' },
115    { n: r.ci, color: 'warning' },
116    { n: Math.max(0, r.active - r.ci - r.ready), color: 'claude' },
117    { n: r.attention, color: 'error' },
118    { n: r.queued, color: 'inactive' },
119    { n: r.parked, color: PHASE_COLOR.parked },
120  ];
121}
122
123function tabRow(f: Fleet, self: Self, tab: Tab): Row {
124  const s = scope(f, self);
125  const runs = s.repos.flatMap((r) => f.repos[r]?.runs ?? []);
126  const badge: Record<Tab, string> = {
127    work: s.work.length ? ` ${s.work.length}` : '',
128    epics: '',
129    ci: runs.some((r) => !isDone(r.state)) ? ` ${runs.filter((r) => !isDone(r.state)).length}` : '',
130    inbox: s.decisions.length ? ` ${s.decisions.length}` : '',
131  };
132  const row: Row = [];
133  for (const t of TABS) {
134    if (row.length) row.push({ text: '  ' });
135    row.push({ text: `${t.label}${badge[t.id]}`, press: `tab:${t.id}`, hotkey: t.hotkey, bold: t.id === tab, ...(t.id === tab ? { color: 'claude' } : t.id === 'inbox' && s.decisions.some((d) => d.blocking) ? { color: 'error' } : {}) });
136  }
137  return row;
138}
139
140function workRows(w: WorkView, o: { cols: number; fleet: boolean; now: number }): Row[] {
141  const wide = o.cols >= 56;
142  const head: Row = [
143    { text: `${PHASE_GLYPH[w.phase]} `, color: PHASE_COLOR[w.phase] },
144    { text: `${w.phase.padEnd(8)}`, color: PHASE_COLOR[w.phase], bold: w.phase === 'blocked' || w.phase === 'failing' },
145    { text: `${o.fleet ? repoShort(w.repo) : ''}#${w.issue} `, bold: true },
146    { text: w.title },
147  ];
148  const at = w.history?.at(-1)?.at ?? w.updatedAt;
149  if (wide) head.push({ text: ` · ${ago(at, o.now)}`, dim: true });
150  const rows: Row[] = [head];
151  const pad = { text: '  ' };
152  const steps = w.plan ?? [];
153  if (steps.length) {
154    const done = steps.filter((s) => s.done).length;
155    const next = steps.find((s) => !s.done);
156    rows.push([pad, ...meter(done, steps.length, clamp(steps.length, 4, 10)), { text: ` ${done}/${steps.length}`, dim: true }, ...(next ? [{ text: ` next: ${next.text}` }] : [])]);
157  } else if (w.report?.note) rows.push([pad, { text: w.report.note, dim: true }]);
158  if (w.checks.length) {
159    const ok = w.checks.filter((c) => isDone(c.state) && isPassing(c.state)).length;
160    const bad = w.checks.filter((c) => isDone(c.state) && !isPassing(c.state));
161    const run = w.checks.filter((c) => c.state === 'running').length;
162    const row: Row = [pad, { text: 'ci ', dim: true }, ...bar([{ n: ok, color: 'success' }, { n: bad.length, color: 'error' }, { n: run, color: 'warning' }], w.checks.length, 8), { text: ` ${ok}/${w.checks.length}`, dim: true }];
163    if (bad.length) row.push({ text: ` ✗ ${bad.map((c) => c.name).join(', ')}`, color: 'error' });
164    else {
165      const live = runningStep(w.jobs);
166      if (live) row.push({ text: ` ▸ ${live}`, dim: true });
167    }
168    rows.push(row);
169  }
170  for (const p of w.leftovers ?? []) rows.push([pad, { text: `left running pid ${p.pid} `, color: 'warning' }, { text: p.command, dim: true }]);
171  if (wide) {
172    const meta = [w.agent ? `agent ${w.agentStatus ?? '?'}` : selfWorked(w) ? 'its session' : 'no agent', w.routing ? `${w.routing.tier ?? ''} ${short(w.routing.model)}/${w.routing.effort}`.trim() : '', w.pull ? `pr #${w.pull.number}${w.pull.draft ? ' draft' : ''}` : '', w.decisions ? `${w.decisions} decision${w.decisions === 1 ? '' : 's'}` : ''].filter(Boolean);
173    rows.push([pad, { text: meta.join(' · '), dim: true }]);
174  }
175  return rows;
176}
177
178function runningStep(jobs: readonly Job[]): string | undefined {
179  for (const j of jobs) {
180    if (isDone(j.state)) continue;
181    const on = j.steps.find((s) => s.state === 'running');
182    const n = j.steps.filter((s) => isDone(s.state)).length;
183    return `${j.name}${j.steps.length ? ` ${n + (on ? 1 : 0)}/${j.steps.length}` : ''}${on ? ` ${on.name}` : ''}`;
184  }
185  return undefined;
186}
187
188function workTab(f: Fleet, self: Self, o: PaneOpts): Row[] {
189  const s = scope(f, self);
190  const rows: Row[] = [summary(counts(s.work, s.decisions))];
191  const width = clamp(o.cols - 4, 12, 48);
192  if (s.work.length) {
193    const phases: Phase[] = ['ready', 'ci', 'working', 'draft', 'failing', 'blocked', 'stalled', 'queued', 'parked'];
194    rows.push(bar(phases.map((p) => ({ n: s.work.filter((w) => w.phase === p).length, color: PHASE_COLOR[p] })), s.work.length, width));
195  }
196  const fmt = { cols: o.cols, fleet: s.fleet, now: f.at };
197  if (s.fleet) {
198    if (f.unattended.length) rows.push([], ...f.unattended.map((u): Row => [{ text: unattendedLine(u, f.at), color: 'warning' }]));
199    const live = f.sessions.filter((x) => !x.gone);
200    for (const x of live) {
201      const mine = s.work.filter((w) => w.owner === x.id).sort(byRank);
202      if (!mine.length) continue;
203      rows.push([], [{ text: x.repo ? repoShort(x.repo) : (x.title ?? x.id.slice(0, 8)), bold: true }, { text: ` ${x.role}${x.id === self.session ? ' (this session)' : ''} · ${x.agents.filter((a) => a.status === 'running').length} agents running`, dim: true }]);
204      for (const w of mine) rows.push(...workRows(w, fmt));
205    }
206    const orphans = s.work.filter((w) => !live.some((x) => x.id === w.owner)).sort(byRank);
207    if (orphans.length) {
208      rows.push([], [{ text: 'no live session', color: 'warning', bold: true }]);
209      for (const w of orphans) rows.push(...workRows(w, fmt));
210    }
211  } else {
212    if (!s.work.length) rows.push([], [{ text: 'nothing queued or active. queue issues with backlog, start them with dispatch.', dim: true }]);
213    for (const w of [...s.work].sort(byRank)) rows.push([], ...workRows(w, fmt));
214  }
215  return rows;
216}
217
218// the subtree's leaves that someone is on, what moves under an epic
219function moving(n: TreeNode): TreeNode[] {
220  if (!n.children.length) return n.phase && n.phase !== 'done' && n.phase !== 'parked' ? [n] : [];
221  return n.children.flatMap(moving);
222}
223
224function epicsTab(f: Fleet, self: Self, o: PaneOpts): Row[] {
225  const s = scope(f, self);
226  const touches = (n: TreeNode): boolean => s.repos.includes(n.repo) || n.children.some(touches);
227  const roots = f.tree.filter((t) => t.state === 'open' && (s.fleet || touches(t)));
228  if (!roots.length) return [[{ text: 'no epics here. an open issue with sub-issues is one.', dim: true }]];
229  const width = clamp(o.cols - 12, 10, 40);
230  const rows: Row[] = [];
231  const sorted = [...roots].sort((a, b) => b.rollup.active + b.rollup.attention - (a.rollup.active + a.rollup.attention) || percent(a.rollup) - percent(b.rollup));
232  for (const t of sorted) {
233    const r = t.rollup;
234    if (rows.length) rows.push([]);
235    rows.push([{ text: `${String(percent(r)).padStart(3)}% `, bold: true }, { text: `${repoShort(t.repo)}#${t.number} `, dim: true }, { text: t.title.replace(/^epic:\s*/i, ''), bold: true }]);
236    rows.push([{ text: '     ' }, ...bar(rollupParts(r), r.total, width), { text: ` ${r.done}/${r.total}`, dim: true }]);
237    const notes = [r.active ? `${r.active} active` : '', r.ci ? `${r.ci} in ci` : '', r.ready ? `${r.ready} ready` : '', r.queued ? `${r.queued} queued` : '', r.parked ? `${r.parked} parked` : '', r.unowned ? `${r.unowned} unowned` : ''].filter(Boolean);
238    if (r.attention) rows.push([{ text: '     ' }, { text: `${r.attention} need attention`, color: 'error' }, ...(notes.length ? [{ text: ` · ${notes.join(' · ')}`, dim: true }] : [])]);
239    else if (notes.length) rows.push([{ text: '     ' }, { text: notes.join(' · '), dim: true }]);
240    for (const n of moving(t).sort((a, b) => PHASE_RANK[a.phase!] - PHASE_RANK[b.phase!]).slice(0, 4)) {
241      rows.push([{ text: '     ' }, { text: `${PHASE_GLYPH[n.phase!]} `, color: PHASE_COLOR[n.phase!] }, { text: `${n.repo === t.repo ? '' : repoShort(n.repo)}#${n.number} `, bold: true }, { text: n.title }, ...(n.plan ? [{ text: ` ${n.plan.done}/${n.plan.total}`, dim: true }] : [])]);
242    }
243  }
244  return rows;
245}
246
247function runRows(repo: string, r: Run, o: { cols: number; now: number; many: boolean }): Row[] {
248  const live = !isDone(r.state);
249  const glyph = live ? '◔' : isPassing(r.state) ? '✓' : '✗';
250  const color = live ? 'warning' : isPassing(r.state) ? 'success' : 'error';
251  const head: Row = [{ text: `${glyph} `, color }, { text: r.workflow, bold: true }, { text: ` ${o.many ? `${repoShort(repo)} ` : ''}${r.tag ? 'tag ' : ''}${r.branch} · ${live ? 'started' : r.state} ${ago(Date.parse(live ? r.createdAt : r.updatedAt), o.now)} ago`, dim: true }];
252  const rows: Row[] = [head];
253  const jobs = r.jobs ?? [];
254  if (!jobs.length) return rows;
255  const ok = jobs.filter((j) => isDone(j.state) && isPassing(j.state)).length;
256  const bad = jobs.filter((j) => isDone(j.state) && !isPassing(j.state));
257  const run = jobs.filter((j) => j.state === 'running');
258  if (live) rows.push([{ text: '  ' }, ...bar([{ n: ok, color: 'success' }, { n: bad.length, color: 'error' }, { n: run.length, color: 'warning' }], jobs.length, clamp(o.cols - 18, 8, 32)), { text: ` ${ok + bad.length}/${jobs.length} jobs`, dim: true }]);
259  for (const j of run.slice(0, 3)) {
260    const on = j.steps.find((s) => s.state === 'running');
261    const n = j.steps.filter((s) => isDone(s.state)).length;
262    rows.push([{ text: '  ▸ ', color: 'warning' }, { text: j.name }, ...(j.steps.length ? [{ text: ` ${n + (on ? 1 : 0)}/${j.steps.length}`, dim: true }] : []), ...(on ? [{ text: ` ${on.name}`, dim: true }] : [])]);
263  }
264  for (const j of bad.slice(0, 3)) rows.push([{ text: '  ✗ ', color: 'error' }, { text: j.name }, { text: ` job ${j.id}`, dim: true }]);
265  return rows;
266}
267
268function ciTab(f: Fleet, self: Self, o: PaneOpts): Row[] {
269  const s = scope(f, self);
270  const runs = s.repos.flatMap((repo) => (f.repos[repo]?.runs ?? []).map((r) => ({ repo, r }))).sort((a, b) => Number(isDone(a.r.state)) - Number(isDone(b.r.state)) || Date.parse(b.r.createdAt) - Date.parse(a.r.createdAt));
271  if (!runs.length) return [[{ text: 'no run in flight or finished in the last half hour.', dim: true }]];
272  const live = runs.filter((x) => !isDone(x.r.state)).length;
273  const failed = runs.filter((x) => isDone(x.r.state) && !isPassing(x.r.state)).length;
274  const rows: Row[] = [[{ text: `${live} in flight`, bold: true }, ...(failed ? [{ text: ` · ${failed} failed`, color: 'error' }] : []), { text: ` · ${runs.length - live - failed} passed lately`, dim: true }]];
275  const fmt = { cols: o.cols, now: f.at, many: s.repos.length > 1 };
276  for (const { repo, r } of runs) rows.push([], ...runRows(repo, r, fmt));
277  return rows;
278}
279
280function inboxTab(f: Fleet, self: Self, o: PaneOpts): Row[] {
281  const s = scope(f, self);
282  if (!s.decisions.length) return [[{ text: s.fleet ? 'nothing waits on you or this session.' : 'nothing is addressed to this session.', dim: true }]];
283  const rows: Row[] = [];
284  const sorted = [...s.decisions].sort((a, b) => Number(b.blocking) - Number(a.blocking) || b.createdAt - a.createdAt);
285  for (const d of sorted) {
286    if (rows.length) rows.push([]);
287    rows.push([{ text: `${d.blocking ? 'waiting' : d.kind}`.padEnd(9), color: d.blocking ? 'error' : 'inactive', bold: d.blocking }, { text: d.repo ? `${repoShort(d.repo)}${d.issue !== undefined ? `#${d.issue}` : ''} ` : '', bold: true }, { text: d.title }, { text: ` · ${ago(d.createdAt, f.at)}`, dim: true }]);
288    const first = d.body.split('\n').find((l) => l.trim());
289    if (first) rows.push([{ text: '         ' }, { text: first, dim: true }]);
290    const controls: Row = [{ text: '         ' }];
291    for (const [i, option] of (d.options ?? []).entries()) controls.push({ text: option, press: `answer:${d.id}:${i}`, boxed: true }, { text: ' ' });
292    if (d.to === 'session') controls.push({ text: 'escalate', press: `escalate:${d.id}`, dim: true }, { text: ' ' });
293    controls.push({ text: 'dismiss', press: `dismiss:${d.id}`, dim: true });
294    rows.push(controls);
295  }
296  if (o.web) rows.push([], [{ text: `a written answer: ${o.web}`, dim: true }]);
297  return rows;
298}
299
300const TAB_ROWS: Record<Tab, (f: Fleet, self: Self, o: PaneOpts) => Row[]> = { work: workTab, epics: epicsTab, ci: ciTab, inbox: inboxTab };
301
302// the pane: the tab row, then the tab's rows cut to the room there is
303export function paneRows(f: Fleet, self: Self, o: PaneOpts): Row[] {
304  const body = TAB_ROWS[o.tab](f, self, o);
305  const room = Math.max(2, o.rows - 2);
306  const cut = body.length <= room ? body : [...body.slice(0, room - 1), [{ text: `… ${body.length - room + 1} more rows`, dim: true }]];
307  return [tabRow(f, self, o.tab), [], ...cut];
308}
309
310// one line above the prompt while something needs the person, nothing otherwise
311export function bandRow(f: Fleet, self: Self): Row | undefined {
312  const s = scope(f, self);
313  const c = counts(s.work, s.decisions);
314  if (!c.attention && !c.waiting) return undefined;
315  return [{ text: 'helm ', color: 'claude', bold: true }, ...summary(c)];
316}
317
318export function statusText(f: Fleet, self: Self): string | undefined {
319  const s = scope(f, self);
320  if (!s.work.length && !s.decisions.some((d) => d.blocking)) return undefined;
321  const c = counts(s.work, s.decisions);
322  return [`helm ${c.active}▸`, c.ci ? `${c.ci}ci` : '', c.attention ? `${c.attention}!` : '', c.waiting ? `${c.waiting}?` : ''].filter(Boolean).join(' ');
323}
324