SLOPSHOPPER

agentille

One typed command runs the work: /agt plans, builds and reviews with the right model per step, steps aside on small tasks, and ends on one short card. Also…

panebandspinnerrowsguardcommand
★ 1v3.24.0MITupdated 2026-10-24hasuwini77/agentille
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · agentille
│ ┃ agentille ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ ◆ agentille run adhoc │ agentille │ │ ┃ No agents yet. Type /agt "task": every ⏺ Read(src/auth.ts) │ agt ⚑ Claude Code v2.1.289 is older than │ │ ┃ dispatch shows up here. ⎿ Read 6 lines │ the v2.1.294 agentille needs — pane tools │ │ ⏺ Update(src/auth.ts) │ stay off until you update it │ │ ⎿ Added 2 lines, re╰────────────────────────────────────────────╯ │ ⏺ 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 │ │ › /agt-deck │ ⎿ agentille: deck open │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · agentille
◆ agentille run adhoc No agents yet. Type /agt "task": every dispatch shows up here.
README

agentille

One typed command runs the work. Type /agt "task" in Claude Code and that one prompt becomes a planned, built and reviewed change, each step on the model that fits it and, if you want, in your own voice (/agentille-init, optional, 1 minute). A few /agt-* commands read or tidy what a run left (/agt-info, /agt-clean).

Quick start

  1. Install (no profile or config needed), then start a new Claude Code session so the plugin and its mod load. Nothing prints on load. `` /plugin marketplace add hasuwini77/agentille /plugin install agentille@hasuwini77-agentille ``
  2. Check that the mod loaded: type /agt-info. Its first line reads display (profile.json → display):, followed by the display settings in effect and the last run's routing. Every /agt-* command comes from the module hooks/hooks.json loads, so if Claude Code does not know /agt-info, the mod did not load.
  3. /agt still works without the mod; its recon line then ends in [agentille v<version>], and you get the plain subagent tree instead of the band.
  4. Smoke test, kept local: type /agt --local "fix the typo in the footer". --local runs that one /agt under integration: "local", so it pushes nothing and opens no PR, with no profile file. Under local each slice is built on its own branch and merged into the branch you were on with a merge commit; nothing is pushed and no PR is opened. It prints recon: low · solo · <reason>, then Claude makes the fix itself on a new fix/<slug> branch, with no agents and no card. The default is integration: "pr", which pushes that branch and opens a PR; { "integration": "local" } in ~/.agentille/profile.json makes local permanent.
  5. Run a bigger one: /agt "add a CSV export endpoint and a download button on the reports page". It reads your repo and picks a level: low (it just does it, or one builder), medium (2–3 builders in parallel) or heavy (one Herdr or tmux pane per part). The recon line names the level it picked (medium · subagent, say), and the band above your prompt fills with the planner, executors and reviewers. Risky changes (auth, payments, data) get a red-team pass, under pr you get one reviewed PR per part to merge (merging on green is opt-in, see "What it touches"), and every pane it opened is closed.
  6. Read the card it ends on (solo runs have none). Everything else (plan, findings, each agent's full report) is in that report.md. A one-part feature's card under pr looks like this: `` ✓ dark mode toggle on /settings · low · 4 files · feat/dark-mode-toggle · 6m verify: npm test → 48 passed review: PASS — code-reviewer design-reviewer ⚑ PR #12 ready Open: ~/.agentille/state/run-a1b2/report.md Next: gh pr merge 12 --merge ``
  7. Then: every other key in ~/.agentille/profile.json is optional (Settings). /agentille-init adds your voice; /agentille-project adds a repo's entry. Each surface the mod draws has an off switch in the profile's display block: band (the band and its session-start toasts), statusLine, mascot, rows (the transcript rows), spinner, deck, focus (the ⚑ flags) and highlight (reply highlighting). The top-level sessions key stops a plain prompt from opening sessions, and AGENTILLE_UPDATE_CHECK=0 turns the daily version check off: docs/settings.md.

Small tasks stay cheap: a one-sentence task with no risk words (the typo, the rename) runs solo, with no agents and no card. A plain prompt never starts /agt: the skill runs only when you type it. Powered by Systown AI Lab.

Also in the box, each covered below: /storm researches what to build next and hands the picks to /agt heavy; "open two sessions" opens real Claude, Codex or shell panes beside yours; /agentille-project writes a repo's CLAUDE.md and /agentille-claude-md trims one (your global ~/.claude/CLAUDE.md unless you give it a path). The band, the deck and the wire belong to the mod. The words this README uses (level, slice, band, transport, integration): docs/glossary.md.

Contents

When to use it

Plain Claude is one developer. /agt is that developer plus a planner and a reviewer, brought in only when the task is big or risky enough to pay for them.

Good fitExample
A multi-step feature/agt "add a dark mode toggle to settings, persisted per user, with tests"
Two independent parts/agt "add a CSV export endpoint and a download button on the reports page"
A risky change (auth, payments, data)/agt "add webhook handling for subscription cancellations"
A review before merge/agt "review the changes on this branch"
A bug across several files/agt "debug why checkout totals are off by one cent"
Unsure of the scope/agt "plan the migration of the auth pages to the app router"
Work through a queue/agt next "add a 404 page" to queue it · /agt next to build the next item

What you get over a plain prompt: a separate reviewer checks the work instead of the model that wrote it, each step runs on the model that fits it, independent parts build at the same time, a finished part's reviewers run together rather than one after another, and risky diffs get a red-team pass.

Skip it for one-file edits, typos, renames and questions: a plain prompt is cheaper. Any run that is not solo costs more tokens than a plain prompt. What you buy is fewer wrong or unreviewed changes, not a lower bill.

Commands

You typeYou get
/agt "task"The level is detected: low (solo or one builder), medium (2–3 builders in parallel as subagents) or heavy (one Herdr/tmux pane per part)
`/agt low\medium\heavy "task"`Force the level for one run
/agt next ["task"]Build the next item in .agentille/backlog.md, or queue one
/agt-infoDisplay settings in effect, last run's routing and ledger, active squads

Every command and its arguments (--fable, /agt-spawn, /agt-clean, /agt-tell, /storm, /agt-deck, the setup skills and the two deprecated ones): docs/commands.md.

Settings

Everything lives in ~/.agentille/profile.json. Every key is optional and no profile file is needed. The key most people set first is integration, what a finished slice becomes: pr (the default) pushes a branch and opens a PR per slice, auto also merges each PR on green and pushes a version tag, push pushes the branch only, local pushes nothing (/agt --local "task" runs one run that way, with no profile). A repo can only lower it, and a risky diff (auth, payments, deploy, migrations, dependencies) stops at the PR under every setting. /agt-info shows the display values in effect and where each came from.

Every key, its default and what is checked (integration, thinkingDepth, projects[], routing.*, display.*, the voice keys, viewports): docs/settings.md.

Storm

/agt builds what you tell it. /storm tells it what to build.

/storm
  • Map: two Haiku scouts map the code (what exists, what is half-built).
  • Research: eight Sonnet lenses research in parallel: user complaints, competitors, what people pay for, cheap wins in the code, activation loops, distribution hooks, new platform capability, quality users notice.
  • Pick: a judge merges and scores them (2·user + 2·value + fit − effort − risk), an adversary red-teams the top 8, and the auto-pick keeps 2–5 that fit one heavy run.
  • Spec: it writes docs/storm/<date>.md, with acceptance criteria per pick, and commits it on a feature branch; on main, master or a detached HEAD it leaves the file uncommitted.
  • Build: then a fresh Claude session opens beside you and types /agt heavy "Build the picks in docs/storm/<date>.md …". Without Herdr or tmux it prints that line to paste.
  • Without agentille at all (storm-skill, a mirror of skills/storm/), the build still runs: a tmux window when one is live, else built-in Sonnet subagents in worktrees, one PR per pick, never merged for you.

Past storm docs are the exclusion list: a feature shipped or dropped once is never proposed again. /storm 3 forces three picks, /storm "onboarding" biases every lens, --ask pauses once at the shortlist, --no-build stops at the doc, --next queues the picks for /agt next instead, quick runs four lenses and hands off at medium.

Sessions

Ask in a plain prompt: "open three sessions", "open a codex session", "open two shells in ../api". The mod opens real Herdr or tmux panes beside yours, unfocused, up to 8 at once, and each one is yours, like a pane opened by hand: no worker role, no reports, no /agt run unless one is typed into it.

Kinds, follow-ups, which ones close on their own and how to get one back: docs/sessions.md.

How it decides

  • Solo (low) for a small, one-sentence task with no risk words.
  • Subagents for one slice or sequential work (low), and for 2–3 small file-disjoint slices built in parallel (medium).
  • Panes (heavy, Herdr or tmux) for 2+ file-disjoint slices that are big enough to pay for a pane: any slice of about 30 minutes or more, one that needs its own dev server, simulator or browser, or more than 3 slices. Without a pane transport heavy runs as a workflow or subagent waves.
  • The pick is always printed with a one-line reason.
  • Fewer stuck runs: shared files (lockfiles, schema, shared types, registries) land first in one contract step before slices split; a builder that stops early is resumed once; cheap Haiku scouts map unfamiliar code before the planner.
  • Review is a gate: P0/P1 findings get fixed before the card says ✓.
  • Squads: in a saas, ecommerce, content or immersive repo, payments, SEO and performance specialists join the review when the diff touches their area.
  • Type less: the first word after /agt completes to a level (low, medium, heavy, next), and a dash completes to --fable.
  • What you see: the band (a live dispatch tree above your prompt, also called the switchboard), a live row per Agent call in the transcript, a pinned status line under the prompt, and a small mascot in each worker pane, all drawn by the mod for zero model tokens: docs/display.md. Each has its own switch in the profile's display block (docs/settings.md).
  • Pane workers report back over the wire, and a pane is closed only once its answer is saved or read.
  • Best with Herdr: workers are labeled in its sidebar and a run with 3+ pane workers gets its own tab; ask for Codex in the task ("codex builds the API slice") and that slice runs as a Codex pane. tmux works with the same band; without a multiplexer you get the subagent tree.

When something goes wrong

  • See what is in effect: /agt-info prints the display settings in effect and where each came from, the last run's routing and ledger, and the active squads. /agt-info route <role> dry-runs one route under your thinkingDepth and routing.*.
  • Read the run: every non-solo run writes ~/.agentille/state/run-<id>/report.md (plan, findings, each agent's full report); the card's Open: line names it. A real failure starts the card with ✗ <what failed + where>, and its Next: line is the fix.
  • A version toast is not a failed run:
  • agt ⚑ agentille vX is installed but this session runs vY — restart Claude Code before opening panes means the plugin updated under a running session, and /agt refuses to open panes until you restart.
  • agt ⚑ Claude Code vX is older than the vY agentille needs means pane tools stay off until you update Claude Code.
  • AGENTILLE_UPDATE_CHECK=0 turns the version check off (see Network).
  • No panes is not a failed run either: without Herdr or tmux, heavy runs as a workflow or subagent waves, and the recon line (recon: <level> · <transport> · <reason>) says workflow or subagent instead of panes.

Requirements

NeedForWithout it
Claude Code 2.1.294+the mod's pane tools: heavy panes, /agt-spawn, sessionsthe mod still draws the band and routes models; pane tools stay off (a toast says so) and heavy runs as a workflow or subagent waves
gitevery levelnothing works
gh (GitHub CLI, logged in)PRs, issues, auto mergesintegration falls back to push or local
Herdr (install from its repo) or tmux 3.3+ (brew install tmux, apt install tmux; an older tmux works but a worker may rename its pane)the heavy level (one pane per slice), /agt-spawn, sessionsheavy runs as a workflow or subagent waves
HerdrCodex worker panes, auto-closing idle sessionstmux panes stay open until you close them
Codex CLI, logged in"codex builds the API slice"the slice runs on Claude
Playwright MCP plugin (mcp__plugin_playwright_playwright__*) and a running dev serverthe design reviewer's screenshots and axe scanthe design reviewer reads code only and says so
jq or nodethe session-end pane sweepthe sweep does nothing

No profile file is needed. macOS and Linux; the shell hooks are bash.

How the plugin is tested (credential-free CI on every PR, a capped eval run weekly and on each release): docs/testing.md.

Releases

One tag a day at most and fixes batched into the next minor. From v3.23.0 (2026-10-23) on, nothing is removed outside a major that deprecated it first; before that, v3.14.0 removed /agt-routing, /agt-ledger and /agt-squads in a minor. What each version number promises and how to pin one: docs/releasing.md.

What it touches

Before you type anything the mod does four small things:

  • it draws its band above the prompt (unless display.band is off) and, under display.highlight: on or all, lights replies;
  • at session start and after a compaction its hook runs the version check, which fetches at most once a day (see Network);
  • at session start it closes finished agt-* panes a dead lead left behind;
  • and it registers its pane tools only on a turn where you typed for them (see Panes).

Everything else waits for a typed /agt, /storm or a session ask. When you do:

  • Your repo: a branch per slice (feat/<slug>, fix/<slug>, or agt/<slug> off a feature branch), atomic commits, one PR per slice, and with auto a merge commit plus a version tag. /agt next and /storm --next keep .agentille/backlog.md (gitignored on first use). /storm writes docs/storm/<date>.md and commits it on a feature branch; on main, master or a detached HEAD it leaves the file uncommitted.
  • On GitHub: with gh, one issue per slice and one PR per slice; with auto, merged PRs and pushed tags.
  • Beside your repo: each parallel executor works in a sibling worktree ../<project>-<slug> with your .env* files copied in and node_modules copied (never linked).
  • The worktree stays until the slice is merged or escalated, then the lead removes it (the branch stays).
  • The run-end tidy and /agt-clean remove only merged, clean agt/* worktrees this session's runs made, and never one made under 10 minutes ago or with no commits of its own.
  • Copied .env* files are deleted from every worktree the run made when it ends, whatever the branch; only untracked copies git ignores go, a tracked or un-ignored .env.example stays.
  • In your home: ~/.agentille/state/run-<id>/ (plan, checkpoints, every agent's report, report.md), ~/.agentille/profile.json when you save a setting, and ~/.agentille/.update-check.json.
  • Network: the hook runs at session start and after a compaction, and at most once a day it fetches this repo's plugin.json from GitHub to compare versions (3 s timeout, nothing sent). AGENTILLE_UPDATE_CHECK=0 turns it off, and so does Claude Code's own DISABLE_TELEMETRY or CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC set to 1 or true.
  • Research agents (/storm) read the web.
  • An executor whose worktree has no node_modules to copy runs the project's own install, and the security reviewer runs npm audit; both reach the package registry.
  • Nothing else goes out.
  • Panes: a plain session has no pane tools.
  • The mod registers them only on a turn where you typed /agt or asked for sessions, panes or terminals, and each tool checks that proof again when called.
  • Worker panes close when harvested; at session end the sweep closes only the idle or done worker panes this session opened whose answer is saved.
  • When the proof lapses, and how shells and folder trust work: docs/guards.md.
  • Models and cost: every non-solo run costs more than a plain prompt. Opus runs the judgment roles, Sonnet the executor and the cheaper reviews, Haiku only classifies and scouts, and Fable runs only with --fable or with routing.autoFable: true (after two plan REVISEs, or for the diagnose planner after two failed fixes). routing.maxRunUsd (default $15) moves later Opus roles to Sonnet once a run passes it. Every cell: Routing.

Turn it off, or uninstall

  • Quiet, not gone: every surface has a switch in the profile's display block, sessions: off keeps panes shut, and a plain prompt never starts a run (Settings).
  • Uninstall: /plugin → uninstall agentille (or claude plugin uninstall agentille). Nothing in the plugin runs after that.
  • What it leaves behind, and how to remove it: ~/.agentille/ (profile.json, config.json, state/ with each run's folder and the lead files, .update-check.json): delete the folder. In a repo: .agentille/backlog.md (gitignored, only if you used /agt next or /storm), docs/storm/<date>.md if you ran /storm, and any agt/* or feat/* slice branch a run left: git branch and git worktree list show them; /agt-clean removes merged agt/* worktrees while the plugin is installed, git worktree remove <path> after.

Routing

Each role gets a model and an effort. The mod picks them from the dispatch header's size and risk and the profile's thinkingDepth (hooks/routing.js); without the mod the lead passes the same models as a fallback. The first column that applies wins, in this order: thinkingDepth=quick, then risk auth or money, then size=large, then the default. A — means that column changes nothing for the role, and risk=data changes no route. This table is a copy of skills/agt/routing.md → "Default routing":

roledefaultsize=largerisk auth/moneythinkingDepth=quick
planneropus · highopus · xhigh—sonnet · medium
plan-reviewersonnet · mediumopus · high—sonnet · medium
ui-prototyperopus · highopus · high—sonnet · medium
executorsonnet · mediumsonnet · highsonnet · highsonnet · medium
code-reviewersonnet · mediumopus · highopus · highsonnet · medium
design-revieweropus · highopus · highopus · highsonnet · high
security-revieweropus · highopus · highopus · maxsonnet · high
payments-revieweropus · highopus · highopus · maxsonnet · high
seo-reviewersonnet · mediumsonnet · high—sonnet · low
perf-reviewersonnet · highopus · high—sonnet · medium
adversarysonnet · highsonnet · highopus · highsonnet · medium
  • Small UI work stays cheap: a one-screen UI feature or fix with size=small and risk=none gets one executor and the Sonnet code-reviewer. The ui-prototyper and design-reviewer join when the change spans more than one screen, at size=large, or when you ask for design work (routing.md → "Roster").
  • The plan-reviewer under quick: the lead skips it (docs/settings.md); its quick cell is the route one still gets if it is dispatched, and what /agt-info route plan-reviewer depth=quick prints.
  • Haiku never writes: it only classifies a task the level table cannot place and runs read-only scouts.
  • The executor never leaves Sonnet; only its effort moves (and on fix rounds: attempt 2 → high, attempt 3 and later → max).
  • Escalation: a plan REVISE puts the next planner on opus · max. Fable (about twice the cost of Opus) runs only when you type --fable, or with routing.autoFable: true after two REVISEs, or for the diagnose planner after two failed fixes, within maxFablePerRun and fableWeeklyCeiling.
  • Check a route: /agt-info route <role> [size=…] [risk=…] [depth=…] prints what a role would get, escalation rungs included.
  • Cost ceiling (routing.maxRunUsd): past it, every later planner, plan-reviewer, reviewer (design-reviewer included), ui-prototyper or adversary, subagent or pane, that would run Opus (or a ladder Fable) runs Sonnet at the same effort. Only the executor and a typed --fable keep their routes.
  • The estimate: subagents are priced from their tokens at API list prices, and Herdr or tmux pane workers, which report no tokens, from their role, routed model and minutes open. A subscription is not billed per token, so this is an estimate. Prices and the formula: docs/routing-cost.md.
  • You see it: one toast and a band flag per run naming what was demoted. /agt-info ledger shows the estimate, and /agt-info route shows the pick past the ceiling.

Contributing

How to verify a change and land it: CONTRIBUTING.md.

Acknowledgments

The executor's debugging, test-first and verification discipline is informed by Jesse Vincent's superpowers (MIT), internalized, not bundled.

MIT, see LICENSE. By Systown AI Lab.

Source 51 files
hooks/register.js 312 lines
1// agentille mod entry: wires the hooks. The state is in state.js; routing, panes, sessions, the reaper, the
2// timers, the worker's wire, display settings, drawing and run files each have a module beside this one.
3
4import { ctx, isLead, Profile, Display, Runs, Spawn, Panes, Proofs, Session, setRunningVersion, markSkewToasted, setHostVersion, markHostOld, setIdentity, setWeeklyPct, setLeadModel, setLeadTurn } from './state.js'
5import { registerAutocomplete } from './autocomplete.js'
6import { toolLabel, runPhases } from './board.js'
7import { cleanText } from './clean.js'
8import { routingView, ledgerView, dispatchAgent, setRouteVerdict, noteAgentTool, enterAgentCall, leaveAgentCall, noteAgentStep, addLeadUsage } from './dispatch.js'
9import { DECK, applyDisplay, answerPanel, deckCommand, focusCommand, highlightCommand, setStoredRaw, setLastAnswer, mascotHello, mascotWorking } from './display.js'
10import { canDraw, drawingBlock } from './drawing.js'
11import { highlightFor, litFor } from './highlight.js'
12import { parseInfoArgs, routeText, routingSummary, ledgerSummary, squadsSummary, overviewText } from './info.js'
13import { verdictChip } from './links.js'
14import { ledger } from './live.js'
15import { parseWorker } from './mascot.js'
16import { PROBE, SPAWN_ROLE, transportBlock, paneName, newRunId, paneKey, parseSpawnArgs, herdrPromptArgv } from './panes.js'
17import { installedSkew, loadProfile, loadSquads, squadsView, tipOnce } from './profile.js'
18import { bashCall, writeCall, editCall } from './guard.js'
19import { pollNow, cleanWorkspace } from './reaper.js'
20import { cardBox, answerBox, switchboard, deck } from './render.js'
21import { registerRows } from './rows.js'
22import { hostMessage, hostTooOld, hostVersionOf, skewMessage } from './skew.js'
23import { probeTransport, transportOf, openPane, loadOwned, savePanes, ownName } from './spawn.js'
24import { spawnPane, openSessions, closePane } from './tools.js'
25import { registerStatus } from './status.js'
26import { refreshAgents, working, ensurePolling, ensureTicker } from './ticker.js'
27import { statusKey, freshStatus, validLead, parseWire, shortName, parseTellArgs } from './wire.js'
28import { publish, noteWire, pubRoute, pubTool, pubStep, pubWorking } from './worker.js'
29import { onPromptSubmit, onTurnComplete } from './turns.js'
30import { dispatchedRun, agtTurnFromDispatch } from './proofs.js'
31import { parseHeader, roleOf } from './routing.js'
32import * as P from './panerec.js'
33
34// Per message id, whether a reply is lit and its highlight: only the AssistantMessage render below reads them.
35const litMemo = new Map()
36const hlMemo = new Map()
37
38export function register(on) {
39  on('session.start', async ($, e, next) => {
40    await loadProfile($)
41    await loadSquads($)
42    try {
43      setRunningVersion(JSON.parse(await $.fs.read($.plugin.root + '/.claude-plugin/plugin.json')).version ?? null)
44    } catch {
45      setRunningVersion(null)
46    }
47    // The session-start toasts belong to the band: display.band off → none. The profile's band is in effect now (it
48    // has no stored value); applyDisplay runs again below once the old store toggles are read.
49    applyDisplay()
50    const skew = await installedSkew($)
51    if (skew) {
52      markSkewToasted()
53      if (Display.bandOn) $.ui.toast('agt ⚑ ' + skewMessage(skew, Session.runningVersion))
54    }
55    // The host's own version: too old for the mod's pane tools → one toast, and ensureTools registers none.
56    setHostVersion(hostVersionOf(await Promise.resolve().then(() => $.session.version()).catch(() => null)))
57    if (Session.hostVersion && hostTooOld(Session.hostVersion)) {
58      markHostOld()
59      if (Display.bandOn) $.ui.toast('agt ⚑ ' + hostMessage(Session.hostVersion))
60    }
61    await probeTransport($)
62    const worker = parseWorker(await $.env.get('AGENTILLE_WORKER'))
63    const sessionId = validLead(await $.session.id().catch(() => null))
64    const wireName = /^agt-[A-Za-z0-9_-]+$/.test((await $.env.get('AGENTILLE_NAME')) ?? '') ? await $.env.get('AGENTILLE_NAME') : null
65    setIdentity({ worker, sessionId, wireName, leadSession: wireName ? validLead(await $.env.get('AGENTILLE_LEAD')) : null })
66    if (Session.worker) pubRoute(Session.worker.model, Session.worker.effort)
67    await $.command.register({ name: 'agt-deck', description: 'Open the agentille deck: the cast, routing timeline, wire log and tokens. auto = open on every /agt (saved as display.deck) · off', argumentHint: '[auto|off]', immediate: true })
68    await $.command.register({ name: 'agt-tell', description: 'Send a message to a worker pane over the wire', argumentHint: '<worker> <message>', immediate: true })
69    await $.command.register({ name: 'agt-spawn', description: 'Open a routed claude pane beside this one (Herdr or tmux); it closes itself once its answer is saved', argumentHint: '"task" [--model sonnet|opus|haiku|fable]' })
70    setStoredRaw({
71      deckAuto: await $.store.get('deck:auto'),
72      focusMode: await $.store.get('focus:mode'),
73      highlightOn: await $.store.get('highlight:on'),
74      highlightAll: await $.store.get('highlight:all'),
75    })
76    applyDisplay()
77    await $.command.register({ name: 'agt-info', description: 'Settings in effect, routing, ledger, squads, or a route dry-run: routing | ledger | squads | route <role>', argumentHint: '[routing|ledger|squads|route <role> [size=…] [risk=…] [depth=…]]', immediate: true })
78    await $.command.register({ name: 'agt-highlight', description: 'Highlight replies: on (/agt replies lit; a paste-ready ask gets a plain-text note) · all (every typed question gets the answer shape) · off (nothing added to any prompt). Saved as display.highlight in profile.json. Deprecated; removed in 4.0.0', argumentHint: '[on|all|off]', immediate: true })
79    await $.command.register({ name: 'agt-clean', description: 'Tidy up now: close finished agt panes, remove merged agt/* worktrees and branches this session\'s runs made, drop run folders untouched for 14 days. Anything still working, unmerged or made elsewhere stays', immediate: true })
80    await $.command.register({ name: 'agt-focus', description: 'Agent flags above the prompt (a REVISE, a FAIL, a blocked pane): on · off. Saved as display.focus in profile.json. Deprecated; removed in 4.0.0', argumentHint: '[on|off]', immediate: true })
81    if (Spawn.transport !== 'none') {
82      // One look now: a lead restarted mid-run takes back the panes it opened (lead-<pane>.panes) and no other
83      // session's. It reaps only those whose answer was written after this look; an older one is flagged
84      // "not harvested" and left to the person. A session that opened none polls nothing.
85      await loadOwned($)
86      await pollNow($, Spawn.transport)
87      if (Panes.panes.length) ensurePolling($)
88      // A lead that died skipped its SessionEnd sweep: close its finished workers now.
89      if (Panes.panes.length && isLead()) void cleanWorkspace($, { auto: true, panesOnly: true }).catch(() => {})
90    }
91    if (working()) ensureTicker($)
92    if (Session.wireName) await publish($, true)
93    await refreshAgents($)
94    return next(e)
95  })
96
97  // The display toggles answer from display.js: deck (open it, auto, off), focus and highlight.
98  on('command.run', { command: 'agt-deck' }, deckCommand)
99  on('command.run', { command: 'agt-focus' }, focusCommand)
100  on('command.run', { command: 'agt-highlight' }, highlightCommand)
101
102  // Typed only. The worker gets it as a peer message over the wire; a Herdr worker without the
103  // mod still gets it as a prompt.
104  on('command.run', { command: 'agt-tell' }, async ($, e) => {
105    if (!['composer', 'bridge'].includes(e.origin?.kind)) return { text: '/agt-tell runs only when typed.' }
106    const t = await transportOf($)
107    if (t !== 'none') await pollNow($, t)
108    const a = parseTellArgs(e.args, Panes.panes)
109    if (a.usage || a.error) return { text: a.usage ?? a.error }
110    const rec = await $.store.get(statusKey(a.name)).catch(() => null)
111    const sid = freshStatus(rec, a.name, Date.now()) ? validLead(rec.session) : null
112    let sent = false
113    if (sid) sent = (await $.session.send({ to: { sessionId: sid }, text: '[agt wire] lead note · ' + a.text }).catch(() => ({ isDelivered: false }))).isDelivered
114    if (!sent && t === 'herdr') sent = (await $.process.run(herdrPromptArgv(a.name, a.text), PROBE).catch(() => null))?.exitCode === 0
115    if (!sent) return { text: 'Could not reach ' + a.name + '.' }
116    noteWire({ from: 'lead', to: shortName(a.name), kind: 'note', summary: a.text, at: Date.now() })
117    $.ui.invalidate('ui.render')
118    return { text: '⇄ sent to ' + a.name }
119  })
120
121  // The one place for read-only facts: settings in effect, routing, ledger and squads views, and a routing dry-run.
122  on('command.run', { command: 'agt-info' }, async ($, e) => {
123    const a = parseInfoArgs(e.args)
124    if (a.error) return { text: a.error }
125    if (a.view === 'routing') return { text: routingView() }
126    if (a.view === 'ledger') return { text: ledgerView() }
127    if (a.view === 'squads') return { text: await squadsView($) }
128    if (a.view === 'route') return { text: routeText({ ...a, depth: a.depth ?? Profile.depth }, Profile.settings, Session.weeklyPct) }
129    await loadSquads($)
130    const log = Runs.runs.get(Runs.lastRun)?.log ?? []
131    return { text: overviewText({ display: Display.display, sessions: Profile.sessions, squads: squadsSummary(Profile.squadRows), routing: routingSummary(log), ledger: ledgerSummary(ledger(Runs.live, Runs.lastRun, Runs.paneRoutes)) }) }
132  })
133
134  // Typed only: a plugin, a scheduled task or a notification never opens a pane.
135  on('command.run', { command: 'agt-spawn' }, async ($, e) => {
136    if (!['composer', 'bridge'].includes(e.origin?.kind)) return { text: '/agt-spawn runs only when typed.' }
137    const a = parseSpawnArgs(e.args)
138    if (a.usage || a.error) return { text: a.usage ?? a.error }
139    const t = await transportOf($)
140    if (t === 'none') return { text: 'No pane transport here: /agt-spawn needs Claude Code running inside Herdr or tmux.' }
141    const run = newRunId()
142    const name = paneName(run, SPAWN_ROLE)
143    try {
144      await openPane($, t, { run, name, model: a.model, task: a.task, cwd: await $.session.cwd() })
145    } catch (err) {
146      return { text: 'Could not open a ' + t + ' pane: ' + String(err?.message ?? err).slice(0, 160) }
147    }
148    ownName(name)
149    await savePanes($)
150    ensurePolling($)
151    return { text: 'Opened ' + name + ' · ' + a.model + ' · ' + t + ' pane.' }
152  })
153
154  on('tool.call', { tool: 'mcp__agentille__spawn_pane' }, spawnPane)
155  on('tool.call', { tool: 'mcp__agentille__open_sessions' }, openSessions)
156  on('tool.call', { tool: 'mcp__agentille__close_pane' }, closePane)
157  on('tool.call', { tool: 'Bash' }, bashCall)  // guard.js: integration guard + worktree ownership
158  // guard.js: a run below auto may not write the trust root or the repo's git state through a non-Bash tool either.
159  on('tool.call', { tool: 'Write' }, writeCall)
160  on('tool.call', { tool: 'Edit' }, editCall)
161  on('tool.call', { tool: 'MultiEdit' }, editCall)
162  on('tool.call', { tool: 'NotebookEdit' }, editCall)
163
164  on('command.run', { command: 'agt-clean' }, async ($, e) => {
165    if (!isLead()) return { text: 'agt clean runs in the lead session, not in a worker pane.' }
166    return { text: cleanText(await cleanWorkspace($, { all: true })) }
167  })
168
169  // A typed /agt starts a clean run, and the turn's proofs are set or dropped: turns.js.
170  on('prompt.submit', async ($, e, next) => next(await onPromptSubmit($, e)))
171
172  on('skill.prompt', async ($, e, next) => {
173    if (!/(^|:)agt$/.test(e.skill)) return next(e)
174    agtTurnFromDispatch()
175    const t = await transportOf($)
176    if (t !== 'none') ensurePolling($)
177    const draws = canDraw(await $.session.surfaces().catch(() => []))
178    if (draws) await tipOnce($)
179    return next({ ...e, text: e.text + Profile.squadBlock + transportBlock(t, Spawn.paneTools && isLead()) + drawingBlock(draws) })
180  })
181
182  // Worker results arrive as peer messages: log them for the band and the deck, then let the
183  // model read them (that delivery is what wakes the lead).
184  on('session.receive', async ($, e, next) => {
185    const w = parseWire(e.text)
186    if (w) {
187      const from = shortName(w.from)
188      // Only the pane whose key the message names: a stale list or a respawned role must not harvest the older pane.
189      const hit = w.kind === 'done' && w.key ? Panes.panes.find((p) => paneKey(p.id) === w.key && p.name === w.from) : null
190      if (hit) P.harvest(hit.id, { wire: true })
191      const route = w.kind === 'done' ? Runs.paneRoutes.findLast((r) => r.name === w.from) : null
192      if (route) setRouteVerdict(w.from, verdictChip(route.agent, w.summary))
193      noteWire({ from, to: Session.wireName ? shortName(Session.wireName) : 'lead', kind: w.kind, summary: w.summary, at: Date.now() })
194      $.ui.toast('⇄ ' + from + ' ' + w.kind)
195      $.ui.invalidate('ui.render')
196    }
197    return next(e)
198  })
199
200  // What each agent is doing right now, for its band row: a subagent's call carries its agentId;
201  // a worker pane's own main loop publishes for its lead. Observe only.
202  // The Write hook (guard.js writeCall) both guards protected writes and observes a run's report write.
203
204  on('tool.call', async ($, e, next) => {
205    if (e.agentId) {
206      noteAgentTool(e.agentId, toolLabel(e.tool, e))
207      // A workflow agent inside one long call (a full test suite) is alive: tree.js quietWorkflows
208      // skips it until the call returns, and the return counts as heard.
209      if (Runs.live.get(e.agentId)?.workflow) {
210        enterAgentCall(e.agentId)
211        try {
212          return await next(e)
213        } finally {
214          leaveAgentCall(e.agentId)
215        }
216      }
217    } else if (Session.wireName) {
218      pubTool(toolLabel(e.tool, e))
219      void publish($).catch(() => {})
220    }
221    return next(e)
222  })
223
224  on('session.measure', async ($, e, next) => {
225    const week = e.rateLimits.find((r) => r.kind === 'seven_day')
226    if (week) setWeeklyPct(week.percentUsed)
227    return next(e)
228  })
229
230  // Routing happens in dispatch.js; the redraw ticker is nudged here so dispatch.js needs no timer.
231  on('agent.spawn', async ($, e, next) => {
232    const res = await dispatchAgent($, e, next)
233    if (!res?.deny && roleOf(e.subagentType)) dispatchedRun(parseHeader(e.prompt)?.run)
234    ensureTicker($)
235    return res
236  })
237
238  on('turn.step', async function* ($, e, next) {
239    const a = e.agentId ? Runs.live.get(e.agentId) : undefined
240    if (!e.agentId) setLeadModel(e.model)
241    const result = yield* next(a && a.routed ? { ...e, effort: a.effort } : e)
242    if (!e.agentId && result?.usage) addLeadUsage(result.usage, e.model)
243    if (!e.agentId && Session.wireName && result?.usage) {
244      pubStep(result.usage, e.model)
245      await publish($)
246    }
247    if (a && noteAgentStep(e.agentId, { effort: e.effort, model: e.model, usage: result?.usage })) $.ui.invalidate('ui.render')
248    return result
249  })
250
251  // A main-loop turn began (a subagent's run raises none). A worker's first one plays hello.
252  on('turn.start', async ($, e, next) => {
253    setLeadTurn(true)
254    if (e.agentId === undefined) setLastAnswer(null)
255    if (Session.worker) {
256      const now = await $.clock.now()
257      if (mascotHello(now)) {
258        // tmux tags the pane name after the split, so the first poll can miss it: look once more.
259        if (!Session.selfName && Spawn.transport && Spawn.transport !== 'none') await pollNow($, Spawn.transport)
260      }
261      mascotWorking(now)
262      ensureTicker($)
263      $.ui.invalidate('ui.render')
264    }
265    if (Session.wireName) {
266      pubWorking()
267      await publish($, true)
268    }
269    return next(e)
270  })
271
272  on('turn.complete', async ($, e, next) => {
273    await onTurnComplete($, e)
274    return next(e)
275  })
276
277  // The switchboard above the prompt and the deck pane: render.js draws both from the state.
278  on('ui.render', { component: 'AbovePrompt' }, switchboard)
279  on('ui.render', { component: 'Pane', requestId: DECK }, deck)
280
281  // A long /agt reply: an essentials card on top, the body dim with its tokens lit. The
282  // decision is memoised per message id so a reply does not restyle when a later turn changes.
283  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
284    if (!litFor(litMemo, e.requestId, { on: Display.highlightOn, agtTurn: Proofs.agtTurn || Display.highlightAll })) return next(e)
285    const final = e.surface === 'terminal' && !e.props?.isSummary ? answerPanel(e.requestId, e.props?.text) : null
286    if (Display.rawIds.has(e.requestId)) return next(e)
287    const h = final ? null : highlightFor(hlMemo, e.requestId, e.props?.text)
288    if (!final && !h) return next(e)
289    const els = $.ui.resolve(e)
290    if (!els.Markdown) return next(e)
291    if (final) return answerBox(els, final)
292    const body = h.body !== null ? els.Markdown({ text: h.body, dimColor: true }) : await next(e)
293    return els.Box({ flexDirection: 'column', children: h.card.length ? [cardBox(els, h.card), body] : [body] })
294  })
295
296  // Main-session spinner: how many subagents (◇) and pane sessions (▣) work behind it. display.spinner off adds nothing.
297  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
298    if (!Display.spinnerOn || Runs.live.has(e.requestId)) return next(e)
299    const subs = [...Runs.live.values()].filter((a) => a.state === 'working').length
300    const busy = Panes.panes.filter((p) => p.state === 'working').length
301    if (subs + busy === 0) return next(e)
302    // In an /agt run the status line holds the counts; the spinner names the phases at work.
303    const phases = Runs.lastRun === 'adhoc' ? '' : runPhases(Runs.live, Runs.paneRoutes, Runs.lastRun)
304    const parts = phases || [subs ? '◇' + subs : '', busy ? '▣' + busy : ''].filter(Boolean).join(' ') + ' working'
305    return next({ ...e, props: { ...e.props, suffix: (e.props.suffix ?? '') + ' · ' + parts } })
306  })
307
308  registerRows(on, ctx)
309  registerStatus(on, ctx)
310  registerAutocomplete(on, ctx)
311}
312
hooks/state.js 34 lines
1// agentille mod state: the index of the session's stores. Each piece of state lives in the module that writes it
2// (store.js makeStore), and every other module reads it through that owner's read view, re-exported here:
3//
4//   Session   session.js   who this session is (lead or worker, its names, ids and versions), the lead's turn
5//   Proofs    proofs.js    the typed proofs the gates trust
6//   Runs      dispatch.js  the run the band follows, per-run counters, live agents, decisions, pane routes
7//   Spawn     spawn.js     the pane transport, the panes and run tabs this lead opened, the pane tools registered
8//   Panes     reaper.js    the agt-* panes the newest poll listed
9//   Sessions  sessions.js  the person's own sessions this lead opened
10//   Profile   profile.js   home, routing settings, depth and squads, from profile.json and squads.json
11//   Display   display.js   the display settings and switches, flags, the newest answer, the worker band's mascot
12//   Wire      worker.js    the wire log, each worker's published status, this worker's own
13//   Timers    ticker.js    the redraw count
14//   Worktrees guard-own.js the worktrees this session's runs made
15//
16// This file defines nothing: it is an index for the modules that own no store (register.js, render.js, tools.js, …).
17// No module it imports may import it, directly or through another module (scripts/validate.sh checks): an owner
18// imports session.js and the owners it reads from directly. A module writes only its own store, through its
19// transitions: a view throws on any write, at any depth. Everything here lives for the session (a reload starts
20// it over); nothing is persisted from here but through $.store and the run files. What the lead keeps about each
21// pane (harvest, wake, stranded, first seen, stage) is in panerec.js.
22
23export * from './session.js'
24export { Timers } from './ticker.js'
25export { Wire } from './worker.js'
26export { Profile } from './profile.js'
27export { Display } from './display.js'
28export { Runs } from './dispatch.js'
29export { Spawn } from './spawn.js'
30export { Panes } from './reaper.js'
31export { Sessions } from './sessions.js'
32export { Proofs } from './proofs.js'
33export { Worktrees } from './guard-own.js'
34
hooks/autocomplete.js 52 lines
1// /agt flag autocomplete: rows for the token at the cursor while a typed /agt prompt is being written.
2
3// Mirror of skills/agt/SKILL.md: the one optional level word right after /agt, and the one flag left.
4export const AGT_LEVELS = [
5  { text: 'low', description: 'one stream, may run solo' },
6  { text: 'medium', description: '2-3 small streams as subagents' },
7  { text: 'heavy', description: 'worker panes in Herdr or tmux' },
8  { text: 'next', description: 'build the next item of .agentille/backlog.md' },
9]
10export const AGT_FLAGS = [
11  { text: '--fable', description: 'Fable ceiling on judgment roles' },
12  { text: '--local', description: 'Integration local for this run: merged into your branch, no push, no PR' },
13]
14
15const CMD = /^\/(agentille:)?agt$/
16
17const WS = /\s/
18
19// The whitespace-delimited word before `start`, found by scanning back from it: the cost is that word's
20// length, not the draft's, and this runs on every keystroke.
21function wordBefore(text, start) {
22  const t = String(text)
23  const space = (i) => WS.test(t[i])
24  let end = Math.min(start, t.length)
25  while (end > 0 && space(end - 1)) end--
26  let at = end
27  while (at > 0 && !space(at - 1)) at--
28  return t.slice(at, end)
29}
30
31// Rows for the token, or [] when the token is the command itself or nothing matches. The first word
32// after /agt completes to the levels; a dash completes to the flag. The draft is known to be a typed
33// /agt one: registerAutocomplete's matcher lets nothing else through.
34export function agtSuggestions({ text, token, start }) {
35  if (typeof token !== 'string' || !(start > 0)) return []
36  const match = (rows) => rows.filter((r) => r.text.startsWith(token) && r.text !== token)
37  if (token === '-' || token.startsWith('--')) return match(AGT_FLAGS)
38  return CMD.test(wordBefore(text, start)) ? match(AGT_LEVELS) : []
39}
40
41// Fires on every keystroke: answer next(e) at once when there is nothing to add.
42export async function autocompleteHook($, e, next) {
43  const rows = agtSuggestions(e)
44  if (!rows.length) return next(e)
45  const r = await next(e)
46  return { suggestions: [...(r?.suggestions ?? []), ...rows] }
47}
48
49export function registerAutocomplete(on, _ctx) {
50  on('prompt.autocomplete', { text: /^\s*\/(agentille:)?agt(\s|$)/ }, autocompleteHook)
51}
52
hooks/board.js 281 lines
1// The switchboard: what the band above the prompt shows, as plain data. Pure on purpose:
2// register.js resolves the elements and paints; this file picks rows, glyphs and columns.
3
4import { MODEL_COLOR, modelKey } from './mascot.js'
5import { effortBar, elapsed, tokens } from './live.js'
6
7export const SPIN = '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'
8export const KIND_GLYPH = { sub: '◇', pane: '▣' }
9export const DONE_GLYPH = '✓'
10export const ACCENT = 0xd97757
11export const FRAME_COLOR = 0x3d4250
12export const DONE_COLOR = 0x3fb950
13export const WIRE_COLOR = 0x56d4dd
14export const WIRE_SHOW_MS = 120_000
15
16export const INK = '#14161c'
17export const hex = (n) => '#' + n.toString(16).padStart(6, '0')
18export const colorOf = (model) => hex(MODEL_COLOR[modelKey(model)])
19
20// One braille frame per tick; each row starts at its own offset so the spinners don't march in step.
21export function spin(tick, offset = 0) {
22  return SPIN[(tick + offset * 3) % SPIN.length]
23}
24
25// "claude-opus-5-5" → "opus 5.5", "claude-haiku-4-5-20251001" → "haiku 4.5", "sonnet" → "sonnet".
26export function prettyModel(model) {
27  const m = String(model ?? '').toLowerCase()
28  const k = modelKey(m)
29  if (k === 'other') return m.replace(/^claude-/, '').slice(0, 14) || 'model'
30  const v = new RegExp(k + '-(\\d+)(?:-(\\d{1,2}))?(?!\\d)').exec(m)
31  return v ? k + ' ' + v[1] + (v[2] ? '.' + v[2] : '') : k
32}
33
34// The model pill's text, one width for every model so the columns line up.
35export const CHIP_WIDTH = 8
36export function chip(model) {
37  const k = modelKey(model)
38  const name = k === 'other' ? String(model ?? '?').replace(/^claude-/, '').slice(0, CHIP_WIDTH - 2) : k
39  const pad = CHIP_WIDTH - name.length
40  return ' '.repeat(Math.floor(pad / 2)) + name + ' '.repeat(Math.ceil(pad / 2))
41}
42
43const base = (p) => String(p ?? '').split('/').filter(Boolean).pop() ?? ''
44const cut = (s, n) => (s.length > n ? s.slice(0, n - 1) + '…' : s)
45
46// What an agent is doing, from its latest tool call: "Edit Paywall.swift", "Bash npm test".
47export function toolLabel(tool, input = {}) {
48  const t = String(tool ?? '')
49  const i = input ?? {}
50  if (['Read', 'Edit', 'Write', 'NotebookEdit'].includes(t)) return t + ' ' + base(i.file_path ?? i.notebook_path)
51  if (t === 'Bash') return 'Bash ' + cut(String(i.command ?? '').trim().split(/\s+/).slice(0, 3).join(' '), 28)
52  if (t === 'Grep' || t === 'Glob') return t + ' ' + cut(String(i.pattern ?? ''), 24)
53  if (t === 'WebFetch') return 'Fetch ' + (/^https?:\/\/([^/]+)/.exec(String(i.url ?? ''))?.[1] ?? '')
54  if (t === 'WebSearch') return 'Search ' + cut(String(i.query ?? ''), 24)
55  if (t === 'Agent') return 'Agent ' + cut(String(i.description ?? i.subagent_type ?? ''), 24)
56  if (t === 'Skill') return 'Skill ' + String(i.skill ?? '')
57  if (t === 'TodoWrite') return 'Plan'
58  if (t.startsWith('mcp__')) return t.split('__').slice(2).join(' ')
59  return t
60}
61
62// Which columns fit in `cols` cells of band body.
63export function columns(cols) {
64  const c = Number(cols) || 80
65  return { kind: c >= 92, effort: c >= 78, tok: c >= 68, role: c >= 88 ? 16 : 12 }
66}
67
68// The run's cast in dispatch order. While anything still works, finished subagents of the run
69// stay as dim ✓ rows so the tree reads as the run's history; otherwise `stage` decides.
70export function cast(staged, agents, run) {
71  const rows = [...staged.rows]
72  if (staged.tally.working > 0) {
73    for (const a of agents.values()) if (a.run === run && a.state === 'done' && !rows.includes(a)) rows.push(a)
74  }
75  const at = (r) => (typeof r.start === 'number' ? r.start : Infinity)
76  return rows.sort((a, b) => at(a) - at(b))
77}
78
79const BUSY = new Set(['working'])
80
81// How the engine's agent list reads on a row. waiting and idle replace the spinner of a working
82// agent; failed and killed replace the done mark of a finished one.
83export const LIST_STATUS = {
84  waiting: { glyph: '⏸', word: 'waiting', color: 'warning' },
85  idle: { glyph: '·', word: 'idle', color: 'inactive' },
86  failed: { glyph: '✗', word: 'failed', color: 'error' },
87  killed: { glyph: '✗', word: 'killed', color: 'error' },
88}
89const BROKEN = new Set(['failed', 'killed'])
90// A workflow agent's reason: plain `workflow` when the script ran the table's model, `workflow, table says X · Y`
91// when it did not. Neither is an escalation; the drift reads `≠`, not `↑`.
92const isWorkflow = (reason) => typeof reason === 'string' && reason.startsWith('workflow')
93const isDrift = (reason) => isWorkflow(reason) && reason !== 'workflow'
94const escalation = (reason) => !!reason && reason !== 'table' && !isWorkflow(reason)
95
96// One band row per agent. `wire` maps a pane name to what its worker published (tool, tok, model).
97// `view` is the id of the agent whose transcript is on screen.
98export function boardRows(rows, { now, tick = 0, cols = 80, wire = new Map(), transport = 'pane', view = null } = {}) {
99  const c = columns(cols)
100  return rows.map((r, i) => {
101    const pub = r.kind === 'pane' ? wire.get(r.name) ?? null : null
102    const model = r.model ?? pub?.model ?? null
103    const busy = BUSY.has(r.state)
104    const done = r.kind === 'sub' ? r.state === 'done' : r.state === 'done' || r.state === 'idle'
105    const ls = r.kind === 'sub' ? LIST_STATUS[r.listStatus] : undefined
106    const broken = done && !!ls && BROKEN.has(r.listStatus)
107    const paused = !done && !!ls && !BROKEN.has(r.listStatus)
108    const tool = r.tool ?? pub?.tool ?? null
109    const tok = r.kind === 'sub' ? r.input + r.output : pub?.tok ?? null
110    const start = r.start ?? pub?.start ?? null
111    const kind = r.kind !== 'pane' ? 'sub' : r.vendor && r.vendor !== 'claude' && r.vendor !== 'agent' ? r.vendor : transport
112    let activity
113    if (r.state === 'blocked') activity = '⚑ waiting on you'
114    else if (broken || paused) activity = ls.word
115    else if (done) activity = r.verdict?.text ?? (r.kind === 'sub' ? 'done' : r.state)
116    else if (r.state === 'open') activity = 'open'
117    else activity = tool ?? (escalation(r.reason) ? '↑ ' + r.reason : isDrift(r.reason) ? '≠ ' + r.reason : r.kind === 'pane' ? 'working' : 'thinking')
118    return {
119      id: r.id,
120      name: r.name ?? null,
121      pane: r.kind === 'pane',
122      tree: r.tree ?? (i === rows.length - 1 ? '└─' : '├─'),
123      inView: view != null && r.id === view,
124      glyph: broken ? ls.glyph : done ? DONE_GLYPH : KIND_GLYPH[r.kind] ?? '·',
125      glyphColor: broken || paused ? ls.color : done ? hex(DONE_COLOR) : colorOf(model),
126      role: cut(String(r.role ?? '?'), c.role).padEnd(c.role),
127      kind: c.kind ? String(kind).slice(0, 5).padEnd(5) : null,
128      chip: model ? chip(model) : chip(r.kind === 'sub' ? '?' : r.vendor ?? 'pane'),
129      chipColor: colorOf(model),
130      effort: c.effort ? (effortBar(r.effort) + ' ' + String(r.effort ?? '').slice(0, 4)).padEnd(6) : null,
131      spinner: paused ? ls.glyph : busy ? spin(tick, i) : done ? ' ' : '·',
132      activity,
133      verdict: done && !broken && r.verdict ? (r.verdict.tone === 'success' ? hex(DONE_COLOR) : r.verdict.tone) : null,
134      escalated: escalation(r.reason),
135      reason: r.reason && r.reason !== 'table' && r.reason !== 'workflow' ? r.reason : null,
136      time: start != null && !r.adopted ? elapsed((r.end ?? now) - start).padStart(5) : '     ',
137      tok: c.tok ? (tok != null && !r.adopted ? tokens(tok) : '').padStart(6) : null,
138      dim: done && !broken,
139      busy,
140    }
141  })
142}
143
144// "◆ agentille · run r1 · gauntlet" on the left, "◇2 ▣1 · 50.3k" on the right.
145// The counts and tokens live on the status line under the prompt; the header carries the run's
146// retry loops instead, the one thing no other surface shows.
147export function header({ run, formation = null, squads = [], loops = '' }) {
148  const left = ['run ' + run]
149  if (formation) left.push(formation)
150  if (squads.length) left.push(squads.join('+'))
151  return { left: left.join(' · '), right: loops }
152}
153
154// The tree's root: the lead session itself.
155export function leadLine({ model, busy, waiting }) {
156  const what = busy ? 'orchestrating' : waiting > 0 ? 'waiting on ' + waiting : 'idle'
157  return { text: 'lead · ' + prettyModel(model ?? 'opus'), state: what, color: colorOf(model ?? 'opus') }
158}
159
160// The newest wire message worth a row: ⇄ exec-1 → lead "slice built" 12s.
161// Subagent traffic (`via: 'sub'`) is left to the rows' verdicts and the deck.
162export function wireRow(log, now) {
163  const m = log.findLast((x) => x.via !== 'sub')
164  if (!m || now - m.at > WIRE_SHOW_MS) return null
165  const ago = Math.max(0, Math.round((now - m.at) / 1000))
166  return { arrow: m.from + ' → ' + m.to, text: '"' + cut(m.summary, 60) + '"', ago: ago < 60 ? ago + 's' : Math.floor(ago / 60) + 'm' }
167}
168
169// ── the deck: the optional /agt-deck pane ─────────────────────────────────────
170
171export const CAST_WIDTH = 14
172
173// Mascots side by side, as many as fit `cols`: each a column of five lines (three of mascot,
174// role, model). `frameOf(mood, tick, role)` is mascot.js frame; `moodOf(row)` its mood.
175export function castColumns(rows, { cols, tick = 0, frameOf, moodOf }) {
176  const fit = Math.max(1, Math.floor((Number(cols) || 80) / CAST_WIDTH))
177  const shown = rows.slice(0, fit)
178  return {
179    cells: shown.map((r) => {
180      const mood = moodOf(r)
181      const [head, body, legs] = frameOf(mood, tick, r.kind === 'sub' ? r.role : 'executor')
182      return { lines: [head, body, legs].map((l) => l.padEnd(CAST_WIDTH)), role: cut(String(r.role ?? '?'), CAST_WIDTH - 4), model: r.model ?? null, glyph: r.state === 'done' ? DONE_GLYPH : KIND_GLYPH[r.kind] ?? '·', dim: r.state === 'done' || r.state === 'idle' }
183    }),
184    more: rows.length - shown.length,
185  }
186}
187
188const clock = (iso) => {
189  const d = new Date(iso)
190  return Number.isNaN(d.getTime()) ? '--:--:--' : d.toTimeString().slice(0, 8)
191}
192
193// The routing timeline, newest last: "12:10:04  planner → opus · high  table".
194export function routingLines(decisions, n = 8) {
195  return decisions.slice(-n).map((d) => ({
196    at: clock(d.at),
197    who: cut(String(d.role), 16).padEnd(16) + (d.kind === 'pane' ? ' ▣' : ' ◇'),
198    route: (prettyModel(d.model) + ' · ' + (d.effort ?? '')).padEnd(21),
199    color: colorOf(d.model),
200    reason: escalation(d.reason) ? '↑ ' + d.reason : isDrift(d.reason) ? '≠ ' + d.reason : d.reason === 'workflow' ? 'workflow' : 'table',
201    escalated: escalation(d.reason),
202    drift: isDrift(d.reason),
203  }))
204}
205
206// The run's conversation, newest last: "12:12:01  lead → code-reviewer:api  task  review the api diff".
207export function wireLines(log, n = 12) {
208  return log.slice(-n).map((m) => ({ at: clock(new Date(m.at).toISOString()), arrow: cut(m.from + ' → ' + m.to, 30).padEnd(30), kind: m.kind.padEnd(5), text: cut(m.summary, 70), sub: m.via === 'sub' }))
209}
210
211// Token bars per role from a ledger (live.js), widest first.
212export function tokenBars(l, width = 20) {
213  const roles = Object.entries(l?.roles ?? {}).map(([name, t]) => ({ name, tok: t.input + t.output }))
214  const top = Math.max(1, ...roles.map((r) => r.tok))
215  return roles.sort((a, b) => b.tok - a.tok).slice(0, 8).map((r) => {
216    const fill = Math.max(r.tok > 0 ? 1 : 0, Math.round((r.tok / top) * width))
217    return { name: cut(r.name, 16).padEnd(16), bar: '█'.repeat(fill) + '░'.repeat(width - fill), tok: tokens(r.tok).padStart(6) }
218  })
219}
220
221// ── the swarm line: the whole run in one line, by phase ──────────────────────
222
223export const PHASES = ['plan', 'build', 'review', 'other']
224
225// The phases at work in a run, in order: "build + review". '' when none of the run's own roles
226// works, so a plain subagent spawned after a run still reads as a count.
227export function runPhases(agents, routes, run) {
228  const at = new Set()
229  for (const a of agents.values()) if (a.run === run && a.state === 'working') at.add(phaseOf(a.role))
230  for (const r of routes) if (r.run === run && r.end == null) at.add(phaseOf(r.agent ?? r.role))
231  return PHASES.filter((p) => p !== 'other' && at.has(p)).join(' + ')
232}
233const LANE_CAP = 8 // cells per lane before it reads "+n"
234
235export function phaseOf(role) {
236  const r = String(role ?? '')
237  if (r === 'planner' || r === 'plan-reviewer' || r === 'ui-prototyper') return 'plan'
238  if (r === 'executor' || r === 'adversary') return 'build'
239  if (r.endsWith('-reviewer')) return 'review'
240  return 'other'
241}
242
243// One cell per agent of the run, done ones included, so a run of twelve reads in one line where
244// the tree only has room for a few rows. A working cell pulses (◆/◇, ▣/□) on the ticker, offset
245// per cell; a finished one is a dim ✓, a failed or killed one ✗. Pane workers come from their
246// routes (one per spawn), working until the route ends. Undefined below three agents (the tree
247// already shows that many) and outside an /agt run (`adhoc` is every plain subagent of the session).
248// A lane past LANE_CAP keeps every working and failed cell and fills the rest with the newest
249// finished ones, in start order: the live agent is never the one cut.
250export function swarm({ agents, routes = [], run, tick = 0 }) {
251  if (run === 'adhoc') return undefined
252  const cells = []
253  for (const a of agents.values()) {
254    if (a.run !== run) continue
255    const broken = BROKEN.has(a.listStatus)
256    const working = a.state === 'working' && !broken
257    cells.push({ at: a.start ?? 0, phase: phaseOf(a.role), kind: 'sub', working, broken, model: a.model })
258  }
259  for (const r of routes) {
260    if (r.run !== run) continue
261    cells.push({ at: r.start ?? 0, phase: phaseOf(r.agent ?? r.role), kind: 'pane', working: r.end == null, broken: false, model: r.model })
262  }
263  if (cells.length < 3) return undefined
264  cells.sort((a, b) => a.at - b.at)
265  const lanes = []
266  for (const phase of PHASES) {
267    const mine = cells.filter((c) => c.phase === phase)
268    if (!mine.length) continue
269    const keep = new Set(mine.filter((c) => c.working || c.broken).slice(-LANE_CAP))
270    for (let i = mine.length - 1; i >= 0 && keep.size < LANE_CAP; i--) keep.add(mine[i])
271    const shown = mine.filter((c) => keep.has(c)).map((c, i) => {
272      if (c.broken) return { glyph: '✗', color: 'error', dim: false }
273      if (!c.working) return { glyph: DONE_GLYPH, color: hex(DONE_COLOR), dim: true }
274      const on = (tick + i) % 4 < 2
275      return { glyph: c.kind === 'pane' ? (on ? '▣' : '□') : on ? '◆' : '◇', color: colorOf(c.model), dim: false }
276    })
277    lanes.push({ phase, cells: shown, more: mine.length - shown.length })
278  }
279  return { lanes, done: cells.filter((c) => !c.working).length, total: cells.length }
280}
281
hooks/clean.js 121 lines
1// agentille clean — what to tidy so no run leaves a workspace behind. Pure on purpose:
2// register.js lists panes and worktrees, asks these helpers what goes, and runs the commands.
3//
4//   orphans   — agt-* panes no live lead owns (a lead that died never ran its SessionEnd sweep)
5//   staleTabs — run-tab files of leads that are gone
6//   worktrees — agt/* worktrees this session's runs opened, whose branch is merged with commits of its
7//               own and whose checkout is clean and not just made
8//
9// Nothing that may hold the only copy of work goes: a working or blocked pane, an unmerged
10// branch, a checkout with changes, another session's worktree. Those are listed as kept, with the reason.
11
12export const AGT_BRANCH = 'agt/'
13
14const FINISHED = new Set(['idle', 'done', 'dead'])
15const isAgt = (name) => typeof name === 'string' && name.startsWith('agt-')
16
17// Herdr's agent list → the agt-* panes in no live lead's tab. A lead is any agent pane that is not
18// agt-*; it owns its own tab and the run tabs it recorded (tabsOf(pane id) → tab ids).
19export function herdrOrphans(list, tabsOf = () => []) {
20  const agents = Array.isArray(list) ? list : []
21  const owned = new Set()
22  for (const a of agents) {
23    if (isAgt(a.name) || !a.pane_id) continue
24    if (a.tab_id) owned.add(a.tab_id)
25    for (const t of tabsOf(a.pane_id) ?? []) owned.add(t)
26  }
27  return agents
28    .filter((a) => isAgt(a.name) && a.pane_id && !owned.has(a.tab_id))
29    .map((a) => ({ id: a.pane_id, name: a.name, state: a.agent_status ?? 'unknown' }))
30}
31
32// tmux rows (parseTmuxList) → the agt-* panes in a window with no lead pane. tmux has no idle
33// state: finished(row) says whether the worker is done (its done-file); a dead pane always is.
34export function tmuxOrphans(rows, finished = () => false) {
35  const all = Array.isArray(rows) ? rows : []
36  const led = new Set(all.filter((r) => !isAgt(r.agt)).map((r) => r.window))
37  return all
38    .filter((r) => isAgt(r.agt) && !led.has(r.window))
39    .map((r) => ({ id: r.id, name: r.agt, state: r.dead ? 'dead' : finished(r) ? 'done' : 'working' }))
40}
41
42// Orphans split into the ones to close and the ones kept: a working or blocked pane may still
43// write its answer, so it stays and is named.
44export function orphanPlan(orphans) {
45  const close = []
46  const keep = []
47  for (const o of orphans ?? []) (FINISHED.has(o.state) ? close : keep).push(o)
48  return { close, keep: keep.map((o) => ({ what: o.name, why: o.state })) }
49}
50
51// The lead keys (lead-<key>.tabs) whose lead pane is no longer listed. An empty list proves
52// nothing (herdr may be down), so it never makes a file stale.
53export function staleTabs(keys, list, keyOf) {
54  const agents = Array.isArray(list) ? list : []
55  if (!agents.length) return []
56  const alive = new Set(agents.filter((a) => !isAgt(a.name) && a.pane_id).map((a) => keyOf(a.pane_id)))
57  return (keys ?? []).filter((k) => k && !alive.has(k))
58}
59
60// `git worktree list --porcelain` → [{ path, head, branch, prunable }]; the first entry is the main checkout.
61export function parseWorktrees(stdout) {
62  const out = []
63  let cur = null
64  for (const line of String(stdout ?? '').split('\n')) {
65    if (line.startsWith('worktree ')) out.push((cur = { path: line.slice(9), head: null, branch: null, prunable: false }))
66    else if (!cur) continue
67    else if (line.startsWith('HEAD ')) cur.head = line.slice(5)
68    else if (line.startsWith('branch refs/heads/')) cur.branch = line.slice(18)
69    else if (line.startsWith('prunable')) cur.prunable = true
70  }
71  return out
72}
73
74// Which agt/* worktrees and branches go. merged: branch names merged into the base or HEAD.
75// dirty: worktree paths with uncommitted or untracked files. owned(t): this session's runs opened the
76// tree or branch (t is { path, branch }); with no owned, nothing goes. empty: tree paths whose branch has
77// no commits of its own (its tip is still where it forked, or the base's). fresh: tree paths made under
78// FRESH_MS ago. A branch still checked out in a worktree that stays is never deleted.
79export const FRESH_MS = 10 * 60_000
80
81export function worktreePlan(trees, merged, dirty, branches = [], { owned = () => false, empty = new Set(), fresh = new Set() } = {}) {
82  const remove = []
83  const keep = []
84  const held = new Set()
85  for (const t of (trees ?? []).slice(1)) {
86    if (!t.branch?.startsWith(AGT_BRANCH) || t.prunable) {
87      if (t.branch) held.add(t.branch)
88      continue
89    }
90    if (!owned(t)) keep.push({ what: t.branch, why: 'not opened by this session' })
91    else if (!merged.has(t.branch)) keep.push({ what: t.branch, why: 'not merged' })
92    else if (dirty.has(t.path)) keep.push({ what: t.branch, why: 'uncommitted changes' })
93    else if (empty.has(t.path)) keep.push({ what: t.branch, why: 'no commits of its own' })
94    else if (fresh.has(t.path)) keep.push({ what: t.branch, why: 'opened under 10 min ago' })
95    else {
96      remove.push(t)
97      continue
98    }
99    held.add(t.branch)
100  }
101  const main = trees?.[0]?.branch
102  const deleteBranches = branches.filter((b) => b.startsWith(AGT_BRANCH) && merged.has(b) && !held.has(b) && b !== main && owned({ path: null, branch: b }))
103  return { remove, deleteBranches, keep, prune: (trees ?? []).some((t) => t.prunable) }
104}
105
106const plural = (n, one, many = one + 's') => n + ' ' + (n === 1 ? one : many)
107
108// The cleaner's report: one line of what went, one of what stayed.
109export function cleanText({ closed = [], tabs = 0, removed = [], branches = [], runs = 0, keep = [] }) {
110  const did = [
111    closed.length && plural(closed.length, 'pane') + ' closed',
112    removed.length && plural(removed.length, 'worktree') + ' removed',
113    branches.length && plural(branches.length, 'branch', 'branches') + ' deleted',
114    tabs && plural(tabs, 'stale tab file') + ' dropped',
115    runs && plural(runs, 'old run folder') + ' dropped',
116  ].filter(Boolean)
117  const head = did.length ? 'agt clean · ' + did.join(' · ') : 'agt clean · workspace already clean'
118  if (!keep.length) return head
119  return head + '\nkept: ' + keep.slice(0, 6).map((k) => k.what + ' (' + k.why + ')').join(' · ') + (keep.length > 6 ? ' · +' + (keep.length - 6) + ' more' : '')
120}
121
hooks/dispatch.js 441 lines
1// agentille run bookkeeping: per-run counters, the routing log and ledger under ~/.agentille/state/run-<id>/,
2// each subagent's raw report, and the Agents section the mod adds to a finished report.md.
3
4import { Session, ctx, ctxSource, isLead } from './session.js'
5import { Profile } from './profile.js'
6import { makeStore } from './store.js'
7import { reportRun, reportTail } from './drawing.js'
8import { sliceOf, party, taskLine } from './links.js'
9import { newAgent, short, ledger, ledgerText, addUsage, finish, endRoute } from './live.js'
10import { SAFE_RUN, splitName } from './panes.js'
11import { formationOf, roleOf, parseHeader, proveHeader, demoteHeaderText, ladderFixes, decide, executorsWorking, executorCapFlag, executorCapDeny, estimateRunUsd, leadUsd, maxRunUsdOf, usd } from './routing.js'
12import { addFlag } from './display.js'
13import { emit } from './bus.js'
14import { Proofs, agtTurnFromDispatch } from './proofs.js'
15import { adopt, applyStatus, quietWorkflows } from './tree.js'
16
17// The run bookkeeping store: the run the band follows, each run's counters and routing log, every agent this session
18// has seen, the dispatch decisions and the pane routes. Read through the Runs view; written only here.
19const { s: my, view, raw } = makeStore('dispatch.js', {
20  lastRun: 'adhoc',
21  runs: new Map(),  // run id → { revise, fixes, fable, formation, log: [], reports: { role → count } }
22  live: new Map(),  // agentId → live agent (live.js)
23  decisions: [],  // this session, for /agt-info routing
24  paneRoutes: [],  // PaneRoute[], append-only: how each worker this lead opened was routed
25  sessionRun: null,  // the run session-<session id>.run names (markRun)
26  lead: new Map(),  // run id → { input, output, cacheRead, model }: the lead's own main-loop tokens on that run
27  leadPending: null,  // { at, input, output, cacheRead, model }: the typed /agt's tokens before its run had an id
28})
29export const Runs = view
30ctxSource({ runs: view })
31const wfToasted = new Set()  // run:role pairs whose drift the person was told once
32const demotedToasted = new Set()  // run ids told once that fable=forced was dropped for want of a typed --fable
33const execPending = new Map()  // run id → executor dispatches past the cap check and not yet in the live map
34
35// The band follows this run (a pane opened for it, or a routed dispatch named it).
36export function setLastRun(id) {
37  my.lastRun = id
38}
39
40// A worker pane this lead opened, and how it was routed.
41export function addRoute(route) {
42  my.paneRoutes.push(route)
43}
44
45// A dispatch decision, for /agt-info routing.
46export function addDecision(rec) {
47  my.decisions.push(rec)
48}
49
50// The engine's agent list names agents the map has not seen (a reload, a foreign spawn): they join the band's run.
51export function adoptAgents(list, now) {
52  return adopt(my.live, list, { run: my.lastRun, now })
53}
54
55// The list's view of each known agent folds into its record (tree.js applyStatus). Returns whether anything changed.
56export function applyAgentList(list, now) {
57  return applyStatus(my.live, list, now)
58}
59
60// Every working workflow agent silent too long is finished (tree.js quietWorkflows). Returns whether any was.
61export function quietAgents(now) {
62  return quietWorkflows(my.live, now)
63}
64
65const agentOf = (id) => (id == null ? undefined : my.live.get(id))
66
67// A subagent called a tool: its band row shows the call, and it was heard from now. False when no agent has the id.
68export function noteAgentTool(id, label) {
69  const a = agentOf(id)
70  if (!a) return false
71  a.tool = label
72  a.heard = Date.now()
73  return true
74}
75
76// A workflow agent inside one long call (a full test suite) is alive: tree.js quietWorkflows skips it while a call
77// is open, and the return counts as heard.
78export function enterAgentCall(id) {
79  const a = agentOf(id)
80  if (a) a.calls = (a.calls ?? 0) + 1
81}
82
83export function leaveAgentCall(id) {
84  const a = agentOf(id)
85  if (!a) return
86  a.calls -= 1
87  a.heard = Date.now()
88}
89
90// A subagent's model step ended: it was heard from, the effort and model it ran on fill in when none was known, and
91// its tokens count. False when no agent has the id.
92export function noteAgentStep(id, { effort, model, usage } = {}) {
93  const a = agentOf(id)
94  if (!a) return false
95  a.heard = Date.now()
96  if (!a.effort && effort) a.effort = String(effort)
97  if (!a.model && model) a.model = model
98  addUsage(a, usage)
99  return true
100}
101
102// A subagent's turn ended: its tool clears, its verdict chip is set, its tokens count if no step counted them, and
103// it is done.
104export function agentDone(id, { verdict, usage, now, durationMs }) {
105  const a = agentOf(id)
106  if (!a) return
107  a.tool = null
108  a.verdict = verdict
109  if (a.input + a.output === 0) addUsage(a, usage)
110  finish(a, now, durationMs)
111}
112
113// A worker pane's done message: its newest route takes the verdict chip.
114export function setRouteVerdict(name, verdict) {
115  const r = my.paneRoutes.findLast((x) => x.name === name)
116  if (r) r.verdict = verdict
117}
118
119// A pane left the stage: its newest open route ends now. Returns that route's run, or null when none was open.
120export function endPaneRoute(name, now) {
121  return endRoute(my.paneRoutes, name, now)?.run ?? null
122}
123
124// A workflow agent is in no agent list, and a cancelled one raises no turn.complete: it is marked,
125// and every event of its loop says it is still alive (tree.js quietWorkflows ends a silent one).
126export function heard(a, e) {
127  if (e.workflow) a.workflow = e.workflow.runId || true
128  a.heard = Date.now()
129  return a
130}
131
132// Once per run: the model wrote fable=forced, nobody typed --fable, so the ladder applies.
133export function demoteToast($, run) {
134  if (demotedToasted.has(run)) return
135  demotedToasted.add(run)
136  $.ui.toast('agt ⚑ fable=forced dropped: --fable was not typed, the ladder applies')
137}
138
139// Once per run: the maxRunUsd ceiling was reached and the first dispatch (subagent or pane) was demoted. One toast and
140// a band ⚑ line that name what was demoted and what follows; every later demotion shows only in the routing log
141// (`capped: true`). A typed --fable passes the ceiling (`pastCeiling`): the first one past it in a run gets its own
142// toast and ⚑ line saying so, every later one shows in the routing log (`pastCeiling: true`). Returns whether it told.
143export function ceilingOnce($, runId, spent, role, d) {
144  const run = runRec(runId)
145  const max = usd(maxRunUsdOf(Profile.settings))
146  if (d.pastCeiling) {
147    if (run.fableCeilingToasted) return false
148    run.fableCeilingToasted = true
149    addFlag($, 'ceiling-fable|' + runId, 'run ' + runId + ': ~' + usd(spent) + ' spent, past maxRunUsd ' + max + '; ' + role + ' runs Fable anyway, since a typed --fable passes the ceiling')
150    return true
151  }
152  if (run.ceilingToasted) return false
153  run.ceilingToasted = true
154  addFlag($, 'ceiling|' + runId, 'run ' + runId + ': ~' + usd(spent) + ' spent, past maxRunUsd ' + max + '; ' + role + ' ' + (d.from ?? 'opus') + ' → sonnet, and every later Opus or Fable planner, reviewer, ui-prototyper and adversary runs Sonnet (the executor keeps its route)')
155  return true
156}
157
158// One main-loop step of the lead (turn.step with no agentId): its tokens count toward the run it works on. Only a
159// turn that is part of an /agt run counts. Until the typed /agt names its run (its first pane or routed dispatch),
160// its steps wait in leadPending, keyed by the typed /agt's clock; the first step after the run has an id files them
161// under it. A newer typed /agt drops what an older one left pending. `p` is the proof state (Proofs by default).
162export function addLeadUsage(u, model, p = Proofs) {
163  if (!u || !p.agtTurn) return
164  const add = (t) => {
165    t.input += (u.input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
166    t.output += u.output_tokens ?? 0
167    t.cacheRead += u.cache_read_input_tokens ?? 0
168    if (model) t.model = model
169  }
170  const fresh = () => ({ input: 0, output: 0, cacheRead: 0, model: model ?? null })
171  const run = SAFE_RUN.test(String(p.agtRun ?? '')) && p.agtRun !== 'adhoc' ? p.agtRun : null
172  if (!run) {
173    if (my.leadPending?.at !== p.agtTypedAt) my.leadPending = { at: p.agtTypedAt, ...fresh() }
174    add(my.leadPending)
175    return
176  }
177  if (!my.lead.has(run)) my.lead.set(run, fresh())
178  const t = my.lead.get(run)
179  if (my.leadPending && my.leadPending.at === p.agtTypedAt) {
180    t.input += my.leadPending.input
181    t.output += my.leadPending.output
182    t.cacheRead += my.leadPending.cacheRead
183    t.model ??= my.leadPending.model
184  }
185  my.leadPending = null
186  add(t)
187}
188
189// The run's spend so far for the ceiling, subagents, pane workers and the lead's own tokens alike, or null when no
190// ceiling is set.
191export function runSpend(runId) {
192  return maxRunUsdOf(Profile.settings) == null ? null : estimateRunUsd(my.live, runId, my.paneRoutes, Date.now(), my.lead)
193}
194
195// A run's counters, made on first use. runRec is this module's writable record; runState is the read view of it.
196function runRec(id) {
197  if (!my.runs.has(id)) my.runs.set(id, { revise: 0, fixes: 0, fixesBySlice: {}, fable: 0, formation: null, log: [], reports: {} })
198  return my.runs.get(id)
199}
200
201export function runState(id) {
202  runRec(id)
203  return view.runs.get(id)
204}
205
206// The run's formation, when this dispatch's header names one.
207export function noteFormation(id, hdr) {
208  const run = runRec(id)
209  run.formation = formationOf(hdr) ?? run.formation
210}
211
212// A plan-reviewer said REVISE.
213export function countRevise(id) {
214  runRec(id).revise += 1
215}
216
217// One more fix round, for the run and for its slice ('' = no slice): the ladder reads the slice's rounds.
218export function countFix(id, slice) {
219  const run = runRec(id)
220  const key = slice ?? ''
221  run.fixes += 1
222  run.fixesBySlice[key] = (run.fixesBySlice[key] ?? 0) + 1
223}
224
225// The run's Fable count is shared across sessions through $.store: take the higher of the two before a pick,
226// and write the new count back after a Fable dispatch.
227export async function syncFable($, id) {
228  const run = runRec(id)
229  run.fable = Math.max(run.fable, Number((await $.store.get('fable:' + id)) ?? 0))
230  return run.fable
231}
232
233export async function countFable($, id) {
234  const run = runRec(id)
235  run.fable += 1
236  await $.store.set('fable:' + id, run.fable)
237}
238
239// A dispatch decision goes to /agt-info routing and to the run's routing log, which is written out whole.
240export async function logDecision($, id, rec) {
241  my.decisions.push(rec)
242  const run = runRec(id)
243  run.log.push(JSON.stringify(rec))
244  await writeRunFile($, id, 'routing.jsonl', run.log.join('\n') + '\n')
245}
246
247export function shortType(t) {
248  return String(t ?? 'agent').split(':').pop()
249}
250
251export function routingView() {
252  if (my.decisions.length === 0) return 'No agentille dispatches this session.'
253  return my.decisions.slice(-30).map((d) => d.role + ' → ' + d.model + (d.effort ? ' · ' + d.effort : '') + (d.reason === 'table' ? '' : '  (' + d.reason + ')') + (d.kind === 'pane' ? ' · pane' : '')).join('\n')
254}
255
256export function ledgerView() {
257  const text = ledgerText(ledger(my.live, my.lastRun, my.paneRoutes))
258  const max = maxRunUsdOf(Profile.settings)
259  return max == null ? text : text + '\nestimate ~' + usd(estimateRunUsd(my.live, my.lastRun, my.paneRoutes, Date.now(), my.lead)) + ' of maxRunUsd ' + usd(max) + ', lead ~' + usd(leadUsd(my.lead, my.lastRun)) + ' of it (list prices; pane workers estimated from their minutes open)'
260}
261
262export async function writeRunFile($, runId, name, text) {
263  if (!Profile.home || !SAFE_RUN.test(runId) || runId === 'adhoc') return
264  try {
265    await $.fs.write(Profile.home + '/.agentille/state/run-' + runId + '/' + name, text)
266  } catch {
267    // the run dir is the orchestrator's; logging never blocks a dispatch
268  }
269}
270
271// A lead names the run it dispatches for in ~/.agentille/state/session-<session id>.run, written once per run, and
272// refreshes the run's ledger.json, so the ledger lists each slice from its first dispatch. The SessionStart hook for
273// a compaction (agentille-compact.sh) reads both to print where the run stands.
274export async function markRun($, runId) {
275  if (!isLead() || !Profile.home || !SAFE_RUN.test(runId) || runId === 'adhoc') return
276  await writeRunFile($, runId, 'ledger.json', JSON.stringify(ledger(my.live, runId, my.paneRoutes), null, 2) + '\n')
277  if (!Session.sessionId || my.sessionRun === runId) return
278  try {
279    await $.fs.write(Profile.home + '/.agentille/state/session-' + Session.sessionId + '.run', runId + '\n')
280    my.sessionRun = runId
281  } catch {
282    // the hook then prints nothing; a dispatch never waits on it
283  }
284}
285
286// A subagent's raw answer goes to run-<id>/agents/<role>-<n>.md, written here so the lead spends
287// no tokens copying it. n counts per role in the run; a second turn of the same agent overwrites.
288export async function writeReport($, a, answer) {
289  a = raw(a) // read through the Runs view by the caller: the report name is written on the record itself
290  if (!a?.routed || !answer) return
291  const counts = runRec(a.run).reports
292  a.report ??= a.role + '-' + (counts[a.role] = (counts[a.role] ?? 0) + 1) + '.md'
293  await writeRunFile($, a.run, 'agents/' + a.report, answer)
294}
295
296// The run an agent's files and counters belong to: a headerless workflow agent files under 'adhoc'.
297export const fileRunOf = (a) => a.fileRun ?? a.run
298
299// /agt writes report.md once at the end; the mod adds the Agents and Raw reports sections it lacks.
300export async function completeReport($, path) {
301  const run = reportRun(path)
302  if (!run || !Profile.home) return
303  const dir = Profile.home + '/.agentille/state/run-' + run
304  if (path !== dir + '/report.md') return
305  try {
306    const text = await $.fs.read(path)
307    const files = (await $.fs.list(dir + '/agents').catch(() => [])).filter((f) => f.kind !== 'dir' && f.name.endsWith('.md')).map((f) => f.name)
308    const agents = [...my.live.values()].filter((a) => fileRunOf(a) === run)
309    const tail = reportTail(text, { agents, routes: my.paneRoutes.filter((r) => r.run === run), files })
310    if (tail) await $.fs.write(path, text + tail)
311  } catch {
312    // the report is the lead's; a missing section never fails its Write
313  }
314}
315
316// The one line a workflow agent is refused with when its script names another model than the routed pick.
317export function workflowModelDeny(role, asked, d) {
318  return 'agt ✗ workflow ' + role + ' asks ' + asked + ', routed ' + d.model + ' · ' + d.effort + ': the mod cannot rewrite a workflow agent\'s model, so it is refused. Set model "' + d.model + '" on this ' + role + ' in the workflow script and run it again.'
319}
320
321// Every Agent dispatch of an agentille role: the header is proved, the model rewritten by the table and the
322// ladder, the run's counters moved, the routing logged. A foreign subagent is only watched: for the band, its
323// transcript row (display.rows) and the spinner's count (display.spinner).
324export async function dispatchAgent($, e, next) {
325  if (e.fork) return next(e)
326  const role = roleOf(e.subagentType)
327
328  if (!role) {
329    const res = await next(e)
330    if (res.agentId) my.live.set(res.agentId, heard(newAgent({ id: res.agentId, role: shortType(e.subagentType), routed: false, model: res.model, effort: null, reason: null, run: my.lastRun, now: Date.now(), parentId: e.parentAgentId ?? null }), e))
331    $.ui.invalidate('ui.render')
332    return res
333  }
334
335  const proof = proveHeader(parseHeader(e.prompt) ?? {}, { fableTyped: Proofs.fableTyped })
336  const hdr = proof.hdr
337  if (proof.demoted) {
338    e = { ...e, prompt: demoteHeaderText(e.prompt) }
339    demoteToast($, SAFE_RUN.test(hdr.run ?? '') ? hdr.run : my.lastRun)
340  }
341  // A workflow script's agent: the engine ignores a model rewrite there (and logs a failure line), so it runs on the
342  // model the script chose, and the lead must name the routed model in the script. A deny does hold there, so the
343  // run's stop (stopAtCeiling, stopAtWeeklyPct) is enforced and a script naming another model than the routed pick is
344  // refused. One that names none runs the engine's default; log the model it ran, not the table's, and flag a drift.
345  if (e.workflow) {
346    // Its prompt may carry no header: it then joins the run in progress rather than reset it. A header
347    // names its run, but the band moves to it only when the current run has nothing working, subagent or pane.
348    const named = SAFE_RUN.test(hdr.run ?? '') ? hdr.run : null
349    const runId = named ?? my.lastRun
350    // Its files and counters follow the header: a headerless agent files under 'adhoc' (which writes
351    // nothing), so the run in progress keeps only its own routing log and ledger.
352    const fileRun = named ?? 'adhoc'
353    const busy = [...my.live.values()].some((a) => a.run === my.lastRun && a.state === 'working') || ctx.panes.some((p) => splitName(p.name)?.run === my.lastRun && p.state === 'working')
354    if (named && (my.lastRun === 'adhoc' || !busy)) my.lastRun = named
355    agtTurnFromDispatch()
356    // The table pick and the spend follow the run in progress (its REVISEs, its agents); `fileRun` is only where the
357    // log goes. The spend is counted as on the subagent path, so the ceiling and the stop see the same estimate.
358    const spent = runSpend(runId)
359    const d = decide({ role, hdr, run: { ...runRec(runId), fixes: ladderFixes(runRec(runId), sliceOf(hdr)), usd: spent }, depth: Profile.depth, settings: Profile.settings, weeklyPct: Session.weeklyPct })
360    // The run is stopped: the workflow agent is refused before it reaches the engine, whatever the role.
361    if (d.stop) return { deny: d.stop }
362    // A model the script names (`inherit` is the lead's) must be the routed one: refused before the engine runs it.
363    const asked = e.model === 'inherit' ? e.parentModel : e.model
364    if (asked && short(asked) !== short(d.model)) return { deny: workflowModelDeny(role, e.model === 'inherit' ? 'inherit (' + short(asked) + ')' : e.model, d) }
365    const res = await next(e)
366    if (res.deny) return res
367    const off = short(res.model) !== short(d.model)
368    const unnamed = asked ? '' : ', no model named: engine default ' + short(res.model)
369    const drift = 'workflow' + unnamed + (off ? ', table says ' + d.model + ' · ' + d.effort : '')
370    if (res.agentId) {
371      const a = heard(newAgent({ id: res.agentId, role, routed: false, model: res.model, effort: null, reason: off ? drift : null, run: runId, now: Date.now(), parentId: e.parentAgentId ?? null }), e)
372      a.fileRun = fileRun
373      a.slice = sliceOf(hdr)
374      my.live.set(res.agentId, a)
375    }
376    const rec = { at: new Date().toISOString(), role, model: res.model, effort: null, reason: drift, asked: e.model ?? null, agentId: res.agentId ?? null, kind: 'workflow' }
377    await logDecision($, fileRun, rec)
378    if (off && !wfToasted.has(runId + ':' + role)) {
379      wfToasted.add(runId + ':' + role)
380      $.ui.toast('agt workflow ' + role + ' runs ' + short(res.model) + ' — table says ' + d.model + ' · ' + d.effort)
381    }
382    $.ui.invalidate('ui.render')
383    return res
384  }
385
386  const runId = SAFE_RUN.test(hdr.run ?? '') ? hdr.run : 'adhoc'
387  agtTurnFromDispatch()
388  my.lastRun = runId
389  const run = runRec(runId)
390  // At most 3 executors at once: counted before this one joins, subagents, the run's executor panes and the
391  // dispatches still on their way to the engine alike (parallel Agent calls all reach this point before any joins).
392  // The one past the cap is refused before it counts a fix round, and flagged on the band.
393  const capped = role === 'executor' && runId !== 'adhoc'
394  if (capped) {
395    const count = executorsWorking(my.live, my.paneRoutes, runId) + (execPending.get(runId) ?? 0) + 1
396    const cap = executorCapFlag(runId, count)
397    if (cap) {
398      addFlag($, 'cap|' + runId, cap) // the band's ⚑ line and one toast
399      return { deny: executorCapDeny(runId, count) }
400    }
401    execPending.set(runId, (execPending.get(runId) ?? 0) + 1)
402  }
403  let pending = capped
404  const settle = () => {
405    if (!pending) return
406    pending = false
407    const left = (execPending.get(runId) ?? 1) - 1
408    if (left > 0) execPending.set(runId, left)
409    else execPending.delete(runId)
410  }
411  try {
412    noteFormation(runId, hdr)
413    if (role === 'executor' && hdr.mode === 'fix') countFix(runId, sliceOf(hdr))
414    await syncFable($, runId)
415
416    // The run's spend so far, estimated from its agents' tokens and its panes' minutes, only when a ceiling is set.
417    const spent = runSpend(runId)
418    const d = decide({ role, hdr, run: { ...run, fixes: ladderFixes(run, sliceOf(hdr)), usd: spent }, depth: Profile.depth, settings: Profile.settings, weeklyPct: Session.weeklyPct })
419    // routing.stopAtCeiling or stopAtWeeklyPct: the run is stopped, so nothing more is dispatched, whatever the role.
420    if (d.stop) return { deny: d.stop }
421    const res = await next({ ...e, model: d.model })
422    if (res.deny) return res
423
424    if (d.fable) await countFable($, runId)
425    const slice = sliceOf(hdr)
426    settle() // from here the live map counts it
427    if (res.agentId) my.live.set(res.agentId, { ...newAgent({ id: res.agentId, role, routed: true, model: res.model, effort: d.effort, reason: d.reason, run: runId, now: Date.now(), parentId: e.parentAgentId ?? null }), slice })
428    if (runId !== 'adhoc') emit('wire.note', { from: 'lead', to: party(role, slice), kind: 'task', summary: taskLine(e.prompt) || role, at: Date.now(), via: 'sub' })
429    const rec = { at: new Date().toISOString(), role, model: res.model, effort: d.effort, reason: d.reason, asked: e.model ?? null, agentId: res.agentId ?? null, ...(d.capped && { capped: true }), ...(d.pastCeiling && { pastCeiling: true }) }
430    await logDecision($, runId, rec)
431    await markRun($, runId)
432    // A demotion or a typed --fable past the ceiling is told once per run; a later typed --fable toasts like any pick.
433    const told = d.capped || d.pastCeiling ? ceilingOnce($, runId, spent, role, d) : false
434    if (!told && !d.capped && d.reason !== 'table') $.ui.toast('agt ↑ ' + role + ' → ' + short(res.model) + ' · ' + d.effort + ' — ' + d.reason)
435    $.ui.invalidate('ui.render')
436    return res
437  } finally {
438    settle()
439  }
440}
441
hooks/display.js 236 lines
1// agentille display: the display settings (deck, focus, highlight, band, statusLine, mascot, rows, spinner) read from
2// profile.json or the mod store and written back, the agent flags above the prompt, and the memo of which message closed an answer.
3
4import { Profile } from './profile.js'
5import { ctx } from './session.js'
6import { makeStore } from './store.js'
7import { on } from './bus.js'
8import { mergeFlags, paneFlags, parseFocusArgs, focusText } from './focus.js'
9import { isAnswerBlock, panel, parseHighlightArgs, highlightText } from './highlight.js'
10import { PROBE } from './panes.js'
11import { cleanDisplay, storedDisplay, resolveDisplay, highlightFlags, withDisplay, profileJson } from './settings.js'
12import { strandedNow } from './panerec.js'
13import { HELLO_MS, BYE_MS } from './mascot.js'
14
15// The display's store: the settings in effect and where each came from, the live switches they set, the agent flags
16// above the prompt, the newest answer and the memo of which message closed one, and the worker band's mascot. Read
17// through the Display view; written only by the transitions below.
18const { s: my, view } = makeStore('display.js', {
19  display: resolveDisplay({}, {}),  // the display settings in effect, and where each came from
20  profileDisplay: {},  // the valid keys of ~/.agentille/profile.json → display
21  storedRaw: {},  // the old $.store toggles, read once at session start (back-compat)
22  deckAuto: false,  // display.deck = auto: the deck opens on every typed /agt
23  focusOn: true,  // agent flags show above the prompt
24  highlightOn: false,  // /agt replies get an essentials card and lit tokens (display.highlight: on | all)
25  highlightAll: false,  // …and so does every other long reply (/agt-highlight all)
26  bandOn: true,  // display.band: the switchboard above the prompt draws
27  statusOn: true,  // display.statusLine: the agt status line under the prompt is pinned
28  mascotOn: true,  // display.mascot: the mascot figure draws in a worker's band and the deck's cast
29  rowsOn: true,  // display.rows: an Agent call, and a Workflow call's agents, draw as live rows in the transcript
30  spinnerOn: true,  // display.spinner: the main spinner gets the working-agents suffix
31  flags: [],  // [{ text, key, at }] from agent results this run
32  lastAnswer: null,  // { text, ms, id, shaped, raw } of the newest main-turn answer; its closing block draws as the panel
33  panelMemo: new Map(),  // message id → { text, panel() result }: the blocks that closed a main turn's answer
34  rawIds: new Set(),  // message ids that closed a raw answer: they draw as the engine does
35  mascot: { greeted: false, hiUntil: 0, byeUntil: 0, working: false, start: 0, ms: null },  // worker band, in $.clock.now() ms
36})
37export const Display = view
38
39// profile.json → display, as loadProfile read it. profile.js reaches it through the bus, since this file reads Profile.
40export function setProfileDisplay(d) {
41  my.profileDisplay = d
42}
43on('profile.display', setProfileDisplay)
44
45// The old $.store toggles, read once at session start.
46export function setStoredRaw(raw) {
47  my.storedRaw = raw
48}
49
50// The newest main-turn answer (null when a main turn starts).
51export function setLastAnswer(a) {
52  my.lastAnswer = a
53}
54
55// A run's flags come down: a new /agt run, or its ✓/✗ card.
56export function clearFlags() {
57  my.flags = []
58}
59
60// The worker band's mascot: hello on the first main turn (true only then), working while a turn runs, and a wave
61// when it ends on an answer.
62export function mascotHello(now) {
63  if (my.mascot.greeted) return false
64  my.mascot.greeted = true
65  my.mascot.hiUntil = now + HELLO_MS
66  return true
67}
68export function mascotWorking(now) {
69  my.mascot.working = true
70  my.mascot.start = now
71}
72export function mascotRest(now, waved) {
73  my.mascot.working = false
74  my.mascot.ms = now - my.mascot.start
75  if (waved) my.mascot.byeUntil = now + BYE_MS
76}
77
78export const DECK = 'agt-deck'
79
80export const FLAG_TTL_MS = 30 * 60_000
81
82// profile.display → old store value → default, applied to the live switches.
83export function applyDisplay() {
84  my.display = resolveDisplay(my.profileDisplay, storedDisplay(my.storedRaw))
85  my.deckAuto = my.display.values.deck === 'auto'
86  my.focusOn = my.display.values.focus
87  const h = highlightFlags(my.display.values.highlight)
88  my.highlightOn = h.on
89  my.highlightAll = h.all
90  my.bandOn = my.display.values.band !== 'off'
91  my.statusOn = my.display.values.statusLine !== 'off'
92  my.mascotOn = my.display.values.mascot !== 'off'
93  my.rowsOn = my.display.values.rows !== 'off'
94  my.spinnerOn = my.display.values.spinner !== 'off'
95}
96
97export const PROFILE_FILE = '/.agentille/profile.json'
98
99// Read-merge-write one display key into ~/.agentille/profile.json: every other key stays, 2-space
100// indent, trailing newline. The old file is copied to profile.json.bak first; a host without $.process
101// still works once ~/.agentille exists.
102// → null on success, else why not.
103export async function saveDisplay($, key, value) {
104  if (!Profile.home) return 'no home folder'
105  const path = Profile.home + PROFILE_FILE
106  const shown = '~' + PROFILE_FILE
107  let profile = null
108  let text = null
109  try {
110    text = await $.fs.read(path)
111  } catch {
112    // unreadable is not missing: a file we cannot read is the person's, and a write would replace it
113    if (await $.fs.exists(path).catch(() => true)) return shown + ' is unreadable'
114  }
115  if (text !== null) {
116    try { profile = JSON.parse(text) } catch { return shown + ' is not valid JSON' }
117    if (profile === null || typeof profile !== 'object' || Array.isArray(profile)) return shown + ' is not a JSON object'
118    try { await $.fs.write(path + '.bak', text) } catch { return 'could not back up ' + shown }
119  }
120  const next = withDisplay(profile, key, value)
121  const body = profileJson(next)
122  // With $.process: make the folder, write a .tmp beside the file and mv it over (no torn write).
123  // Without it, or when mv fails: write the file directly; the .bak above is the way back.
124  let made = null
125  try { made = (await $.process.run(['mkdir', '-p', Profile.home + '/.agentille'], PROBE)).exitCode } catch { /* no $.process on this host */ }
126  if (made === 0) {
127    try {
128      await $.fs.write(path + '.tmp', body)
129      if ((await $.process.run(['mv', '-f', path + '.tmp', path], PROBE)).exitCode === 0) made = 'moved'
130    } catch { /* the direct write below */ }
131  }
132  if (made !== 'moved') {
133    try {
134      await $.fs.write(path, body)
135    } catch {
136      return made !== null && made !== 0 ? 'could not create ~/.agentille' : 'could not write ' + shown
137    }
138  }
139  my.profileDisplay = cleanDisplay(next.display)
140  applyDisplay()
141  return null
142}
143
144// A toggle: profile.json when it can be written, else the mod store as before. Always applied now.
145// → '' when saved in profile.json, else the one line saying where it went.
146export async function setDisplay($, key, value) {
147  const why = await saveDisplay($, key, value)
148  if (!why) return ''
149  const sets =
150    key === 'deck' ? { deckAuto: value === 'auto' } :
151    key === 'focus' ? { focusMode: value ? 'on' : 'off' } :
152    { highlightOn: value !== 'off', highlightAll: value === 'all' }
153  const names = { deckAuto: 'deck:auto', focusMode: 'focus:mode', highlightOn: 'highlight:on', highlightAll: 'highlight:all' }
154  const profileWins = Object.hasOwn(my.profileDisplay, key) // a profile value comes back next session
155  my.storedRaw = { ...my.storedRaw, ...sets }
156  delete my.profileDisplay[key]
157  applyDisplay()
158  try {
159    for (const [k, v] of Object.entries(sets)) await $.store.set(names[k], v)
160  } catch {
161    return 'applied for this session only: ' + why + ' and the mod store refused it'
162  }
163  if (profileWins) return 'applied for this session only: ' + why + ', and display.' + key + ' in profile.json wins next session'
164  return "saved in this machine's mod store, not in profile.json: " + why
165}
166
167export const MOVED = (key) => '\nmoved: display.' + key + ' in ~/.agentille/profile.json — this command is deprecated; removed in 4.0.0'
168
169export function addFlag($, key, text) {
170  my.flags = mergeFlags(my.flags, key, text, Date.now(), FLAG_TTL_MS)
171  if (text) $.ui.toast('agt ⚑ ' + text)
172}
173
174export function focusLines(now) {
175  if (!my.focusOn) return []
176  const fresh = [...new Set(my.flags.filter((f) => now - f.at < FLAG_TTL_MS).map((f) => f.text))]
177  return [...fresh, ...paneFlags(ctx.panes, strandedNow)].slice(0, 5)
178}
179
180// The panel for a message id, once it is known to close the newest answer; kept per id after that.
181export function answerPanel(id, text) {
182  if (!id || typeof text !== 'string') return null
183  const hit = my.panelMemo.get(id)
184  if (hit && hit.text === text) return hit.p
185  if (!hit && !(my.lastAnswer && (my.lastAnswer.id === id || (!my.lastAnswer.id && isAnswerBlock(my.lastAnswer.text, text))))) return null
186  if (my.lastAnswer && !my.lastAnswer.id && !hit) my.lastAnswer.id = id
187  const own = my.lastAnswer?.id === id
188  if (own && my.lastAnswer.raw) {
189    my.rawIds.add(id)
190    if (my.rawIds.size > 200) my.rawIds.delete(my.rawIds.values().next().value)
191    return null
192  }
193  const p = panel(text, { ms: own ? my.lastAnswer.ms : undefined, shaped: own ? my.lastAnswer.shaped : false })
194  my.panelMemo.delete(id)
195  my.panelMemo.set(id, { text, p })
196  if (my.panelMemo.size > 200) my.panelMemo.delete(my.panelMemo.keys().next().value)
197  return p
198}
199
200export async function deckCommand($, e) {
201  const a = String(e.args ?? '').trim().toLowerCase()
202  if (a && a !== 'auto' && a !== 'off') return { text: 'Usage: /agt-deck [auto|off]' }
203  let note = ''
204  if (a) {
205    note = await setDisplay($, 'deck', a)
206    if (!my.deckAuto) return { text: 'deck: opens only when you type /agt-deck (display.deck: off)' + (note && '\n' + note) }
207  }
208  const o = await $.ui.open({ id: DECK, title: 'agentille' })
209  const auto = my.deckAuto ? ' · opens on every /agt (/agt-deck off to stop)' : ''
210  const tail = note && '\n' + note
211  if (o?.isPlaced === false) return { text: 'deck waits: ' + (o.reason ?? 'no surface here places panes') + auto + tail }
212  return { text: 'deck open' + auto + tail }
213}
214
215export async function focusCommand($, e) {
216  const a = parseFocusArgs(e.args)
217  if (a.error) return { text: a.error }
218  let note = ''
219  if (a.on !== undefined) {
220    note = await setDisplay($, 'focus', a.on)
221    $.ui.invalidate('ui.render')
222  }
223  return { text: focusText(my.focusOn, focusLines(Date.now())) + (note && '\n' + note) + MOVED('focus') }
224}
225
226export async function highlightCommand($, e) {
227  const a = parseHighlightArgs(e.args)
228  if (a.error) return { text: a.error }
229  let note = ''
230  if (a.on !== undefined) {
231    note = await setDisplay($, 'highlight', !a.on ? 'off' : a.all ? 'all' : 'on')
232    $.ui.invalidate('ui.render')
233  }
234  return { text: highlightText(my.highlightOn, my.highlightAll) + (note && '\n' + note) + MOVED('highlight') }
235}
236
hooks/drawing.js 45 lines
1// agentille mod — what /agt can leave to the mod when the mod draws: the version and the phases
2// on the band, the one-time tip, and the Agents and Raw reports sections of report.md.
3// Pure: register.js reads the surfaces and the files, this decides and formats.
4
5import { elapsed, short, tokens } from './live.js'
6
7// Surfaces that show a mod's band. `$.session.surfaces()` names terminal, desktop, vscode or mobile, and is
8// empty in `claude -p` and the SDK; the VS Code chat panel runs hooks but draws nothing, and Remote Control
9// draws in the machine's terminal, which the list names too.
10const DRAWN = new Set(['terminal', 'desktop'])
11
12export const TIP = 'tip: /agentille-init makes agents sound like you'
13
14export function canDraw(surfaces) {
15  return (surfaces ?? []).some((s) => DRAWN.has(s))
16}
17
18// The marker the skill looks for (display.md → "When the mod draws"). Absent: the skill prints it all itself.
19export function drawingBlock(draws) {
20  if (!draws) return ''
21  return '\n## Drawing (agentille mod)\n\nmod draws: yes. The band shows the version and the phases (no TodoWrite spine), the mod shows the tip and adds Agents and Raw reports to report.md.\n'
22}
23
24// `…/.agentille/state/run-<id>/report.md` → the run id, else null.
25export function reportRun(path) {
26  const m = /\/\.agentille\/state\/run-([A-Za-z0-9_-]{1,64})\/report\.md$/.exec(String(path ?? ''))
27  return m ? m[1] : null
28}
29
30// The sections the mod owns, for whichever of them the report still lacks. '' when it has both.
31export function reportTail(text, { agents = [], routes = [], files = [] }) {
32  const out = []
33  if (!/^## Agents[ \t]*\r?$/m.test(text)) {
34    const rows = [...agents].sort((a, b) => a.start - b.start).map((a) =>
35      '| ' + a.role + ' | ' + short(a.model) + (a.effort ? ' · ' + a.effort : '') + ' | ' + elapsed((a.end ?? a.start) - a.start) + ' | ' + tokens(a.input) + ' / ' + tokens(a.output) + ' |')
36    for (const r of routes) rows.push('| ' + (r.agent ?? r.role) + ' (pane) | ' + short(r.model) + (r.effort ? ' · ' + r.effort : '') + ' | ' + elapsed((r.end ?? r.start) - r.start) + ' | n/a |')
37    if (rows.length) out.push('## Agents', '', '| role | model · effort | elapsed | tokens in / out |', '|---|---|---|---|', ...rows, '')
38  }
39  if (!/^## Raw reports[ \t]*\r?$/m.test(text) && files.length) {
40    out.push('## Raw reports', '', ...[...files].sort().map((f) => '- [' + f + '](agents/' + f + ')'), '')
41  }
42  if (!out.length) return ''
43  return (text.endsWith('\n') ? '\n' : '\n\n') + out.join('\n')
44}
45
hooks/highlight.js 367 lines
1// agentille highlight — make a long /agt reply scannable. Pure on purpose: register.js
2// draws; these helpers decide what to light and what goes on the essentials card.
3//
4//   essentials — the next action, the one flag, the one done line, read off the text. No model.
5//                 Skipped for a final card (an answer opening with ✓ or ✗): it would repeat it.
6//   lightTokens — wrap paths, versions, refs and numbers in backticks so the dim body
7//                 shows them lit. Code, links and fences are never touched.
8//   panel       — the turn's final answer, between two rules: a head, the essentials, the body lit at full
9//                 brightness. Narration between tool calls stays dim, so the eye lands on the answer.
10
11import { words } from './focus.js'
12
13export const CARD_MIN_WORDS = 40
14export const LIT_MAX = 10_000
15export const LIT_MEMO_MAX = 500
16export const MARK = { next: '→', flag: '⚑', done: '✓' }
17export const SPAN_COLOR = { path: '#7fd3e6', cmd: '#4f8ef7', version: '#a77bff', number: '#f2a33a', ref: '#3fb950' }
18export const HIGHLIGHT_USAGE = 'Usage: /agt-highlight [on|all|off]'
19
20const MAX_LINE = 96
21
22const PATH_ABS = /^(~\/|\.{1,2}\/|\/)[\w@.\/-]*[\w@-](:\d+(-\d+)?)?$/
23const PATH_REL = /^[\w@.-]+(\/[\w@.-]+)+\.[A-Za-z0-9]{1,8}(:\d+(-\d+)?)?$/
24const VERSION = /^v?\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$|^v\d+(\.\d+)?$/
25const REF = /^#\d+$/
26const NUMBER = /^\d+([.,]\d+)?(×|x|%|k|K|M|ms|s|min)$/
27
28function kindOf(core) {
29  if (core.includes('://')) return null
30  if (PATH_ABS.test(core) || PATH_REL.test(core)) return 'path'
31  if (VERSION.test(core)) return 'version'
32  if (REF.test(core)) return 'ref'
33  if (NUMBER.test(core)) return 'number'
34  return null
35}
36
37// Punctuation that hugs a token is not part of it: "(#75)," lights #75 only.
38function peel(token) {
39  const lead = /^(?:[(\[{"'*_]|~(?!\/))+/.exec(token)?.[0] ?? ''
40  const rest = token.slice(lead.length)
41  const trail = /[.,;:!?)\]}"'*_…]+$/.exec(rest)?.[0] ?? ''
42  return { lead, core: rest.slice(0, rest.length - trail.length), trail }
43}
44
45// A fence opens at any indent (list items nest them) and closes only on the same
46// character, at least as long, alone on its line. An unclosed fence runs to the end.
47function fenceMask(lines) {
48  let open = null
49  return lines.map((l) => {
50    // Quoted code blocks fence the same way: `> ```` opens one too.
51    l = l.replace(/^\s*(?:>\s?)+/, '')
52    if (open) {
53      const c = /^\s*(`+|~+)\s*$/.exec(l)
54      if (c && c[1][0] === open[0] && c[1].length >= open.length) open = null
55      return true
56    }
57    // A backtick fence's info string has no backtick, so ```npm test``` is inline code.
58    const m = /^\s*(`{3,})[^`]*$/.exec(l) ?? /^\s*(~{3,})/.exec(l)
59    if (m) {
60      open = m[1]
61      return true
62    }
63    return false
64  })
65}
66
67const PROTECTED = /(`[^`]*`|!?\[[^\]]*\]\([^)]*\)|<[^>\s]+>)/
68
69function lightPlain(seg) {
70  return seg
71    .split(/(\s+)/)
72    .map((tok) => {
73      if (!tok.trim() || tok.includes('://') || tok.startsWith('www.')) return tok
74      const { lead, core, trail } = peel(tok)
75      return core && kindOf(core) ? lead + '`' + core + '`' + trail : tok
76    })
77    .join('')
78}
79
80export function lightTokens(md) {
81  const lines = String(md ?? '').split('\n')
82  const fenced = fenceMask(lines)
83  return lines
84    .map((l, i) => {
85      if (fenced[i]) return l
86      if (/^\s{0,3}\[[^\]]+\]:/.test(l)) return l
87      if ((l.match(/`/g) ?? []).length % 2) return l
88      return l.split(PROTECTED).map((seg, j) => (j % 2 ? seg : lightPlain(seg))).join('')
89    })
90    .join('\n')
91}
92
93function clip(s) {
94  const t = s.replace(/\s+/g, ' ').trim()
95  return t.length > MAX_LINE ? t.slice(0, MAX_LINE - 1) + '…' : t
96}
97
98const NEGATED = /\b(0|no|zero|without)\s+(\w+\s+)?(failures?|failed|failing|fails?|errors?|warnings?|blockers?)\b/gi
99
100function isFlag(line) {
101  const t = line.replace(NEGATED, '')
102  return (
103    /[⚑✗]/.test(t) ||
104    /\b(blockers?|blocked|failed|failing)\b/i.test(t) ||
105    /\b(FAIL|CONCERNS|REVISE)\b/.test(t) ||
106    /needs you/i.test(t) ||
107    /\b[1-9]\d*\s+(\w+\s+)?(errors?|warnings?)\b/i.test(t) ||
108    /^(error|warning):/i.test(t)
109  )
110}
111
112function isDone(line) {
113  if (/\bnot\s+(yet\s+)?(done|merged|released|passing)\b/i.test(line)) return false
114  return /[✓✅]/.test(line) || /\b(done|passes|passed|passing|merged|released|shipped|tagged|green)\b/i.test(line)
115}
116
117function nextText(line) {
118  if (line.startsWith('→')) return line.slice(1).trim()
119  const m = /^next(?: steps?)?\s*[:—-]\s*(.*)$/i.exec(line)
120  if (m) return m[1].trim()
121  return /next step/i.test(line) ? line : ''
122}
123
124// → [{ kind, text }]: at most one per kind, first line wins, next · flag · done.
125export function essentials(text) {
126  const lines = String(text ?? '').split('\n')
127  const fenced = fenceMask(lines)
128  const found = {}
129  lines.forEach((raw, i) => {
130    if (fenced[i]) return
131    if (/^\s*#{1,6}(\s|$)/.test(raw)) return
132    if (/^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/.test(raw)) return
133    const line = raw
134      .replace(/^\s*(?:(?:[-*+]|\d+[.)])\s+|>\s*)+/, '')
135      .replace(/\*\*|__/g, '')
136      .trim()
137    if (!line) return
138    const next = !found.next && nextText(line)
139    if (next) {
140      found.next = clip(next)
141      return
142    }
143    if (!found.flag && isFlag(line)) {
144      const t = clip(line.replace(/^⚑️?\s*/, ''))
145      if (t) found.flag = t
146      return
147    }
148    if (isFlag(line)) return // a second flag is still a flag, never the done line
149    if (!found.done && isDone(line)) {
150      const t = clip(line.replace(/^[✓✅]️?\s*/, ''))
151      if (t) found.done = t
152    }
153  })
154  return ['next', 'flag', 'done'].filter((k) => found[k]).map((kind) => ({ kind, text: found[kind] }))
155}
156
157// A line → coloured spans. Backtick delimiters are dropped; the texts rejoin to the line.
158export function spans(line) {
159  const out = []
160  const push = (text, kind) => {
161    if (!text) return
162    const last = out[out.length - 1]
163    if (kind === 'plain' && last?.kind === 'plain') last.text += text
164    else out.push({ text, kind })
165  }
166  String(line ?? '').split(/`([^`]*)`/).forEach((seg, j) => {
167    if (j % 2) return push(seg, kindOf(seg) ?? 'cmd')
168    for (const tok of seg.split(/(\s+)/)) {
169      if (!tok.trim()) {
170        push(tok, 'plain')
171        continue
172      }
173      const { lead, core, trail } = peel(tok)
174      const kind = !core ? 'plain' : /^\/[a-z][\w:-]*$/.test(core) ? 'cmd' : (kindOf(core) ?? 'plain')
175      push(lead, 'plain')
176      push(core, kind)
177      push(trail, 'plain')
178    }
179  })
180  return out
181}
182
183// The run's final card opens with ✓ (done) or ✗ (failed): it is its own summary, so no
184// essentials card and no word floor, only the tokens lit.
185const isFinalCard = (text) => /^[✓✗]/.test(String(text ?? '').trimStart())
186
187export function highlight(text) {
188  const final = isFinalCard(text)
189  if (!final && words(text) < CARD_MIN_WORDS) return null
190  const card = final ? [] : essentials(text)
191  const lit = lightTokens(text)
192  const body = lit.length <= LIT_MAX ? lit : null
193  if (!card.length && body === null) return null
194  return { card, body }
195}
196
197// highlight() is regex work and the transcript redraws on every ticker tick, so the result
198// is kept per message id while its text is unchanged (a streaming reply recomputes).
199export function highlightFor(memo, id, text) {
200  if (!id) return highlight(text)
201  const hit = memo.get(id)
202  if (hit && hit.text === text) return hit.h
203  const h = highlight(text)
204  memo.delete(id)
205  memo.set(id, { text, h })
206  if (memo.size > LIT_MEMO_MAX) memo.delete(memo.keys().next().value)
207  return h
208}
209
210// The lit/dim decision is made once per message id, on its first sight, so a reply
211// does not flip style when a later turn changes.
212export function litFor(memo, id, { on, agtTurn }) {
213  if (!id) return !!(on && agtTurn)
214  if (!memo.has(id)) {
215    memo.set(id, !!agtTurn)
216    if (memo.size > LIT_MEMO_MAX) memo.delete(memo.keys().next().value)
217  }
218  return !!on && memo.get(id)
219}
220
221// The block that closes the main turn's answer: its text is the answer's tail (a reply drawn in
222// several blocks frames only its last).
223export function isAnswerBlock(answer, text) {
224  const a = String(answer ?? '').trim()
225  const t = String(text ?? '').trim()
226  return !!a && !!t && a.endsWith(t)
227}
228
229const clock = (ms) => {
230  const s = Math.max(0, Math.round((ms ?? 0) / 1000))
231  return s < 60 ? s + 's' : Math.floor(s / 60) + 'm ' + String(s % 60).padStart(2, '0') + 's'
232}
233
234// How a main-session answer should be shaped, sent beside each typed prompt under
235// display.highlight: all. The panel reads the same shape back: a headline, bullets, a move block.
236export const ANSWER_STYLE = [
237  '[agentille answer style] Shape your final answer for a two-second read:',
238  '- Line 1: the answer or outcome in at most 15 words. No preamble.',
239  '- Then at most 6 bullets, one fact each, at most 15 words. No paragraphs, no step-by-step recap of what you did.',
240  '- If the user must act, end with a line "Your move:" then numbered steps, one action each, any command in backticks.',
241  '- If nothing is needed from the user, leave the "Your move:" section out.',
242  '- Code, tables and headings only when they carry the answer itself.',
243].join('\n')
244
245// A typed prompt that asks for text to paste as is: "no formatting", "remove the formatting", "plain
246// text", "raw text", "copy-paste", "paste-ready" or a leading "raw:". Its answer skips the panel and the
247// answer style, draws as the engine does and goes on the clipboard: copying out of the panel brings
248// its rules and the markdown along. Only the prompt's own ask counts: the whole prompt when it is
249// short, else its first or last sentence when that one is short (a pasted draft, then "make this plain
250// text"). A long prompt that only talks about formatting or copy-paste is not an ask for paste text.
251const RAW_LEAD = /^\s*raw\s*[:—-]/i
252const RAW = [
253  /\b(?:no|without|remove|strip|drop)\s+(?:the\s+|all\s+|any\s+)?(?:markdown|formatting)\b/i,
254  /\bunformatted\b/i,
255  /\bplain[- ]text\b/i,
256  /\braw\s+(?:text|output|version|copy)\b/i,
257  /\bcopy[- ]?paste(?:able)?\b/i,
258  /\bpaste[- ]ready\b/i,
259]
260export const RAW_PROMPT_WORDS = 25
261export const RAW_ASK_WORDS = 20
262const asks = (s) => RAW.some((re) => re.test(s))
263const sentences = (line) => line.split(/(?<=[.!?:])\s+/).filter((s) => s.trim())
264
265export function isRawPrompt(text) {
266  const t = String(text ?? '')
267  if (RAW_LEAD.test(t)) return true
268  if (words(t) <= RAW_PROMPT_WORDS) return asks(t)
269  const lines = t.split('\n').filter((l) => l.trim())
270  return [sentences(lines[0])[0], sentences(lines.at(-1)).at(-1)].some((s) => words(s) <= RAW_ASK_WORDS && asks(s))
271}
272
273// Sent beside a raw prompt in place of the answer style.
274export const RAW_STYLE = [
275  '[agentille raw] The person wants text to paste as is, and your final answer is copied to their clipboard.',
276  '- Reply with only that text: no markdown (no headings, bullets, bold or code fences), no preamble, no closing line.',
277].join('\n')
278
279// A move block opens on a line naming the user's turn ("Your move:", "Action needed:", "You do:").
280const MOVE = /^\s*(?:#{1,6}\s*)?(?:[*_]{1,2})?\s*(?:▶\s*)?(?:your move|action needed|you do|on your end|to do on your side)\b(?:[*_]{1,2})?\s*[:—-]?\s*(?:[*_]{1,2})?\s*(.*)$/i
281const STEP = /^\s*(?:[-*+]|\d+[.)])\s+/
282
283// The text → { main, move }: the move block's steps (list markers dropped), or null when there is none.
284// It runs from its opening line to the end, or to the next heading. Fenced lines never open one.
285export function splitMove(text) {
286  const lines = String(text ?? '').split('\n')
287  const fenced = fenceMask(lines)
288  const at = lines.findIndex((l, i) => !fenced[i] && MOVE.test(l))
289  if (at < 0) return { main: String(text ?? ''), move: null }
290  let stop = lines.length
291  for (let i = at + 1; i < lines.length; i++) if (!fenced[i] && /^\s*#{1,6}\s/.test(lines[i])) { stop = i; break }
292  const inline = MOVE.exec(lines[at])[1].replace(/[*_]{2}/g, '').trim()
293  const steps = [inline, ...lines.slice(at + 1, stop)].map((l) => l.replace(STEP, '').replace(/\*\*|__/g, '').trim()).filter(Boolean)
294  const main = [...lines.slice(0, at), ...lines.slice(stop)].join('\n').replace(/\s+$/, '')
295  return { main, move: steps.length ? steps : null }
296}
297
298// The panel's body → parts: each run of top-level bullet lines ("- ", "* ", "+ ") becomes { items },
299// drawn as • rows with a hanging indent; everything else stays { text } for the markdown renderer.
300// Fenced lines are never bullets. Bold markers are dropped from items, as from move steps.
301export function bodyParts(text) {
302  const lines = String(text ?? '').split('\n')
303  const fenced = fenceMask(lines)
304  const parts = []
305  lines.forEach((line, i) => {
306    const m = !fenced[i] && /^[-*+]\s+(\S.*)$/.exec(line)
307    const last = parts[parts.length - 1]
308    if (m) {
309      const item = m[1].replace(/\*\*|__/g, '').trim()
310      if (last?.items) last.items.push(item)
311      else parts.push({ items: [item] })
312    } else if (last?.lines) last.lines.push(line)
313    else parts.push({ lines: [line] })
314  })
315  return parts.map((p) => (p.items ? p : { text: p.lines.join('\n').trim() })).filter((p) => p.items || p.text)
316}
317
318// The first line becomes the panel's headline when it reads as one: short, not code, a table or a list.
319function headline(main) {
320  const lines = main.split('\n')
321  const i = lines.findIndex((l) => l.trim())
322  if (i < 0) return { head: null, rest: main }
323  const raw = lines[i].trim()
324  if (/^(```|~~~|\||>|[-*+]\s|\d+[.)]\s)/.test(raw)) return { head: null, rest: main }
325  const head = raw.replace(/^#{1,6}\s+/, '').replace(/\*\*|__/g, '').trim()
326  if (!head || head.length > 120) return { head: null, rest: main }
327  return { head, rest: lines.slice(i + 1).join('\n').replace(/^\s+|\s+$/g, '') }
328}
329
330// The final answer's panel. tone colours the frame (fail · ok · move · flag · plain); head is the
331// answer's own first line, or null when it does not read as a headline; time is the turn's; card is the essentials strip, kept only for
332// an unshaped long answer; body is lit; move is the user's steps; idle says "nothing needed from you"
333// for a shaped answer that has no move.
334export function panel(text, { ms, shaped = false } = {}) {
335  const t = String(text ?? '')
336  const { main, move } = splitMove(t)
337  const { head, rest } = headline(main)
338  const lead = t.trimStart()
339  const card = shaped || move || isFinalCard(t) || words(t) < CARD_MIN_WORDS ? [] : essentials(t)
340  const lit = lightTokens(rest)
341  const tone = lead.startsWith('✗') ? 'fail' : move ? 'move' : lead.startsWith('✓') ? 'ok' : card.some((c) => c.kind === 'flag') ? 'flag' : 'plain'
342  return {
343    tone,
344    head,
345    time: typeof ms === 'number' && ms > 0 ? clock(ms) : null,
346    card,
347    body: rest ? (lit.length <= LIT_MAX ? lit : rest) : null,
348    move,
349    idle: shaped && !move,
350  }
351}
352
353export function parseHighlightArgs(args) {
354  const a = String(args ?? '').trim().toLowerCase()
355  if (!a) return { show: true }
356  if (a === 'on') return { on: true, all: false }
357  if (a === 'all') return { on: true, all: true }
358  if (a === 'off') return { on: false, all: false }
359  return { error: HIGHLIGHT_USAGE }
360}
361
362export function highlightText(on, all = false) {
363  if (!on) return 'Highlight: off — replies draw as usual, and nothing is added to your prompts: no answer style, no raw style, no clipboard copy. /agt-highlight on turns it back on.'
364  if (all) return 'Highlight: all — every long reply is lit, and each answer comes short and framed: a headline, bullets, and a ▶ your move box when you have something to do.'
365  return 'Highlight: on — /agt replies get an essentials card and a dim body with paths, versions, refs and numbers lit, and the final answer is framed. /agt-highlight all shapes every answer.'
366}
367
hooks/info.js 103 lines
1// agentille info — the pure half of /agt-info: argument parsing, the overview lines, and the route
2// dry-run. No mods API; register.js feeds it what the mod holds.
3
4import { ROLES, decide, maxRunUsdOf, usd } from './routing.js'
5import { elapsed, short, tokens } from './live.js'
6import { displayText } from './settings.js'
7
8export const INFO_USAGE = 'Usage: /agt-info [routing|ledger|squads|route <role> [size=small|large] [risk=none|auth|money|data] [depth=quick|complex-only|always]]'
9
10const SIZES = ['small', 'large']
11const RISKS = ['none', 'auth', 'money', 'data']
12const DEPTHS = ['quick', 'complex-only', 'always']
13
14// "agentille:agentille-planner", "agentille-planner" and "planner" all name the planner.
15function roleName(word) {
16  return String(word).replace(/^agentille:/, '').replace(/^agentille-/, '')
17}
18
19// → { view: 'overview' | 'routing' | 'ledger' | 'squads' } | { view: 'route', role, hdr, depth } | { error }
20export function parseInfoArgs(args) {
21  const words = String(args ?? '').trim().split(/\s+/).filter(Boolean)
22  if (words.length === 0) return { view: 'overview' }
23  const sub = words[0].toLowerCase()
24  if (sub === 'routing' || sub === 'ledger' || sub === 'squads') {
25    return words.length === 1 ? { view: sub } : { error: INFO_USAGE }
26  }
27  if (sub !== 'route') return { error: INFO_USAGE }
28  if (words.length < 2) return { error: 'Usage: /agt-info route <role> [size=…] [risk=…] [depth=…]. Roles: ' + ROLES.join(', ') }
29  const role = roleName(words[1])
30  if (!ROLES.includes(role)) return { error: 'Unknown role "' + words[1] + '". Valid roles: ' + ROLES.join(', ') }
31  const hdr = {}
32  let depth = null
33  for (const w of words.slice(2)) {
34    const i = w.indexOf('=')
35    const k = i > 0 ? w.slice(0, i).toLowerCase() : ''
36    const v = i > 0 ? w.slice(i + 1).toLowerCase() : ''
37    if (k === 'size' && SIZES.includes(v)) hdr.size = v
38    else if (k === 'risk' && RISKS.includes(v)) hdr.risk = v
39    else if (k === 'depth' && DEPTHS.includes(v)) depth = v
40    else return { error: 'Cannot read "' + w + '". Use size=' + SIZES.join('|') + ', risk=' + RISKS.join('|') + ', depth=' + DEPTHS.join('|') }
41  }
42  return { view: 'route', role, hdr, depth }
43}
44
45const pick = (d) => (d.stop ? 'denied (' + (/seven-day/.test(d.stop) ? 'routing.stopAtWeeklyPct' : 'routing.stopAtCeiling') + ')' : d.model + (d.effort ? ' · ' + d.effort : '') + ' · ' + d.reason)
46
47// Dry-run of decide() with fresh run state under the person's routing settings, then each escalation
48// rung that changes the pick. Nothing here touches a live run.
49export function routeText({ role, hdr = {}, depth = null }, settings, weeklyPct = null) {
50  const ask = (h, run) => decide({ role, hdr: h, run: { revise: 0, fixes: 0, fable: 0, ...run }, depth, settings, weeklyPct })
51  const base = ask(hdr, {})
52  const head = role + (hdr.size ? ' size=' + hdr.size : '') + (hdr.risk ? ' risk=' + hdr.risk : '') + (depth ? ' depth=' + depth : '')
53  const rungs = [
54    ['1st REVISE', ask(hdr, { revise: 1 })],
55    ['2nd REVISE', ask(hdr, { revise: 2 })],
56    ['fix attempt 2', ask({ ...hdr, mode: 'fix' }, { fixes: 2 })],
57    ['fix attempt 3', ask({ ...hdr, mode: 'fix' }, { fixes: 3 })],
58    ['diagnose, 2 failed fixes', ask({ ...hdr, mode: 'diagnose' }, { fixes: 2 })],
59    ...(maxRunUsdOf(settings) == null ? [] : [['past maxRunUsd ' + usd(maxRunUsdOf(settings)), ask(hdr, { usd: maxRunUsdOf(settings) })]]),
60  ].filter(([, d]) => d.stop || d.model !== base.model || d.effort !== base.effort || d.reason !== base.reason)
61  const lines = [head + ' → ' + pick(base)]
62  if (rungs.length === 0) lines.push('  no escalation rungs for this role')
63  for (const [label, d] of rungs) lines.push('  ' + label.padEnd(26) + pick(d))
64  return lines.join('\n')
65}
66
67// One line: how many dispatches the run logged and on which models.
68export function routingSummary(logLines) {
69  const models = new Map()
70  let n = 0
71  for (const l of logLines ?? []) {
72    try {
73      const r = JSON.parse(l)
74      n += 1
75      const m = short(r.model)
76      models.set(m, (models.get(m) ?? 0) + 1)
77    } catch { /* a bad log line is skipped */ }
78  }
79  if (n === 0) return 'routing: no dispatches yet (/agt-info routing)'
80  return 'routing: ' + n + ' dispatch' + (n === 1 ? '' : 'es') + ' · ' + [...models].map(([m, c]) => m + ' ' + c).join(' · ') + ' (/agt-info routing)'
81}
82
83export function ledgerSummary(l) {
84  if (!l || l.total.agents === 0) return 'ledger: no agents in this run yet (/agt-info ledger)'
85  const t = l.total
86  return 'ledger: run ' + l.run + ' · ' + t.agents + ' agent' + (t.agents === 1 ? '' : 's') + ' · in ' + tokens(t.input) + ' · out ' + tokens(t.output) + ' · ' + elapsed(t.ms) + ' (/agt-info ledger)'
87}
88
89export function squadsSummary(rows) {
90  if (rows === null) return 'squads: squads.json is unreadable (/agt-info squads)'
91  const active = rows.filter((r) => r.active).map((r) => r.name)
92  return 'squads: ' + (active.length ? active.join(', ') : 'none active') + ' (/agt-info squads)'
93}
94
95// profile.json → sessions as one line: null is unset, which reads as on.
96export function sessionsLine(v) {
97  return 'sessions: ' + (v ?? 'on') + (v ? ' (profile)' : ' (default)') + (v === 'off' ? ' · a plain prompt opens no sessions' : '')
98}
99
100export function overviewText({ display, sessions, squads, routing, ledger }) {
101  return ['display (profile.json → display):', displayText(display), sessionsLine(sessions), squads, routing, ledger, 'more: /agt-info routing | ledger | squads | route <role>'].join('\n')
102}
103
hooks/links.js 85 lines
1// agentille links — who works on which slice, what each finished agent said, and the lead's side
2// of the conversation. Pure on purpose: register.js reads headers and answers, board.js draws.
3
4import { verdictOf } from './routing.js'
5
6// `slice=<slug>` in the [agt …] header names the slice an agent builds, reviews or attacks.
7const SLICE_RE = /^[a-z0-9][a-z0-9-]{0,23}$/
8export const sliceOf = (hdr) => (SLICE_RE.test(String(hdr?.slice ?? '')) ? hdr.slice : null)
9
10const isBuilder = (r) => (r.agent ?? r.role) === 'executor'
11// The roles that check a built diff: every *-reviewer but the plan-reviewer, and the adversary.
12const isChecker = (r) => {
13  const role = String(r.agent ?? r.role ?? '')
14  return role === 'adversary' || (role.endsWith('-reviewer') && role !== 'plan-reviewer')
15}
16
17// A finished agent's head as a chip: PASS · CONCERNS P1:2 · FAIL P0:1 · APPROVE · REVISE · HELD · BROKEN 2.
18// tone is a theme color name. null when the answer has no head this role writes.
19export function verdictChip(role, answer) {
20  const a = String(answer ?? '')
21  const r = String(role ?? '')
22  if (r === 'plan-reviewer') {
23    const v = verdictOf(a)
24    return v ? { text: v, tone: v === 'APPROVE' ? 'success' : 'warning' } : null
25  }
26  if (r === 'adversary') {
27    const b = /\bBROKEN:\s*(\d+)/.exec(a)
28    if (!b) return null
29    const n = Number(b[1])
30    return n ? { text: 'BROKEN ' + n, tone: 'error' } : { text: 'HELD', tone: 'success' }
31  }
32  if (r.endsWith('-reviewer')) {
33    const v = /VERDICT:\s*(PASS|CONCERNS|FAIL)\b/.exec(a)?.[1]
34    if (!v) return null
35    const count = (p) => Number(new RegExp('\\b' + p + ':\\s*(\\d+)').exec(a)?.[1] ?? 0)
36    const counts = v === 'PASS' ? [] : ['P0', 'P1'].filter((p) => count(p) > 0).map((p) => p + ':' + count(p))
37    return { text: [v, ...counts].join(' '), tone: v === 'PASS' ? 'success' : v === 'FAIL' ? 'error' : 'warning' }
38  }
39  return null
40}
41
42// A slice's reviewers and adversary hang under the executor that built it, so the tree reads
43// who checks whose diff. A row whose own parent is on screen keeps it; the newest builder of a
44// slice wins (a fix attempt replaces the first build). With exactly one builder on screen, a checker
45// that names no slice is that builder's: the common one-slice run, or a lead that left slice= out.
46// Two builders and no slice say nothing about which diff a reviewer reads, so nothing is linked.
47export function linkSlices(rows) {
48  const builders = new Map()
49  for (const r of rows) if (r.slice && isBuilder(r)) builders.set(r.slice, r.id)
50  const all = rows.filter(isBuilder)
51  const only = all.length === 1 ? all[0].id : null
52  const ids = new Set(rows.map((r) => r.id))
53  return rows.map((r) => {
54    if (isBuilder(r) || !isChecker(r) || (r.parentId && ids.has(r.parentId))) return r
55    const b = r.slice ? builders.get(r.slice) : only
56    if (!b || b === r.id) return r
57    return { ...r, parentId: b }
58  })
59}
60
61// Who a wire line names: the role, plus its slice when it has one ("code-reviewer:api").
62export const party = (role, slice = null) => String(role ?? '?') + (slice ? ':' + slice : '')
63
64// The task line of a dispatch prompt: the first line that is not the header or the profile prefix.
65export function taskLine(prompt, n = 70) {
66  const line = String(prompt ?? '').split('\n').map((l) => l.trim()).find((l) => l && !/^\[agt\s/.test(l) && !/^(User|Avoid|Communicate):/.test(l)) ?? ''
67  return line.length > n ? line.slice(0, n - 1) + '…' : line
68}
69
70// What a finished agent said back, in one line: its chip, else its first line.
71export function answerLine(role, answer, n = 70) {
72  const chip = verdictChip(role, answer)
73  if (chip) return chip.text
74  const line = String(answer ?? '').split('\n').map((l) => l.trim().replace(/^[#>*\s-]+/, '')).find(Boolean) ?? 'done'
75  return line.length > n ? line.slice(0, n - 1) + '…' : line
76}
77
78// Retry loops of a run, for the band header: "plan ↺2 · fix ×3". '' when there were none.
79export function loopText(run) {
80  const parts = []
81  if (run?.revise > 0) parts.push('plan ↺' + run.revise)
82  if (run?.fixes > 0) parts.push('fix ×' + run.fixes)
83  return parts.join(' · ')
84}
85
hooks/live.js 175 lines
1// What is running right now: in-process subagents and herdr agt-* panes.
2// Pure state + formatting; register.js feeds it events and draws the result.
3
4import { BYE_MS, modelKey } from './mascot.js'
5
6export const DONE_GRACE_MS = 10_000 // a done pane is reaped this fast once its answer is saved
7export const IDLE_GRACE_MS = 60_000 // an idle pane, lead between turns
8export const STATUS_GRACE_MS = 90_000 // how long the status line keeps a finished agent on screen
9export const ON_STAGE = new Set(['working', 'blocked'])
10const LEAVING = new Set(['done', 'idle'])
11const EFFORT_BAR = { low: '▂', medium: '▄', high: '▆', xhigh: '▇', max: '█' }
12
13export function newAgent({ id, role, routed, model, effort, reason, run, now, parentId = null }) {
14  return { id, kind: 'sub', role, routed, model, effort, reason, run, parentId, listStatus: null, start: now, end: null, leftAt: null, state: 'working', input: 0, output: 0, cacheRead: 0 }
15}
16
17export function addUsage(a, u) {
18  if (!a || !u) return
19  a.input += (u.input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
20  a.output += u.output_tokens ?? 0
21  a.cacheRead += u.cache_read_input_tokens ?? 0
22}
23
24export function finish(a, now, ms) {
25  if (!a) return
26  a.state = 'done'
27  a.end = ms != null ? a.start + ms : now
28  a.leftAt = now
29}
30
31// herdr `agent list` rows → pane agents; `name` = agt-<run>-<role…>
32export function paneAgents(list, selfPane) {
33  return (list ?? [])
34    .filter((p) => typeof p.name === 'string' && p.name.startsWith('agt-') && p.pane_id !== selfPane)
35    .map((p) => {
36      const parts = p.name.split('-')
37      return { id: p.pane_id, kind: 'pane', name: p.name, role: parts.slice(2).join('-') || p.name, run: parts[1] ?? '', vendor: p.agent ?? 'agent', state: p.agent_status ?? 'unknown', seq: p.state_change_seq ?? 0, tab: p.tab_id ?? null, workspace: p.workspace_id ?? null }
38    })
39}
40
41// Remembers when each pane entered its current state (by state_change_seq) and sorts the panes
42// that sat in done ≥ 10s, or in idle ≥ 60s while the lead has no turn running (an idle worker
43// mid-run is waiting for review, not abandoned). A due pane is only `reap` once `harvested(pane)`
44// says its answer is in hand; otherwise it is `stranded`: kept open and flagged, since closing
45// it would lose the output. With no `harvested` nothing is ever reaped. Only agt-* panes reach here.
46export function reapPlan(panes, seen, now, leadBusy = true, harvested = () => false) {
47  const reap = []
48  const stranded = []
49  for (const p of panes) {
50    const key = p.id
51    const prev = seen.get(key)
52    if (!prev || prev.seq !== p.seq || prev.state !== p.state) seen.set(key, { seq: p.seq, state: p.state, since: now })
53    const since = seen.get(key).since
54    const due = (p.state === 'done' && now - since >= DONE_GRACE_MS) || (p.state === 'idle' && !leadBusy && now - since >= IDLE_GRACE_MS)
55    if (due) (harvested(p) ? reap : stranded).push(p)
56  }
57  for (const key of [...seen.keys()]) if (!panes.some((p) => p.id === key)) seen.delete(key)
58  return { reap, stranded }
59}
60
61export function short(model) {
62  return modelKey(model)
63}
64
65export function tokens(n) {
66  if (n >= 1_000_000) return (n / 1_000_000).toFixed(1) + 'M'
67  if (n >= 1000) return (n / 1000).toFixed(1) + 'k'
68  return String(n)
69}
70
71export function elapsed(ms) {
72  const s = Math.max(0, Math.round(ms / 1000))
73  return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0')
74}
75
76export function effortBar(effort) {
77  return EFFORT_BAR[effort] ?? ' '
78}
79
80// The run's ledger: tokens and time per role, minutes per pane role, and per slice the newest state of each role
81// that works on it (`slices`: slug → role → working | done). The compaction hook reads `slices` back.
82export function ledger(agents, run, routes = []) {
83  const roles = {}
84  const panes = {}
85  const slices = {}
86  const total = { agents: 0, input: 0, output: 0, cacheRead: 0, ms: 0 }
87  for (const a of agents.values()) {
88    if ((a.fileRun ?? a.run) !== run) continue // a headerless workflow agent counts under its file run (ad hoc), not the band's
89    const r = (roles[a.role] ??= { agents: 0, input: 0, output: 0, cacheRead: 0, ms: 0 })
90    const ms = (a.end ?? a.start) - a.start
91    for (const t of [r, total]) {
92      t.agents += 1; t.input += a.input; t.output += a.output; t.cacheRead += a.cacheRead; t.ms += ms
93    }
94    if (a.slice) (slices[a.slice] ??= {})[a.role] = a.state
95  }
96  for (const r of routes) {
97    if (r.run !== run) continue
98    const t = (panes[r.agent ?? r.role] ??= { agents: 0, ms: 0 })
99    t.agents += 1
100    t.ms += (r.end ?? r.start) - r.start
101    if (r.slice) (slices[r.slice] ??= {})[r.agent ?? r.role] = r.end == null ? 'working' : 'done'
102  }
103  return { run, roles, total, panes, slices }
104}
105
106export function ledgerText(l) {
107  const names = Object.keys(l.roles)
108  const panes = l.panes ?? {}
109  const paneNames = Object.keys(panes)
110  if (names.length === 0 && paneNames.length === 0) return 'No agents in this run yet.'
111  const line = (name, t) => name.padEnd(20) + String(t.agents).padStart(3) + '  in ' + tokens(t.input).padStart(7) + '  out ' + tokens(t.output).padStart(7) + '  cache ' + tokens(t.cacheRead).padStart(7) + '  ' + elapsed(t.ms)
112  const paneLine = (name, t) => (name + ' (pane)').padEnd(20) + String(t.agents).padStart(3) + '  tokens n/a  ' + elapsed(t.ms)
113  return ['run ' + l.run, ...names.sort().map((n) => line(n, l.roles[n])), ...paneNames.sort().map((n) => paneLine(n, panes[n])), line('total', l.total)].join('\n')
114}
115
116// ── stage: who is on screen ──────────────────────────────────────────────────
117
118// Names of the panes that left the stage this call: they finished, went idle or vanished.
119// Unknown/open panes are unreadable, so they keep their slot. `staged` maps name → last pane.
120export function panesLeft(staged, next) {
121  const out = []
122  for (const [name, last] of [...staged]) {
123    const q = next.find((p) => p.name === name)
124    if (q && !LEAVING.has(q.state)) continue
125    staged.delete(name)
126    out.push(name)
127  }
128  for (const q of next) if (ON_STAGE.has(q.state)) staged.set(q.name, q)
129  return out
130}
131
132function newestRoute(routes, name, open = false) {
133  for (let i = routes.length - 1; i >= 0; i--) {
134    const r = routes[i]
135    if (r.name === name && (!open || r.end == null)) return r
136  }
137  return null
138}
139
140export function withRoute(pane, routes = []) {
141  const r = newestRoute(routes, pane.name)
142  return { ...pane, agent: r?.agent ?? null, model: r?.model ?? null, effort: r?.effort ?? null, reason: r?.reason ?? null, start: r?.start ?? null, slice: r?.slice ?? null, verdict: r?.verdict ?? null }
143}
144
145export function endRoute(routes, name, now) {
146  const r = newestRoute(routes, name, true)
147  if (!r) return null
148  r.end = now
149  return r
150}
151
152// With `now`, a subagent that finished less than BYE_MS ago stays on stage to wave bye.
153// leftAt is wall time; end can sit earlier when the harness reports a shorter duration.
154export function waving(a, now) {
155  return now != null && a.state === 'done' && a.leftAt != null && now - a.leftAt < BYE_MS
156}
157
158export function stage({ agents, panes = [], routes = [], run, now = null }) {
159  const subs = [...agents.values()].filter((a) => a.run === run)
160  const working = subs.filter((a) => a.state === 'working').sort((a, b) => a.start - b.start)
161  const byes = subs.filter((a) => waving(a, now)).sort((a, b) => a.start - b.start)
162  const rows = [...working, ...byes, ...panes.filter((p) => ON_STAGE.has(p.state)).map((p) => withRoute(p, routes))]
163  const tally = {
164    working: working.length + panes.filter((p) => p.state === 'working').length,
165    done: subs.filter((a) => a.state === 'done').length + routes.filter((r) => r.run === run && r.end != null).length,
166    tok: subs.reduce((s, a) => s + a.input + a.output, 0),
167  }
168  return { rows, tally }
169}
170
171// A typed /agt run (bare or plugin-qualified), never /agt-ledger, …
172export function isAgtPrompt(text) {
173  return /^\s*\/(agentille:)?agt(\s|$)/.test(String(text ?? ''))
174}
175