SLOPSHOPPER

ctk

Token-light team companion: capped agent teams, risk-based review, disciplined debugging.

panebandguardcommandtoastprompt
★ 2v0.1.8MITupdated 2026-10-26tc3oliver/claude-team-kit/plugins/ctk
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ctk
│ ┃ CTK Mission Control ✕ › fix the failing auth test and add an audit log call │ ┃ ◆ CTK MISSION CONTROL ○ unavailable read-o │ ┃ 1: Overview 2: Workers 3: Tasks ⏺ Read(src/auth.ts) │ ┃ 4: Usage 5: Config 6: Stats 7: Doctor ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ SLOTS · · · · · 0/5 ⎿ Added 2 lines, removed 1 line │ ┃ No native team yet. ⏺ Bash(bun test) │ ┃ Use a team to start coordinated work. ⎿ 3 pass, 1 fail │ ┃ Ordinary subagents are not workers │ ┃ and do not count toward the CTK Worker Cap. ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ TASKS unavailable │ ┃ CTX [███░░░] 49% · $0.42 · unavailable ✻ Worked for 42s · done 4:20 PM │ ┃ 5H 31% · 59m WK – │ ┃ guard Agent Teams are not enabled, so n › /ctk-stats │ ┃ can start ⎿ ctk: CTK session preview-session │ ┃ HUD form HUD form auto HUD form compact H ⎿ ctk: counted by CTK: │ ┃ ⎿ ctk: teammate spawns: 0 accepted, 0 refused at capacity, 0 fai │ ┃ [ Refresh ] [ Close ] Esc closes ⎿ ctk: guard reached by 0 spawn event(s); named agents started o │ ⎿ ctk: peak live teammates: 0 (cap 5); now 0 │ ⎿ ctk: worker models: – │ │ Open CTK Mission Control ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
Open CTK Mission Control
Pane · CTK Mission Control
◆ CTK MISSION CONTROL ○ unavailable read-only 1: Overview 2: Workers 3: Tasks 4: Usage 5: Config 6: Stats 7: Doctor SLOTS · · · · · 0/5 No native team yet. Use a team to start coordinated work. Ordinary subagents are not workers and do not count toward the CTK Worker Cap. TASKS unavailable CTX [███░░░] 49% · $0.42 · unavailable 5H 31% · 59m WK – guard Agent Teams are not enabled, so no teammate can start HUD form HUD form auto HUD form compact HUD form standard [ Refresh ] [ Close ] Esc closes
README

<img src="docs/assets/logo-light.svg" alt="Claude Team Kit: Native agent teams. Under control." width="520">

<h2 align="center">Build with a team. Stay in control.</h2>

Turn complex tasks into coordinated Claude Code agent teams.<br> Set hard limits, watch teammates work, and follow task dependencies live.

<a href="#install"><b>Install CTK</b></a> &nbsp;·&nbsp; <a href="#mission-control"><b>Watch Mission Control</b></a> &nbsp;·&nbsp; <a href="#how-ctk-works"><b>How it works</b></a>

<a href="https://github.com/tc3oliver/claude-team-kit/actions/workflows/ci.yml"><img src="https://github.com/tc3oliver/claude-team-kit/actions/workflows/ci.yml/badge.svg" alt="CI"></a> <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="MIT license"></a>

<img src="docs/assets/mission-control-f.svg" alt="Recording of a real Claude Code session: one plain sentence starts a team, three teammates work, and a click on the CTK line above the prompt opens Mission Control beside the transcript with workers, a task graph whose nodes turn from ready to running to done, and usage" width="900">

Three reasons to use CTK

Coordinated native teams

One goal, several teammates, clear tasks and dependencies. Claude Code's own Agent Teams do the work; CTK's skill guides the lead to split the goal into verifiable tasks and to check the result before calling it done.

Hard worker limits

Choose how many native teammates may be live at once (default 5, from 1 to 12). A spawn above the limit is refused and its task stays pending. Claude Code itself documents no such limit.

Mission Control

See workers, tasks, dependencies and usage without leaving Claude Code. It is read-only: it never starts, stops or changes anything.

Install

Two ways, both through Claude Code's own Plugin Manager.

Install with your AI Agent

Paste this into Claude Code (or another coding agent that can run shell commands):

Install Claude Team Kit (CTK), a Claude Code plugin, by following https://raw.githubusercontent.com/tc3oliver/claude-team-kit/main/INSTALL.md

Manual install

In Claude Code:

/plugin marketplace add tc3oliver/claude-team-kit
/plugin install ctk@ctk-kit

Then run /reload-plugins (or restart). CTK needs Claude Code 2.1.287 or newer.

Turn on Agent Teams. They are experimental and off by default, and a plugin cannot switch them on. Add this to the env object in ~/.claude/settings.json (keep your other settings), then restart:

"env": { "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1" }

Run /ctk-doctor to check the setup: it changes nothing and prints the exact fix for anything missing. Details, Claude 5.x notes and options: Installation.

Your first team

Ask in plain words:

Use a team to implement this feature, write tests, and review the result.

Or be explicit with /ctk:team <goal>. The explicit command always loads the team skill. A plain sentence usually does too, but the model decides, so use the command when you want to be sure (how it works). Then click CTK ▸ above the prompt to open Mission Control.

How CTK works

<img src="docs/assets/how-it-works.svg" alt="Illustration: one goal becomes eight tasks with dependencies; only ready tasks start; three native teammates work at once and a fourth ready task waits; the lead hands the next ready task to an idle teammate; the lead runs the final verification" width="900">

Plan → Coordinate → Execute → Verify

Claude Code provides the agent team and its shared task list. CTK's skill guides the lead through the four steps, and CTK's mod enforces the limit on native teammates. CTK has no scheduler of its own. Full division of work: How CTK works.

Mission Control

Click the CTK ▸ line above the prompt, or run /ctk-mission. Seven views: Overview, Workers, Tasks, Usage, Config, Stats and Doctor; keys 1 to 7 switch, Esc closes. Figures come from Claude Code's own events and API, and anything CTK could not observe reads unavailable, never a made-up zero.

When a team finishes, /ctk-report prints a Markdown summary (tasks, spawns, cost, changed files) to paste into a PR body. Desktop notifications say when a teammate fails or all have finished.

<a href="docs/assets/mission-control-f-workers.svg"><img src="docs/assets/mission-control-f-workers.svg" alt="Mission Control Workers view beside the transcript: three workers on Sonnet 5.5, each with its task, tool-call count, elapsed time and last activity" width="640"></a><br> <b>Live workers</b><br> <sub>Who is running what, on which model, and how recently it did something.</sub>

<a href="docs/assets/mission-control-f-poster.svg"><img src="docs/assets/mission-control-f-poster.svg" alt="Mission Control Tasks view beside the transcript: five finished tasks fan in to a running npm test task, which leads to the report task" width="640"></a><br> <b>Task dependency graph</b><br> <sub>Drawn only from the dependencies the lead declared; waiting, ready, running and done are distinct.</sub>

<a href="docs/assets/mission-control-f-usage.svg"><img src="docs/assets/mission-control-f-usage.svg" alt="Mission Control Usage view beside the transcript: 5-hour and weekly limits with reset times, context use, session cost and tool calls" width="640"></a><br> <b>Usage</b><br> <sub>5-hour and weekly limits, context and session cost, as Claude Code reports them.</sub>

Everything else

  • Models by role. Explorers on Haiku, implementers and reviewers on Sonnet, the high-risk reviewer on Opus, unless a spawn names a model. An optional read-only designer on Opus writes UI/UX briefs; it is new on main and has not yet been part of a recorded run.
  • Risk-based review. /ctk:review scales reviewer depth to the risk of the change.
  • Debugging workflow. /ctk:debug asks for a failing reproduction before a fix; when a standalone debugging skill is installed, generic debugging should use one diagnosis protocol, not two.
  • Optional Backlog / BetFirst composition. CTK runs independently; when explicitly combining tools, the team lead alone owns durable task updates. Workflow contract.
  • Natural-language control. Ask in words for a team or for a setting change, such as "set the worker cap to 2"; the change applies only after you press Confirm in Mission Control (details).
  • Usage HUD. A team line above the prompt with the model, 5-hour and weekly usage, agents against the limit, tasks and cost, fitted to your terminal width. It reads only what Claude Code hands it: no network calls, no model calls.
  • Portable configuration. Change options with /plugin configure ctk@ctk-kit. The optional ctk CLI syncs a profile between machines through a git repository you own, with a secrets scan before every publish (Configuration).
  • Small footprint. The plugin adds about 480 tokens to a session (measured with a real call). No speed, cost or token-saving claim is made.

Limitations

  • Agent Teams are experimental, and Mods, which carry the limit and the team line, are early access. Where Mods are missing, /ctk:team says the limit and the team line are off.
  • The hard limit counts native teammates only. Ordinary subagents are not counted or limited.
  • The team workflow is guided by a skill that the model may follow imperfectly. CTK is not another scheduler.
  • Used interactively on macOS. Linux and Windows are covered by CI only, and the agent install prompt has not been run end to end.
  • Status: public preview, released as the GitHub pre-release v0.1.8: the model no longer sees your quota unless asked, stalled and colliding teammates are flagged, optional usage limits refuse new spawns, and teammates and the lead are woken less for nothing. The install commands above follow main.

More: Limitations · Architecture · Threat model

Documentation

Installation · How CTK works · Mission Control · Natural language · Configuration · Architecture · Limitations · Recordings · Verification record · Comparison with OMC, superpowers and claude-hud · Coming from OMC · Rollback


Contributing · Code of Conduct · Security · Changelog · MIT License · Third-party notices

Source 30 files
hooks/register.tsx 1069 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import { readOptions } from '../shared/policy.ts'
4import type { PolicyOptions } from '../shared/policy.ts'
5import { emptyStats, parseStats, safeSessionId } from '../shared/stats.ts'
6import type { StatsRecord } from '../shared/stats.ts'
7import type { CacheUsage } from './band.ts'
8import { BAND_MARGIN, BAND_SEP, bandParts, cacheHealth, formatSummary, GUARD_QUIET } from './band.ts'
9import { factsFrom, formatDoctor, isCtkStatusLine } from './doctor.ts'
10import type { Facts } from './doctor.ts'
11import { budgetDeny, budgetReached, capacityDeny, CONFIG_TOOL_NAME, effectiveLive, emptySnapshot, guardDeny, settingChangeDeny, isNewToolCall, isLiveStatus, measuredOf, noteSample, prunePending, routed, snapshotOf, startsOutsideCap, STATUS_TOOL_NAME, teamHintFor } from './team.ts'
12import type { PctSample, Snapshot } from './team.ts'
13import { cancel, confirm, describeOptions, emptyPending, OPTION_NAMES, propose, sweep, validateChange } from './config.ts'
14import type { PendingState } from './config.ts'
15import { displayWidth } from '../shared/hudline.ts'
16import { readBranch } from './branch.ts'
17import { TRANSCRIPT_PREFIX } from './ui/workers.tsx'
18import { filterBashOutput, hashOutput } from './outfilter.ts'
19import { formatReport } from './report.ts'
20import { budgetNotice, capNotice, isLifecycleOnly, isOwnAssignmentEcho, LEAD_NAME, NOTIFY_TITLE, stallNotices, teamNotices, teamSummary } from './notify.ts'
21import {
22  buildMission,
23  forcedTierColumns,
24  guardOf,
25  MC_PANE_ID,
26  missionJson,
27  missionText,
28  newMcState,
29  newCollisionNote,
30  newMissionState,
31  noteFileChange,
32  noteLeadBash,
33  noteWorkerActive,
34  noteSpawn,
35  noteTaskCall,
36  noteTeammateIdle,
37  noteWorkerToolCall,
38  toolLabel,
39  noteWorkerTurnEnd,
40  OPEN_KEY,
41  pressMc,
42  signalsOf,
43  stalledOf,
44} from './mission.ts'
45import type { McState, Mission, MissionState } from './mission.ts'
46import { renderMission } from './missionui.tsx'
47import { delayFor, motionOf, newMotionState, observe, reducedFrom } from './ui/motion.ts'
48import type { MotionState } from './ui/motion.ts'
49
50// Every host call is here because `$` may only be handed to top-level functions of this
51// file. Anything pure (cap text, routing, snapshot math, band text) is in team.ts / band.ts.
52// Each host call degrades on failure: a stats or HUD problem never touches a spawn, and
53// the cap itself fails closed.
54
55const STATS_WRITE_GAP_MS = 2000
56/** The band is redrawn for a tool call at most this often. */
57const DRAW_GAP_MS = 1000
58
59type Ctx = {
60  opts: PolicyOptions
61  stats: StatsRecord
62  snap: Snapshot
63  /** The main loop's last turn cache counts, from turn.complete's usage; null before one. */
64  cache: CacheUsage | null
65  /** When the last cap-refusal notice went out (clock ms); 0 before one. */
66  lastCapNotice: number
67  /** When the last usage-limit notice went out (clock ms); 0 before one. */
68  lastBudgetNotice: number
69  /** True once a response read from the cache: before that, a 0% read is the first write, not a lapse. */
70  cacheWarm: boolean
71  /** Spawns that passed the cap and have not returned yet; bumped before the first await. */
72  inflight: number
73  /** Accepted teammates (id -> accepted-at ms) the roster has not listed yet; see effectiveLive. */
74  pending: Map<string, number>
75  /** Last clock reading, the fallback timestamp if the clock fails. */
76  lastNow: number
77  /** False until the first refresh: the band draws nothing before it has figures. */
78  ready: boolean
79  dirty: boolean
80  lastWrite: number
81  lastDraw: number
82  /** tool_use_ids already counted, so one call is never counted twice. */
83  toolSeen: Set<string>
84  /** Recall files written so far this session; the next one goes to slot (this % RECALL_SLOTS). */
85  recallCount: number
86  /** True while the CTK status line is configured: the band then leaves out what it shows. */
87  coordinated: boolean
88  /** The git branch of the session's directory, read from .git/HEAD; null when not in a repository. */
89  branch: string | null
90  /** 2 when CTK_AMBIGUOUS_WIDTH=2 (a terminal that draws │ and … two cells wide). */
91  ambiguous: 1 | 2
92  /** What Mission Control shows: workers, tasks and tool calls observed this session (memory only). */
93  mission: MissionState
94  /** Which view the pane shows and the HUD form; session-local, never saved. */
95  mc: McState
96  /** Whether the Agent Teams flag is set; null until read. */
97  teamsEnabled: boolean | null
98  /** An option change the model proposed and the person has not yet confirmed (memory only). */
99  cfg: PendingState
100  /** The last result of a confirmed or cancelled change, shown in Config. */
101  notice: string | null
102  /** True from just before a confirmed change is written until it is refused: teammate spawns wait, because the reload that follows forgets spawns in flight. */
103  applying: boolean
104  /** Mission Control's motion: highlights and the slow frame. Memory only; reduced motion keeps it static. */
105  mo: MotionState
106  /** The one pending redraw timer, armed only while the pane draws and something moves. */
107  moTimer: { cancel: () => void } | null
108  /** True from a pane draw until the pane is closed by its own button; the timer does nothing otherwise. */
109  paneOpen: boolean
110  /** True from session end: a late pane draw must not arm another timer. */
111  ended: boolean
112  /** Teammates already announced as failed or killed, so each is announced once. */
113  announced: Set<string>
114  /** Recent 5-hour usage readings for the burn-rate forecast (memory only). */
115  samples: PctSample[]
116  /** Workers already announced as stalled; cleared per worker once it is active again. */
117  stallNoticed: Set<string>
118  /** Re-reads the roster while a team is live, so a stall is seen though nothing else happens. */
119  stallTimer: { cancel: () => void } | null
120  /** True once /ctk-report was suggested for the current team run; cleared when a teammate is live again. */
121  reportSuggested: boolean
122  /** Lead compactions and turns where the cache went cold, for the report's Friction section (memory only). */
123  friction: { compactions: number; coldCache: number; echoes: number; lifecycle: number }
124}
125
126async function ctkDir($: EngineInterface): Promise<string | null> {
127  const explicit = await $.env.get('CLAUDE_CONFIG_DIR')
128  const home = explicit ? null : (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
129  const dir = explicit || (home ? `${home}/.claude` : null)
130  return dir === null ? null : `${dir.replace(/[\\/]+$/, '')}/ctk`
131}
132
133async function statsPath($: EngineInterface, sessionId: string): Promise<string | null> {
134  const dir = await ctkDir($)
135  return dir === null ? null : `${dir}/stats/${safeSessionId(sessionId)}.json`
136}
137
138/** The engine's reminder to use the task (or todo) tools; matched by text, as its type name varies by build. */
139const TASK_NUDGE = /(task tools haven't|TodoWrite tool hasn't) been used recently/
140
141/** How many full outputs the Bash filter keeps per session; older ones are overwritten slot by slot. */
142export const RECALL_SLOTS = 32
143/** A session dir untouched this long is taken as dead: a live parallel session is never emptied. */
144const RECALL_STALE_MS = 24 * 3600 * 1000
145
146// One dir per session so a parallel session never overwrites or wipes another's recalls. The Mods API
147// has no delete: an emptied file stays on disk as a zero-byte file.
148async function recallDir($: EngineInterface, sessionId: string): Promise<string | null> {
149  const dir = await ctkDir($)
150  return dir === null ? null : `${dir}/recall/${safeSessionId(sessionId)}`
151}
152
153/** Writes the full output for Read and returns the note for the model, or null when it was not written. */
154async function keepRecall($: EngineInterface, c: Ctx, command: string, stdout: string, stderr: string, hash: string): Promise<string | null> {
155  const dir = await recallDir($, c.stats.sessionId)
156  if (dir === null) return null
157  const path = `${dir}/${c.recallCount % RECALL_SLOTS}.txt`
158  await $.fs.write(path, `ctk recall ${hash}\n$ ${command}\n--- stdout ---\n${stdout}\n--- stderr ---\n${stderr}\n`)
159  c.recallCount += 1
160  return `\n[ctk: output shortened; the full output is in ${path} until this session ends (first line: ctk recall ${hash})]`
161}
162
163/**
164 * Empties non-empty recall files: every one when `olderThanMs` is null, else only files not written
165 * for that long (any session dir, plus loose files of the earlier flat layout). Fails open.
166 */
167async function wipeRecalls($: EngineInterface, olderThanMs: number | null, now: number, onlyDir?: string) {
168  const empty = async (dir: string) => {
169    for (const f of await $.fs.list(dir).catch(() => [])) {
170      if (f.kind === 'file' && f.size > 0 && (olderThanMs === null || now - f.mtimeMs > olderThanMs)) {
171        await $.fs.write(`${dir}/${f.name}`, '').catch(() => undefined)
172      }
173    }
174  }
175  try {
176    if (onlyDir !== undefined) return await empty(onlyDir)
177    const dir = await ctkDir($)
178    if (dir === null) return
179    await empty(`${dir}/recall`)
180    for (const f of await $.fs.list(`${dir}/recall`)) if (f.kind === 'dir') await empty(`${dir}/recall/${f.name}`)
181  } catch {
182    // No directory yet, or unreadable: nothing to wipe.
183  }
184}
185
186// Throttled to one write per STATS_WRITE_GAP_MS; a change inside the gap is written by the
187// next state change, turn end or (forced) session end. `dirty` is cleared before the write
188// so a change made during it is kept, and set again if the write fails, so the forced write
189// at session end retries it.
190async function persist($: EngineInterface, c: Ctx, force = false) {
191  if (!c.opts.recordStats || !c.dirty) return
192  try {
193    const now = await $.clock.now()
194    if (!force && now - c.lastWrite < STATS_WRITE_GAP_MS) return
195    const path = await statsPath($, c.stats.sessionId)
196    if (path === null) return
197    c.lastWrite = now
198    c.dirty = false
199    c.stats.updatedAt = now
200    try {
201      await $.fs.write(path, `${JSON.stringify(c.stats)}\n`)
202    } catch (err) {
203      c.dirty = true
204      throw err
205    }
206  } catch {
207    // A stats failure must never affect a spawn or the HUD.
208  }
209}
210
211// Re-reads .git/HEAD (two small files at most) and redraws the band when the branch changed. Never throws.
212async function refreshBranch($: EngineInterface, c: Ctx) {
213  try {
214    const branch = await readBranch(path => $.fs.read(path), await $.session.cwd())
215    if (branch === c.branch) return
216    c.branch = branch
217    c.dirty = true
218    $.ui.invalidate('ui.render')
219  } catch {
220    // No branch shown; the band is otherwise unchanged.
221  }
222}
223
224/** At most one cap-refusal notice per this gap. */
225const CAP_NOTICE_GAP_MS = 60_000
226
227// One desktop notification per event, and the same text as a toast in the terminal; a terminal without
228// a channel, or any failure, says nothing.
229async function announce($: EngineInterface, texts: string[]) {
230  for (const text of texts) {
231    try {
232      $.ui.toast(text)
233    } catch {
234      // The toast is a courtesy.
235    }
236    await $.ui.notify(text, { title: NOTIFY_TITLE }).catch(() => undefined)
237  }
238}
239
240const STALL_CHECK_MS = 60_000
241
242function armStall($: EngineInterface, c: Ctx) {
243  if (c.stallTimer !== null || c.ended || (c.snap.live ?? 0) === 0) return
244  c.stallTimer = $.clock.after(STALL_CHECK_MS, () => {
245    c.stallTimer = null
246    void refresh($, c)
247  })
248}
249
250// Re-reads the roster and usage, then redraws the band and writes stats. Never throws.
251async function refresh($: EngineInterface, c: Ctx, write = true) {
252  try {
253    const [agents, usage, now, model] = await Promise.all([
254      $.agent.list().catch(() => null),
255      $.session.usage().catch(() => null),
256      $.clock.now().catch(() => 0),
257      $.session.model().catch(() => null),
258    ])
259    if (now > 0) c.lastNow = now
260    const before = c.snap
261    c.snap = snapshotOf(agents, usage, now)
262    // Not awaited: $.ui.notify runs the person's Notification hooks first, and a slow one must not hold a spawn or a turn.
263    void announce($, [...teamNotices(before, c.snap, c.announced), ...(agents === null ? [] : stallNotices(stalledOf(c.mission, c.snap, c.lastNow), c.stallNoticed))])
264    armStall($, c)
265    // Once per team run, when the last live teammate has finished: offer the report as the prompt's dim suggestion.
266    if ((c.snap.live ?? 0) > 0) c.reportSuggested = false
267    else if (before.live !== null && before.live > 0 && c.snap.live === 0 && !c.reportSuggested) {
268      c.reportSuggested = true
269      void Promise.resolve($.prompt.suggest({ text: '/ctk-report' })).catch(() => undefined)
270    }
271    // A failed usage read keeps the last figures: a null must not switch a usage limit off.
272    if (usage !== null) c.stats.measured = measuredOf(usage, model)
273    else if (model !== null) c.stats.measured = { ...c.stats.measured, model }
274    noteSample(c.samples, now, c.stats.measured.fiveHourPct)
275    if (c.snap.live !== null) c.stats.peakLive = Math.max(c.stats.peakLive, c.snap.live)
276    c.ready = true
277    c.dirty = true
278    $.ui.invalidate('ui.render')
279  } catch {
280    // Band and stats are best effort.
281  }
282  await refreshBranch($, c)
283  if (write) await persist($, c)
284}
285
286// Whether the CTK status line is the configured one (any settings level) and whether the Agent Teams
287// flag is set. Best effort: unreadable settings leave the last answers, which start as "no" and
288// "unknown", so the band then shows everything and the guard reads unavailable.
289async function detectEnvironment($: EngineInterface, c: Ctx) {
290  try {
291    const [settings, flag] = await Promise.all([
292      $.settings.read().catch(() => null),
293      $.env.get('CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS').then(value => ({ value }), () => null),
294    ])
295    if (settings !== null) c.coordinated = isCtkStatusLine(settings)
296    c.teamsEnabled = factsFrom({ opts: c.opts, envFlag: flag, settings, toolNames: null }).teamsEnabled
297  } catch {
298    // Keep the previous answers.
299  }
300}
301
302// A tool call changed the count: redraw the band (at most once per DRAW_GAP_MS) and let the
303// throttled stats write pick it up. Never throws, never touches the call.
304async function touch($: EngineInterface, c: Ctx) {
305  try {
306    const now = await $.clock.now()
307    c.lastNow = now
308    c.dirty = true
309    if (now - c.lastDraw >= DRAW_GAP_MS) {
310      c.lastDraw = now
311      $.ui.invalidate('ui.render')
312    }
313  } catch {
314    // The count is kept; the next refresh draws it.
315  }
316  await persist($, c)
317}
318
319// Rejects when the roster or the clock cannot be read: the caller fails closed.
320async function liveTeammates($: EngineInterface, c: Ctx): Promise<number> {
321  const roster = await $.agent.list()
322  const now = await $.clock.now()
323  c.lastNow = now
324  return effectiveLive(roster, c.pending, now)
325}
326
327// What the readiness report and the status tool's preflight fields rest on. Each read
328// degrades to null on failure; nothing is written.
329async function gatherFacts($: EngineInterface, c: Ctx): Promise<Facts> {
330  const [value, settings, tools, engine] = await Promise.all([
331    $.env.get('CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS').then(value => ({ value }), () => null),
332    $.settings.read().catch(() => null),
333    $.tool.list().catch(() => null),
334    // Added after the bundled types (2.1.295): an older build rejects, and the row says so.
335    Promise.resolve().then(() => $.session.version()).then(v => v.version, () => null),
336  ])
337  const base = factsFrom({ opts: c.opts, envFlag: value, settings, toolNames: tools === null ? null : tools.map(t => t.name) })
338  // The guard is judged from what this session saw, with the flag read just now; callers refresh the roster first.
339  const guard = guardOf(c.stats, c.snap, base.teamsEnabled, c.ready)
340  return { ...base, guard: { state: guard.state, why: guard.why }, outsideCap: c.stats.spawnsOutsideCap, engine }
341}
342
343// A session.start that fires again (enable, worker respawn, reload) continues this
344// session's counters from its stats file instead of resetting them.
345async function boot($: EngineInterface, c: Ctx) {
346  try {
347    const now = await $.clock.now()
348    const sessionId = await $.session.id()
349    c.lastNow = now
350    c.stats = emptyStats(sessionId, c.opts.maxWorkers, now)
351    c.lastWrite = 0
352    try {
353      const path = await statsPath($, sessionId)
354      const prior = path === null ? null : parseStats(JSON.parse(await $.fs.read(path)))
355      if (prior !== null && prior.sessionId === sessionId) {
356        c.stats = {
357          ...c.stats,
358          ...prior,
359          maxWorkers: c.opts.maxWorkers,
360          workerModels: prior.workerModels ?? {},
361          subagentModels: prior.subagentModels ?? {},
362          measured: { ...c.stats.measured, ...prior.measured },
363        }
364      }
365    } catch {
366      // No readable prior file: start from zero.
367    }
368  } catch {
369    // Keep the placeholder session id; counters still work.
370  }
371  try {
372    c.ambiguous = (await $.env.get('CTK_AMBIGUOUS_WIDTH')) === '2' ? 2 : 1
373  } catch {
374    // Keep one-cell ambiguous characters.
375  }
376  try {
377    c.mo = newMotionState(reducedFrom(await $.env.get('CTK_REDUCED_MOTION'), await $.env.get('NO_COLOR')))
378  } catch {
379    // Keep motion on its default.
380  }
381  await detectEnvironment($, c)
382  await refresh($, c)
383}
384
385// Stops the redraw timer. Called when the pane closes and when the session ends.
386function stopMotion(c: Ctx, ended = false) {
387  if (ended) c.ended = true
388  c.moTimer?.cancel()
389  c.moTimer = null
390  c.paneOpen = false
391}
392
393// One timer at most, and only while the pane is drawing and something moves (a running worker, or a highlight
394// still to end). Each fire redraws the pane, which arms the next; a pane that is gone draws nothing, so the
395// chain ends by itself.
396function armMotion($: EngineInterface, c: Ctx, mission: Mission, now: number) {
397  if (c.moTimer !== null || c.ended) return
398  const ms = delayFor(c.mo, mission, now)
399  if (ms === null) return
400  c.moTimer = $.clock.after(ms, () => {
401    c.moTimer = null
402    if (!c.paneOpen || c.ended) return
403    try {
404      c.mo = { ...c.mo, frame: c.mo.frame + 1 }
405      $.ui.invalidate('ui.render')
406    } catch {
407      // A redraw that cannot be asked for ends the chain; motion is decoration.
408    }
409  })
410}
411
412const noop = () => {}
413
414const bandSignals = (c: Ctx) => {
415  const s = signalsOf(c.mission, c.snap, c.lastNow)
416  return { stalled: s.stalled, ready: s.ready.length, idleWorkers: s.idleWorkers.length }
417}
418
419/** The one line for the lead when it closes the last open task while teammate completions are unchecked; null otherwise. */
420const uncheckedAtEnd = (m: MissionState): string | null => {
421  const tasks = [...m.tasks.values()].filter(t => t.status !== 'deleted')
422  if (tasks.some(t => t.status !== 'completed')) return null
423  const ids = tasks.filter(t => m.unverified.has(t.id)).map(t => `#${t.id}`)
424  return ids.length === 0 ? null : `CTK: ${ids.join(' ')} ${ids.length === 1 ? 'was' : 'were'} completed by a teammate and not checked by you yet; run the tests or inspect the result before reporting done.`
425}
426
427const missionOf = (c: Ctx) =>
428  buildMission({ stats: c.stats, snap: c.snap, state: c.mission, nowMs: c.lastNow, teamsEnabled: c.teamsEnabled, ready: c.ready, cache: c.cache, samples: c.samples })
429
430// Reads the readiness report for the Doctor view; a failure leaves a one-line reason.
431async function loadDoctor($: EngineInterface, c: Ctx) {
432  try {
433    await refresh($, c, false)
434    c.mc = { ...c.mc, doctorText: formatDoctor(await gatherFacts($, c)) }
435  } catch {
436    c.mc = { ...c.mc, doctorText: 'CTK readiness could not be read.' }
437  }
438}
439
440// Opens Mission Control. It is always called from the person's own press or command, which is what lets
441// the pane be placed at any terminal width. Resolves false when no pane could be drawn.
442async function openMission($: EngineInterface, c: Ctx): Promise<boolean> {
443  try {
444    await refresh($, c)
445    if (c.mc.view === 'doctor') await loadDoctor($, c)
446    const r = await $.ui.open({ id: MC_PANE_ID, title: 'CTK Mission Control', focus: true, closeOnEscape: true, rows: 16 })
447    return r.isPlaced
448  } catch {
449    return false
450  }
451}
452
453// A press on the band or on one of the pane's buttons. Only the band's opens something; the pane's
454// buttons change what the pane shows. A failure here is swallowed: the team is never affected.
455async function handlePress($: EngineInterface, c: Ctx, key: string) {
456  try {
457    if (key === OPEN_KEY) {
458      await openMission($, c)
459      return
460    }
461    if (key.startsWith(TRANSCRIPT_PREFIX)) {
462      // $.ui.view arrived in Claude Code 2.1.300, after the generated types: on an older build the call
463      // throws, as it does for an agent that ended or left the list; both are caught below.
464      // The cast is erased at compile time: the call site must stay `$.ui.view(...)` for the validator.
465      await ($.ui as unknown as { view: (args: { agentId: string }) => Promise<unknown> }).view({ agentId: key.slice(TRANSCRIPT_PREFIX.length) })
466      return
467    }
468    const r = pressMc(c.mc, key)
469    c.mc = r.mc
470    if (r.effect === 'close') {
471      stopMotion(c)
472      await $.ui.close({ id: MC_PANE_ID })
473    }
474    else if (r.effect === 'doctor') await loadDoctor($, c)
475    else if (r.effect === 'refresh') await refresh($, c)
476    else if (r.effect === 'confirm' || r.effect === 'cancel') await decideChange($, c, r.effect, r.id ?? '')
477    $.ui.invalidate('ui.render')
478  } catch {
479    // Mission Control is a view; its failure changes nothing else.
480  }
481}
482
483// The person's answer to a proposed option change. Confirm is the only way a change is applied: the model
484// can only propose. Before the one write (`$.config.set`) the change is checked again against the options
485// as they are now, the setting must not be locked by managed settings, and no teammate may be starting
486// (a successful set reloads this module, which forgets spawns still in flight).
487async function decideChange($: EngineInterface, c: Ctx, answer: 'confirm' | 'cancel', id: string) {
488  const waiting = c.cfg.pending
489  if (waiting === null || waiting.id !== id) {
490    // The press was drawn for a proposal that is gone or has been replaced: it answers nothing.
491    c.notice = waiting === null ? 'Nothing is waiting for your confirmation.' : 'That proposal was replaced. Check the one now waiting; nothing changed.'
492    return
493  }
494  if (answer === 'cancel') {
495    c.cfg = cancel(c.cfg, id).state
496    c.notice = `Cancelled: ${waiting.change.text}. Nothing changed.`
497    return
498  }
499  let now: number
500  try {
501    now = await $.clock.now()
502    // The gate is "no teammate is STARTING" (docs/MISSION-CONTROL.md): roster-live teammates
503    // deliberately do not block a confirmed change — lowering the cap below the live count is
504    // allowed, and the guard then refuses further spawns. The roster read is not for a count but
505    // for its prune: spawns the roster has settled leave c.pending, so only ones still starting
506    // (c.inflight reservations, c.pending not yet listed) block.
507    prunePending(await $.agent.list(), c.pending, now)
508  } catch {
509    c.notice = 'Not applied: the clock or the roster could not be read, so CTK cannot tell the team is settled.'
510    return
511  }
512  if (c.inflight > 0 || c.pending.size > 0) {
513    c.notice = 'Teammates are starting. Confirm again in a moment; nothing changed.'
514    return
515  }
516  const decided = confirm(c.cfg, id, now)
517  c.cfg = decided.state
518  if (decided.outcome.kind === 'expired') {
519    c.notice = 'That proposal is older than 10 minutes and was dropped. Ask again; nothing changed.'
520    return
521  }
522  if (decided.outcome.kind !== 'confirmed') return
523  const change = decided.outcome.change
524  const again = validateChange(change.name, change.value, c.opts)
525  if (!again.ok) {
526    c.notice = `Not applied: ${again.reason}`
527    return
528  }
529  try {
530    const row = (await $.config.list()).find(r => r.key === again.key)
531    if (row === undefined) {
532      c.notice = 'Not applied: this Claude Code has no such setting.'
533      return
534    }
535    if (row.isLocked) {
536      c.notice = 'Not applied: a managed setting controls this option.'
537      return
538    }
539    // The checks above awaited: look again, and from here until the write is refused no teammate may start.
540    if (c.inflight > 0 || c.pending.size > 0) {
541      c.notice = 'Teammates are starting. Confirm again in a moment; nothing changed.'
542      return
543    }
544    c.applying = true
545    // A successful set reloads the module a moment later: write the counters now and the notice first.
546    await persist($, c, true)
547    c.notice = `Applied: ${again.text}.`
548    const res = await $.config.set({ key: again.key, value: again.value })
549    c.applying = false
550    if (res.deny !== undefined) {
551      c.notice = `Not applied: ${res.deny}`
552      return
553    }
554    c.opts = { ...c.opts, [again.name]: again.value }
555    if (again.name === 'maxWorkers') c.stats.maxWorkers = c.opts.maxWorkers
556  } catch {
557    c.applying = false
558    c.notice = 'Not applied: the setting could not be written.'
559  }
560}
561
562// The model's tool for options: `show` lists them, `propose` stores one change and opens Mission Control on it.
563// Nothing is applied here.
564async function configTool($: EngineInterface, c: Ctx, input: Record<string, unknown>): Promise<string> {
565  if (input.action === 'show') {
566    return JSON.stringify({
567      options: describeOptions(c.opts).map(r => ({ option: r.name, value: r.shown, allowed: r.allowed, default: r.defaultShown })),
568      waiting: c.cfg.pending === null ? null : c.cfg.pending.change.text,
569    })
570  }
571  if (input.action !== 'propose') return JSON.stringify({ error: 'action must be "show" or "propose"' })
572  const v = validateChange(String(input.option), input.value, c.opts)
573  if (!v.ok) return JSON.stringify({ status: 'rejected', reason: v.reason, validOptions: OPTION_NAMES })
574  const now = await $.clock.now().catch(() => c.lastNow)
575  c.cfg = propose(c.cfg, v, now).state
576  c.notice = null
577  c.mc = { ...c.mc, view: 'config', selected: null }
578  $.ui.invalidate('ui.render')
579  const shown = await openMission($, c)
580  return JSON.stringify({
581    status: 'pending_user_confirmation',
582    change: v.text,
583    applied: false,
584    next: shown
585      ? 'Nothing has changed yet. Mission Control is open on its Config page with a Confirm button, and the band above the prompt says "Confirm setting" until it is answered. Tell the user, in their language: "I opened CTK Mission Control; press Confirm there to apply it, or Cancel. Nothing changes until you do." Do not say it is done.'
586      : 'Nothing has changed. Mission Control could not be drawn here. Tell the user to run /ctk-mission and press Confirm on its Config page (the band above the prompt also says "Confirm setting"), or to change the option with /plugin configure ctk@ctk-kit. Do not say it is done.',
587  })
588}
589
590export const register: Register = (on, options) => {
591  const opts = readOptions(options)
592  const c: Ctx = {
593    opts,
594    stats: emptyStats('unknown', opts.maxWorkers, 0),
595    snap: emptySnapshot(),
596    cache: null,
597    cacheWarm: false,
598    lastCapNotice: 0,
599    inflight: 0,
600    pending: new Map(),
601    lastNow: 0,
602    ready: false,
603    dirty: false,
604    lastWrite: 0,
605    lastDraw: 0,
606    toolSeen: new Set(),
607    recallCount: 0,
608    coordinated: false,
609    branch: null,
610    ambiguous: 1,
611    mission: newMissionState(),
612    mc: newMcState(),
613    teamsEnabled: null,
614    cfg: emptyPending(),
615    notice: null,
616    applying: false,
617    mo: newMotionState(),
618    moTimer: null,
619    paneOpen: false,
620    ended: false,
621    announced: new Set(),
622    samples: [],
623    lastBudgetNotice: 0,
624    stallNoticed: new Set(),
625    stallTimer: null,
626    reportSuggested: false,
627    friction: { compactions: 0, coldCache: 0, echoes: 0, lifecycle: 0 },
628  }
629
630  // Hard cap on live teammates. `inflight` is bumped synchronously before the first await,
631  // so concurrent spawns from one assistant message each see the others' reservations. A
632  // spawn that has started but not yet released its reservation may be counted twice: the
633  // cap errs toward refusing, never over. Only teammate spawns are gated.
634  on('agent.spawn', async ($, e, next) => {
635    // Every spawn event counts: that this hook is reached at all is what "Guard ON" rests on.
636    c.stats.spawnsSeen += 1
637    c.dirty = true
638    if (startsOutsideCap(e, c.teamsEnabled)) c.stats.spawnsOutsideCap += 1
639    if (e.isTeammate !== true) {
640      const r = await next(routed(e, c.opts))
641      // Started, not merely requested: only a result with an agentId ran a subagent.
642      if (r.deny === undefined && r.agentId !== undefined) c.stats.subagentModels[r.model] = (c.stats.subagentModels[r.model] ?? 0) + 1
643      // Let the band and Mission Control list this subagent now. A failed read never touches the spawn (and must not throw: the spawn already ran).
644      try {
645        await refresh($, c)
646      } catch {
647        // the next refresh will catch up
648      }
649      return r
650    }
651
652    // A confirmed option change is being written; the reload after it forgets reservations, so a
653    // teammate waits (retryable) rather than starting across it. Counted as neither accepted nor failed.
654    if (c.applying) return { deny: settingChangeDeny() }
655
656    c.inflight += 1
657    let held = true
658    const release = () => {
659      if (held) {
660        held = false
661        c.inflight -= 1
662      }
663    }
664
665    try {
666      if (c.opts.stopAtFiveHourPct > 0 || c.opts.stopAtCostUsd > 0) {
667        await refresh($, c, false)
668        const why = budgetReached(c.opts, c.stats.measured)
669        if (why !== null) {
670          release()
671          c.stats.spawnsBudgetStopped += 1
672          const now = await $.clock.now().catch(() => 0)
673          if (now - c.lastBudgetNotice >= CAP_NOTICE_GAP_MS) {
674            c.lastBudgetNotice = now
675            void announce($, [budgetNotice(why)])
676          }
677          return { deny: budgetDeny(why) }
678        }
679      }
680      const live = await liveTeammates($, c)
681      if (live + c.inflight > c.opts.maxWorkers) {
682        const starting = c.inflight - 1
683        release()
684        c.stats.spawnsRejected += 1
685        // A lead that retries a refused spawn would otherwise raise one notice per try.
686        const now = await $.clock.now().catch(() => 0)
687        if (now - c.lastCapNotice >= CAP_NOTICE_GAP_MS) {
688          c.lastCapNotice = now
689          void announce($, [capNotice(live, c.opts.maxWorkers)])
690        }
691        await refresh($, c)
692        return { deny: capacityDeny(live, starting, c.opts.maxWorkers) }
693      }
694      const started = await next(routed(e, c.opts))
695      // Accepted is verified, not assumed: a result without both ids did not start a teammate.
696      if (started.deny === undefined && started.agentId !== undefined && started.teammateId !== undefined) {
697        c.stats.spawnsAccepted += 1
698        c.stats.workerModels[started.model] = (c.stats.workerModels[started.model] ?? 0) + 1
699        // Keep it counted until the roster lists it, and only then release the reservation,
700        // so a roster that lags behind next() cannot let a spawn past the cap.
701        const acceptedAt = await $.clock.now().catch(() => c.lastNow)
702        c.pending.set(started.teammateId, acceptedAt)
703        // `teammateId.split('@')[0]` is always a string, so the name fallback needs no further `??`.
704        noteSpawn(c.mission, started.agentId, e.name ?? started.teammateId.split('@')[0], started.model, acceptedAt)
705      }
706      release()
707      await refresh($, c)
708      return started
709    } finally {
710      release()
711    }
712  }).catch(($, e, next) => {
713    if (next.called) return next(e)
714    if (e.isTeammate !== true) return next(e)
715    c.stats.spawnsFailedClosed += 1
716    return { deny: guardDeny() }
717  })
718
719  // A prompt that asks for several agents, a team or parallel work, or to use CTK, gets one hint line beside it
720  // (never shown, no model call): the model then loads the team skill instead of starting plain subagents. The
721  // prompt's own text is untouched, a prompt that is not the person's own is left alone, and any failure here
722  // lets the prompt through as it was.
723  on('prompt.submit', async ($, e, next) => {
724    await refreshBranch($, c) // a `git checkout` the person ran themselves shows up with their next prompt
725    const hint = c.opts.teamHint ? teamHintFor(e) : null
726    return next(hint === null ? e : { ...e, context: [...(e.context ?? []), hint] })
727  }).catch(($, e, next) => next(e))
728
729  // The engine nudges the model to use the task tools every few turns. Once this session has created
730  // tasks the lead already keeps a task list, so the nudge is noise; before that it is left alone.
731  on('prompt.attachment', async ($, e, next) => {
732    const r = await next(e)
733    if (e.origin?.kind !== 'engine' || ((c.stats.tasks?.created ?? 0) === 0 && c.mission.tasks.size === 0)) return r
734    return TASK_NUDGE.test(r.text ?? '') ? { text: null } : r
735  }).catch(($, e, next) => next(e))
736
737  on('session.start', async ($, e, next) => {
738    c.ended = false
739    try {
740      await $.tool.register({
741        name: STATUS_TOOL_NAME,
742        description: 'Live CTK team state: workers, cap, accepted and refused spawns. Quota, cost and context are left out unless includeUsage is true; ask for them only when the person asks about usage.',
743        inputSchema: { type: 'object', properties: { includeUsage: { type: 'boolean' } } },
744      })
745    } catch {
746      // Without the tool the Agent result's teammate_id still confirms a spawn.
747    }
748    try {
749      await $.tool.register({
750        name: CONFIG_TOOL_NAME,
751        description: 'Show CTK options, or propose one change. A proposal applies nothing: the user confirms it in CTK Mission Control.',
752        inputSchema: {
753          type: 'object',
754          properties: {
755            action: { type: 'string', enum: ['show', 'propose'] },
756            option: { type: 'string', enum: [...OPTION_NAMES] },
757            value: { description: 'maxWorkers: whole number 1-12; models: alias or id; hudBand, recordStats, teamHint and bashFilter: true or false' },
758          },
759          required: ['action'],
760        },
761        isDeferred: true,
762      })
763    } catch {
764      // Without the tool, options are changed with /plugin configure.
765    }
766    try {
767      await $.command.register({ name: 'ctk-stats', description: 'Show CTK team stats for this session.' })
768    } catch {
769      // Without the command `ctk stats` still reads the stats file.
770    }
771    try {
772      await $.command.register({ name: 'ctk-doctor', description: 'Check CTK readiness (read-only).' })
773    } catch {
774      // Without the command the status tool still reports the same facts.
775    }
776    try {
777      await $.command.register({ name: 'ctk-mission', description: 'Open CTK Mission Control (read-only team view).' })
778    } catch {
779      // Without the command the CTK band is the way in.
780    }
781    try {
782      await $.command.register({ name: 'ctk-report', description: 'Print a team summary for a PR body (tasks, spawns, cost, changed files).' })
783    } catch {
784      // Without the command /ctk-stats still prints the counters.
785    }
786    c.cache = null
787    c.cacheWarm = false
788    // Off: recalls from before it was turned off would stay on disk. On: only dead sessions' files go.
789    await wipeRecalls($, c.opts.bashFilter ? RECALL_STALE_MS : null, await $.clock.now().catch(() => 0))
790    const r = await next(e)
791    await boot($, c)
792    return r
793  })
794
795  on('session.measure', async ($, e, next) => {
796    const r = await next(e)
797    await refresh($, c)
798    return r
799  })
800
801  // Teammate status changes raise no session.measure; turn ends do.
802  on('turn.complete', async ($, e, next) => {
803    const r = await next(e)
804    // The main loop only (a subagent's turn carries agentId): the usage is that turn's own, free, no extra call.
805    if (e.agentId === undefined && e.usage !== undefined) {
806      if (e.usage.cache_read_input_tokens > 0) c.cacheWarm = true
807      const was = cacheHealth(c.cache)?.state
808      c.cache = c.cacheWarm ? e.usage : null
809      if (cacheHealth(c.cache)?.state === 'cold' && was !== 'cold') c.friction.coldCache++
810    }
811    await detectEnvironment($, c)
812    await refresh($, c)
813    noteWorkerTurnEnd(c.mission, (e as { agentId?: string }).agentId, c.lastNow, e.usage)
814    return r
815  })
816
817  // An agent that claims a task with TaskUpdate is sent its own task_assignment back, which wakes it for a whole
818  // extra turn. Only that echo (assignedBy is the recipient; the main conversation is the team's lead) is dropped,
819  // and so is shutdown bookkeeping that woke the lead to say nothing. Everything else arrives.
820  on('session.receive', async ($, e, next) => {
821    if (e.agentId === undefined && isLifecycleOnly(e.text)) {
822      c.friction.lifecycle++
823      return { consumed: 'ctk: shutdown bookkeeping' }
824    }
825    const name = e.agentId === undefined ? LEAD_NAME : c.snap.workers.find(w => w.agentId === e.agentId)?.name
826    if (name === undefined || !isOwnAssignmentEcho(e.text, name)) return next(e)
827    c.friction.echoes++
828    return { consumed: 'ctk: own task_assignment echo' }
829  }).catch(($, e, next) => next(e))
830
831  // Whatever compacts, the summarizer is told to keep the live team and open tasks; with no team it is untouched.
832  on('session.compact', async ($, e, next) => {
833    // A subagent's or teammate's own compaction (agentId set) is about its task, not the lead's team.
834    if (e.trigger === 'precompute' || (e as { agentId?: string }).agentId !== undefined) return next(e)
835    c.friction.compactions++
836    const summary = teamSummary(c.snap, c.mission.tasks.values(), c.opts.maxWorkers)
837    return next(summary === null ? e : { ...e, instructions: e.instructions ? `${e.instructions}\n\n${summary}` : summary })
838  }).catch(($, e, next) => next(e))
839
840  on('session.end', async ($, e, next) => {
841    stopMotion(c, true)
842    c.stallTimer?.cancel()
843    c.stallTimer = null
844    await persist($, c, true)
845    // A recall can hold whatever a command printed, secrets included: it outlives no session.
846    const dir = await recallDir($, c.stats.sessionId).catch(() => null)
847    if (dir !== null) await wipeRecalls($, null, 0, dir)
848    return next(e)
849  })
850
851  // Read-only counters: these never block a task. A task event changes only these counters (the
852  // board rides tool.call/noteTaskCall, the roster rides spawn/measure/turn events), so it goes
853  // through the throttled touch() like tool.call does: a burst of 50 events costs bounded host
854  // calls instead of 50 full refreshes, and the counter reaches the stats file on the next
855  // throttled write at the latest — a session's forced end-write guarantees it.
856  on('classic.TaskCreated', async ($, e, next) => {
857    c.stats.tasks = { created: (c.stats.tasks?.created ?? 0) + 1, completed: c.stats.tasks?.completed ?? 0 }
858    await touch($, c)
859    return next(e)
860  })
861
862  on('classic.TaskCompleted', async ($, e, next) => {
863    c.stats.tasks = { created: c.stats.tasks?.created ?? 0, completed: (c.stats.tasks?.completed ?? 0) + 1 }
864    await touch($, c)
865    return next(e)
866  })
867
868  // Every tool call the model makes, in the lead and in subagents and teammates, counts once by
869  // its tool_use_id. The count happens before the call runs and the call is passed on untouched;
870  // a call a hook later denies still counts, because the model made it.
871  on('tool.call', async ($, e, next) => {
872    const isNew = isNewToolCall(c.toolSeen, e.tool_use_id)
873    if (isNew) c.stats.toolCalls += 1
874    // A call still running is activity: a tool that takes over ten minutes must not read as a stall.
875    if (isNew && e.agentId !== undefined) noteWorkerActive(c.mission, e.agentId, await $.clock.now().catch(() => c.lastNow))
876    const r = await next(e)
877    await touch($, c)
878    if (isNew) {
879      noteWorkerToolCall(c.mission, e.agentId, c.lastNow, toolLabel(e.tool, e), r.deny !== undefined || r.isError === true)
880      if (e.tool === 'Bash' && e.agentId === undefined) noteLeadBash(c.mission)
881      // The task board is built from the Task tools' named fields only (see noteTaskCall), and only
882      // from a call that ran: a denied or failed one changes nothing.
883      if (r.deny === undefined && r.isError !== true) {
884        const path = noteFileChange(c.mission, e.tool, e, e.agentId)
885        const note = path === null ? null : newCollisionNote(c.mission, c.snap, path)
886        if (note !== null) return { ...r, context: [...(r.context ?? []), note] }
887      }
888      if ((e.tool === 'TaskCreate' || e.tool === 'TaskUpdate') && r.deny === undefined) {
889        const result = (r as { result?: unknown }).result
890        const taskId = (e as { taskId?: unknown }).taskId
891        const wasOpen = typeof taskId === 'string' && c.mission.tasks.get(taskId)?.status !== 'completed'
892        noteTaskCall(c.mission, e.tool, e as unknown as Record<string, unknown>, result, e.agentId)
893        const failed = (result as { success?: unknown } | null | undefined)?.success === false
894        const completes = (e as { status?: unknown }).status === 'completed' && wasOpen
895        const left = e.agentId === undefined && e.tool === 'TaskUpdate' && completes && !failed && r.isError !== true ? uncheckedAtEnd(c.mission) : null
896        if (left !== null) return { ...r, context: [...(r.context ?? []), left] }
897      }
898    }
899    return r
900  }).catch(($, e, next) => next(e)) // whatever fails here, the model's tool call still goes through
901
902  // Opt-in (bashFilter): a long test, build or log output reaches the model cut to its failures,
903  // with the full text written where Read can get it. Only a write that succeeded is announced;
904  // otherwise the model gets the output untouched.
905  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
906    const r = await next(e)
907    // The inner try/catch (not the .catch below) so a failed recall write returns the original output.
908    try {
909      if (!c.opts.bashFilter || r.deny !== undefined) return r
910      const command = String((e as { command?: unknown }).command ?? '')
911      // A non-zero exit arrives as isError with the text as a string, which core will not take back
912      // as a result (verified on 2.1.310); a deny carries the shortened text as the same error.
913      if (r.isError === true) {
914        if (typeof r.result !== 'string') return r
915        const f = filterBashOutput(command, r.result)
916        const note = f.changed ? await keepRecall($, c, command, r.result, '', f.hash) : null
917        return note === null ? r : { deny: f.text + note }
918      }
919      const out = r.result as { stdout?: unknown; stderr?: unknown; persistedOutputPath?: unknown } | undefined
920      // stdout is only a preview of a persisted output: shortening it would hide what Read can fetch.
921      if (out?.persistedOutputPath) return r
922      if (typeof out?.stdout !== 'string' || typeof out.stderr !== 'string') return r
923      const so = filterBashOutput(command, out.stdout)
924      const se = filterBashOutput(command, out.stderr)
925      if (!so.changed && !se.changed) return r
926      const note = await keepRecall($, c, command, out.stdout, out.stderr, hashOutput(`${out.stdout}\0${out.stderr}`))
927      if (note === null) return r
928      return { result: { ...out, stdout: so.text + note, stderr: se.text }, ...(r.context ? { context: r.context } : {}) }
929    } catch {
930      return r
931    }
932  }).catch(($, e, next) => next(e)) // a failure before next() runs: the call goes through untouched
933
934  // A teammate going idle is the one moment its idle time starts; nothing else reads this event.
935  on('classic.TeammateIdle', async ($, e, next) => {
936    noteTeammateIdle(c.mission, e.teammate_name, await $.clock.now().catch(() => c.lastNow))
937    await refresh($, c)
938    return next(e)
939  }).catch(($, e, next) => next(e))
940
941  // The matcher must be a literal for `claude plugin validate`; policy.test.ts ties it to STATUS_TOOL.
942  on('tool.call', { tool: 'mcp__ctk__ctk_team_status' }, async ($, e, next) => {
943    await refresh($, c)
944    const facts = await gatherFacts($, c)
945    const status = {
946      live: c.snap.live,
947      max: c.opts.maxWorkers,
948      workers: c.snap.workers,
949      rejected: c.stats.spawnsRejected,
950      budgetStopped: c.stats.spawnsBudgetStopped,
951      accepted: c.stats.spawnsAccepted,
952      cap: c.opts.maxWorkers,
953      teamsEnabled: facts.teamsEnabled,
954      taskTools: facts.taskTools,
955      ...missionJson(missionOf(c), (e as { includeUsage?: unknown }).includeUsage === true),
956    }
957    // Claude Code validates a registered tool's result as a string or an array of content
958    // blocks; an MCP-style { content, isError } object is rejected (verified on 2.1.294).
959    return { result: JSON.stringify(status) }
960  })
961
962  on('tool.call', { tool: 'mcp__ctk__ctk_config' }, async ($, e, next) => ({ result: await configTool($, c, e as unknown as Record<string, unknown>) })).catch(
963    () => ({ result: JSON.stringify({ error: 'CTK could not read the request; nothing changed.' }) }),
964  )
965
966  on('command.run', { command: 'ctk-stats' }, async ($, e, next) => {
967    await refresh($, c)
968    return { text: formatSummary(c.stats, c.snap, c.lastNow) }
969  })
970
971  on('command.run', { command: 'ctk-report' }, async ($, e, next) => {
972    await refresh($, c)
973    const teamMs = c.mission.teamStartedAt === null ? null : Math.max(0, c.lastNow - c.mission.teamStartedAt)
974    return { text: formatReport({ stats: c.stats, tasks: c.mission.tasks.values(), files: c.mission.files, filesDropped: c.mission.filesDropped, cwd: await $.session.cwd().catch(() => null), teamMs, friction: { ...c.friction, failed: c.snap.failed ?? 0 } }) }
975  })
976
977  // The command is the way in where the band is hidden, and the answer where no pane can be drawn.
978  on('command.run', { command: 'ctk-mission' }, async ($, e, next) => {
979    if (await openMission($, c)) return { text: 'ctk: Mission Control is open. Esc returns to the prompt; /ctk-stats and /ctk-doctor still work.' }
980    return { text: missionText(missionOf(c)) }
981  })
982
983  // Presses on the band and on Mission Control's buttons. The buttons' own handlers do nothing; the
984  // work is done here, after them.
985  on('ui.press', { plugin: 'ctk' }, async ($, e, next) => {
986    // The button's own handler runs first: handling the press redraws, and a redraw releases the handler.
987    const r = await next(e)
988    await handlePress($, c, e.element)
989    return r
990  }).catch(($, e, next) => next(e))
991
992  on('command.run', { command: 'ctk-doctor' }, async ($, e, next) => {
993    await refresh($, c, false)
994    return { text: formatDoctor(await gatherFacts($, c)) }
995  })
996
997  // The whole band is one button: a click anywhere on it, or Enter once it has the focus (ctrl+x then Tab),
998  // opens Mission Control. The line itself is laid out for the room left after the `CTK ▸` entry.
999  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1000    if (!c.opts.hudBand || !c.ready || e.props.hasSurvey) return next(e)
1001    const { Box, Text, Button } = $.ui.resolve(e)
1002    const entry = 'CTK ▸ '
1003    const guard = guardOf(c.stats, c.snap, c.teamsEnabled, c.ready).label
1004    // Until a teammate has started, the band may show less: only the entry and the guard, or nothing
1005    // (then /ctk-mission is the way in). Once a team has run, the band always shows in full.
1006    const waiting = sweep(c.cfg, c.lastNow).pending !== null
1007    const idle = c.mission.workers.size === 0 && (c.snap.live ?? 0) === 0 && c.stats.spawnsAccepted === 0 && !waiting
1008    if (idle && c.opts.hudIdle === 'hidden') return next(e)
1009    const room = e.props.bodyColumns - displayWidth(entry, c.ambiguous)
1010    const parts =
1011      idle && c.opts.hudIdle === 'minimal'
1012        ? GUARD_QUIET.has(guard) ? [] : [{ text: `Guard ${guard}` }]
1013        : bandParts(c.stats, c.snap, room, {
1014            nowMs: c.lastNow,
1015            ambiguous: c.ambiguous,
1016            coordinated: c.coordinated,
1017            branch: c.branch,
1018            guard,
1019            cache: cacheHealth(c.cache),
1020            ...bandSignals(c),
1021            subagentsLive: c.snap.subagents.filter(a => isLiveStatus(a.status)).length,
1022            pendingChange: waiting,
1023            tierColumns: forcedTierColumns(c.mc.hudMode) ?? e.viewport?.columns ?? e.props.bodyColumns + BAND_MARGIN,
1024          })
1025    return (
1026      <Box marginTop={1}>
1027        <Button key={OPEN_KEY} plain label="Open CTK Mission Control" onPress={noop}>
1028          {/* Accent and underline say the band is a button; the figures stay dim unless one needs attention. */}
1029          <Text bold underline color="suggestion">{entry.trimEnd()}</Text>
1030          <Text> </Text>
1031          {parts.flatMap((p, i) => [
1032            ...(i > 0 ? [<Text key={`s${i}`} dimColor>{BAND_SEP}</Text>] : []),
1033            p.tone === undefined ? (
1034              <Text key={`p${i}`} dimColor>{p.text}</Text>
1035            ) : (
1036              <Text key={`p${i}`} bold={p.tone === 'bad'} color={p.tone === 'bad' ? 'error' : 'warning'}>{p.text}</Text>
1037            ),
1038          ])}
1039        </Button>
1040      </Box>
1041    )
1042  })
1043
1044  on('ui.render', { component: 'Pane' }, async ($, e, next) => {
1045    if (e.requestId !== MC_PANE_ID) return next(e)
1046    const now = await $.clock.now().catch(() => c.lastNow)
1047    c.paneOpen = true
1048    // One Mission and one pending-change sweep for the whole frame: observe, the motion timer and
1049    // the draw all read the same snapshot, so buildMission (with its O(n²) task rows) runs once,
1050    // not three times, and the pane cannot show motion from one draw and rows from another.
1051    const mission = missionOf(c)
1052    const pending = sweep(c.cfg, c.lastNow).pending
1053    c.mo = observe(c.mo, mission, now)
1054    armMotion($, c, mission, now)
1055    return renderMission(
1056      $.ui.resolve(e),
1057      mission,
1058      c.mc,
1059      {
1060        statsText: formatSummary(c.stats, c.snap, c.lastNow),
1061        options: describeOptions(c.opts).map(r => ({ label: r.label, value: r.shown })),
1062        pending: pending === null ? null : { id: pending.id, text: pending.change.text },
1063        notice: c.notice,
1064      },
1065      { ...e.props, ambiguous: c.ambiguous, motion: motionOf(c.mo) },
1066    )
1067  })
1068}
1069
shared/policy.ts 118 lines
1// Single source of truth for the plugin's runtime options (the flat `userConfig`
2// values Claude Code hands to `register(on, options)`).
3//
4// Plain TypeScript with no imports: the plugin loads this file directly (mods may
5// only import their own files) and the CLI imports it too, so defaults can never
6// drift. `test/contract.test.ts` checks plugin.json `userConfig` against this file.
7
8export const ROLES = ['explorer', 'implementer', 'reviewer', 'highRisk', 'designer'] as const
9export type Role = (typeof ROLES)[number]
10
11export const HUD_IDLE = ['full', 'minimal', 'hidden'] as const
12export type HudIdle = (typeof HUD_IDLE)[number]
13
14export type PolicyOptions = {
15  /** Most teammates alive at once. Further spawns are refused with TEAM_CAPACITY_REACHED. */
16  maxWorkers: number
17  /** Model for each CTK agent role: an alias (`haiku`), a full id, or `inherit`. */
18  explorerModel: string
19  implementerModel: string
20  reviewerModel: string
21  highRiskModel: string
22  designerModel: string
23  /** Draw the team band above the prompt. */
24  hudBand: boolean
25  /** What the band shows while no teammate has started: everything, only the CTK entry and guard, or nothing. */
26  hudIdle: HudIdle
27  /** Write small per-session counters to <config>/ctk/stats/ for `ctk stats`. */
28  recordStats: boolean
29  /** Add one hidden hint line to a prompt that asks for several agents or a team, so the model loads the team skill. */
30  teamHint: boolean
31  /** Shrink long test, build and log output from Bash to its failures; the full text stays recallable. Off by default. */
32  bashFilter: boolean
33  /** Refuse a teammate spawn once the 5-hour rate limit has used this percent (1-100). 0 = off. */
34  stopAtFiveHourPct: number
35  /** Refuse a teammate spawn once the session cost reaches this many US dollars. 0 = off. */
36  stopAtCostUsd: number
37}
38
39export const DEFAULT_OPTIONS: PolicyOptions = {
40  maxWorkers: 5,
41  explorerModel: 'haiku',
42  implementerModel: 'sonnet',
43  reviewerModel: 'sonnet',
44  highRiskModel: 'opus',
45  designerModel: 'opus',
46  hudBand: true,
47  hudIdle: 'full',
48  recordStats: true,
49  teamHint: true,
50  bashFilter: false,
51  stopAtFiveHourPct: 0,
52  stopAtCostUsd: 0,
53}
54
55/** Default reasoning effort per role. Mirrors the `effort:` frontmatter in plugins/ctk/agents/. */
56export const DEFAULT_EFFORT: Record<Role, string> = {
57  explorer: 'medium',
58  implementer: 'medium',
59  reviewer: 'medium',
60  highRisk: 'high',
61  designer: 'high',
62}
63
64/** Agent type names as Claude Code reports them for plugin agents (`<plugin>:<name>`). */
65export const AGENT_TYPES: Record<Role, string> = {
66  explorer: 'ctk:explorer',
67  implementer: 'ctk:implementer',
68  reviewer: 'ctk:reviewer',
69  highRisk: 'ctk:high-risk-reviewer',
70  designer: 'ctk:designer',
71}
72
73/** Error code carried in every capacity refusal. The team skill keys off this exact token. */
74export const CAPACITY_CODE = 'TEAM_CAPACITY_REACHED'
75
76/** Error code carried in every usage-limit refusal (stopAtFiveHourPct, stopAtCostUsd). */
77export const BUDGET_CODE = 'TEAM_BUDGET_REACHED'
78
79const str = (v: unknown, d: string) => (typeof v === 'string' && v.trim() !== '' ? v.trim() : d)
80const bool = (v: unknown, d: boolean) => (typeof v === 'boolean' ? v : d)
81
82export const clampMax = (v: unknown): number => {
83  const n = Number(v ?? DEFAULT_OPTIONS.maxWorkers)
84  return Number.isFinite(n) && n >= 1 ? Math.min(Math.floor(n), 12) : DEFAULT_OPTIONS.maxWorkers
85}
86
87/** A usage limit: a finite number in (0, max], else 0 (off). */
88const limit = (v: unknown, max: number): number => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.min(v, max) : 0)
89
90/** Normalize whatever `register` received into a complete, valid PolicyOptions. */
91export const readOptions = (raw: unknown): PolicyOptions => {
92  const o = (raw ?? {}) as Record<string, unknown>
93  return {
94    maxWorkers: clampMax(o.maxWorkers),
95    explorerModel: str(o.explorerModel, DEFAULT_OPTIONS.explorerModel),
96    implementerModel: str(o.implementerModel, DEFAULT_OPTIONS.implementerModel),
97    reviewerModel: str(o.reviewerModel, DEFAULT_OPTIONS.reviewerModel),
98    highRiskModel: str(o.highRiskModel, DEFAULT_OPTIONS.highRiskModel),
99    designerModel: str(o.designerModel, DEFAULT_OPTIONS.designerModel),
100    hudBand: bool(o.hudBand, DEFAULT_OPTIONS.hudBand),
101    hudIdle: (HUD_IDLE as readonly unknown[]).includes(o.hudIdle) ? (o.hudIdle as HudIdle) : DEFAULT_OPTIONS.hudIdle,
102    recordStats: bool(o.recordStats, DEFAULT_OPTIONS.recordStats),
103    teamHint: bool(o.teamHint, DEFAULT_OPTIONS.teamHint),
104    bashFilter: bool(o.bashFilter, DEFAULT_OPTIONS.bashFilter),
105    stopAtFiveHourPct: limit(o.stopAtFiveHourPct, 100),
106    stopAtCostUsd: limit(o.stopAtCostUsd, Infinity),
107  }
108}
109
110export const modelFor = (opts: PolicyOptions, role: Role): string =>
111  ({
112    explorer: opts.explorerModel,
113    implementer: opts.implementerModel,
114    reviewer: opts.reviewerModel,
115    highRisk: opts.highRiskModel,
116    designer: opts.designerModel,
117  })[role]
118
shared/stats.ts 107 lines
1// Per-session counters written by the mod and read by `ctk stats`.
2// Only figures Claude Code reports through its public mod API. Nothing here is a
3// per-worker cost: Claude Code exposes none, so none is invented.
4
5export const STATS_SCHEMA_VERSION = 1
6
7export type StatsRecord = {
8  schemaVersion: typeof STATS_SCHEMA_VERSION
9  sessionId: string
10  /** Epoch ms of the first write for this session. */
11  startedAt: number
12  /** Epoch ms of the latest write. */
13  updatedAt: number
14  /** Configured cap. */
15  maxWorkers: number
16  /** Teammate spawns that Claude Code accepted. */
17  spawnsAccepted: number
18  /** Teammate spawns CTK refused with TEAM_CAPACITY_REACHED. */
19  spawnsRejected: number
20  /** Teammate spawns CTK refused with TEAM_BUDGET_REACHED (a usage limit). */
21  spawnsBudgetStopped: number
22  /** Teammate spawns refused for any other CTK reason (guard failure). */
23  spawnsFailedClosed: number
24  /** Every `agent.spawn` event the guard saw, teammate or not: proof that Claude Code reaches it. */
25  spawnsSeen: number
26  /** Named agents Claude Code started as ordinary subagents while Agent Teams were on (a call with `isolation` is one): outside the cap. */
27  spawnsOutsideCap: number
28  /** Highest number of simultaneously live teammates seen at a spawn decision. */
29  peakLive: number
30  /** Resolved model per accepted spawn, as reported by Claude Code: counts by model id/alias. */
31  workerModels: Record<string, number>
32  /** Resolved model per started ordinary subagent (not a teammate), as reported by Claude Code. */
33  subagentModels: Record<string, number>
34  /** Counts from TaskCreated / TaskCompleted events; null when no such event ever fired. */
35  tasks: { created: number; completed: number } | null
36  /**
37   * Tool calls the model made this session, counted from `tool.call` events: the lead, its
38   * subagents and its teammates together, each tool_use_id once, including calls a hook then denied.
39   */
40  toolCalls: number
41  /** Latest measured figures; null when Claude Code did not report them. */
42  measured: {
43    costUsd: number | null
44    contextPct: number | null
45    fiveHourPct: number | null
46    sevenDayPct: number | null
47    /** ISO 8601 reset time of each window, as Claude Code reported it; null when it did not. */
48    fiveHourResetsAt: string | null
49    sevenDayResetsAt: string | null
50    /** The session's model id, as `$.session.model()` returns it. */
51    model: string | null
52  }
53}
54
55const EMPTY_MEASURED = (): StatsRecord['measured'] => ({
56  costUsd: null,
57  contextPct: null,
58  fiveHourPct: null,
59  sevenDayPct: null,
60  fiveHourResetsAt: null,
61  sevenDayResetsAt: null,
62  model: null,
63})
64
65export const emptyStats = (sessionId: string, maxWorkers: number, now: number): StatsRecord => ({
66  schemaVersion: STATS_SCHEMA_VERSION,
67  sessionId,
68  startedAt: now,
69  updatedAt: now,
70  maxWorkers,
71  spawnsAccepted: 0,
72  spawnsRejected: 0,
73  spawnsBudgetStopped: 0,
74  spawnsFailedClosed: 0,
75  spawnsSeen: 0,
76  spawnsOutsideCap: 0,
77  peakLive: 0,
78  workerModels: {},
79  subagentModels: {},
80  tasks: null,
81  toolCalls: 0,
82  measured: EMPTY_MEASURED(),
83})
84
85/** Session ids become file names; keep them to a safe charset. */
86export const safeSessionId = (id: string): string => id.replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 64) || 'unknown'
87
88const count = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) && v >= 0 ? v : 0)
89
90/** Narrow unknown JSON to a StatsRecord, or null. Used by the CLI on files it did not just write. */
91export const parseStats = (raw: unknown): StatsRecord | null => {
92  if (typeof raw !== 'object' || raw === null) return null
93  const r = raw as Partial<StatsRecord>
94  if (r.schemaVersion !== STATS_SCHEMA_VERSION || typeof r.sessionId !== 'string') return null
95  if (typeof r.spawnsAccepted !== 'number' || typeof r.spawnsRejected !== 'number') return null
96  // Files written by an earlier version lack the newer fields: fill them, never guess them.
97  return {
98    ...(r as StatsRecord),
99    toolCalls: typeof r.toolCalls === 'number' && r.toolCalls >= 0 ? r.toolCalls : 0,
100    spawnsBudgetStopped: count(r.spawnsBudgetStopped),
101    spawnsSeen: count(r.spawnsSeen),
102    spawnsOutsideCap: count(r.spawnsOutsideCap),
103    subagentModels: typeof r.subagentModels === 'object' && r.subagentModels !== null ? r.subagentModels : {},
104    measured: { ...EMPTY_MEASURED(), ...(typeof r.measured === 'object' && r.measured !== null ? r.measured : {}) },
105  }
106}
107
hooks/band.ts 239 lines
1import { DASH, fmtModels, pct, usd } from '../shared/format.ts'
2import { fmtCountdown, fmtPct, layoutItems, layoutLine, pressureTone, resetMs, SEP, truncateToWidth, usageSegment } from '../shared/hudline.ts'
3import type { Segment } from '../shared/hudline.ts'
4import type { StatsRecord } from '../shared/stats.ts'
5import type { Snapshot } from './team.ts'
6
7/** The last API response's prompt-cache figures (a ModelUsage subset), read from local session data only. */
8export type CacheUsage = { input_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
9
10export type CacheHealth = { ratio: number; state: 'ok' | 'low' | 'cold' }
11
12/** Share of the last response's input served from the cache; null before a response or with no input. */
13export const cacheHealth = (u: CacheUsage | null | undefined): CacheHealth | null => {
14  if (!u) return null
15  const total = u.input_tokens + u.cache_read_input_tokens + u.cache_creation_input_tokens
16  if (total <= 0) return null
17  const ratio = u.cache_read_input_tokens / total
18  return { ratio, state: ratio >= 0.7 ? 'ok' : ratio >= 0.3 ? 'low' : 'cold' }
19}
20
21export const cacheText = (h: CacheHealth | null): string =>
22  h === null ? DASH : `${Math.round(h.ratio * 100)}% read${h.state === 'cold' ? ' (cold: the cache lapsed or was rewritten)' : h.state === 'low' ? ' (low)' : ''}`
23
24// Pure text for the AbovePrompt band and the /ctk-stats summary (figure formatting is in
25// shared/format.ts, which `ctk stats` uses too; the width-aware layout is in shared/hudline.ts).
26
27const num = (v: number | null): string => (v === null ? DASH : String(v))
28
29/**
30 * `5s`, `4m`, `1h05m` for a duration in ms; `nullText` stands in for a null duration. The one
31 * body behind the band's `fmtElapsed` (sentinel DASH) and Mission Control's `fmtSpan` (sentinel
32 * UNAVAILABLE): both call sites keep their own null wording, so the formats stay as pinned.
33 */
34export const spanText = (ms: number | null, nullText: string): string => {
35  if (ms === null) return nullText
36  const s = Math.floor(ms / 1000)
37  if (s < 60) return `${s}s`
38  const m = Math.floor(s / 60)
39  return m < 60 ? `${m}m` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}m`
40}
41
42export const fmtElapsed = (ms: number | null): string => spanText(ms, DASH)
43
44/**
45 * `claude-sonnet-5-5` -> `Sonnet 5.5`; `claude-opus-4-1-20250805` -> `Opus 4.1`; an alias such
46 * as `sonnet` -> `Sonnet`. Anything unrecognised is shown as given, minus a `claude-` prefix.
47 */
48export const modelLabel = (id: string | null): string | null => {
49  if (id === null) return null
50  const raw = id.trim().replace(/^claude-/i, '')
51  if (raw === '') return null
52  const long = /\[1m\]$/i.test(raw) ? ' 1M' : ''
53  const parts = raw.replace(/\[.*\]$/, '').split('-')
54  const family = parts[0] ?? ''
55  if (!/^(opus|sonnet|haiku|fable)$/i.test(family)) return raw
56  const nums = parts.slice(1).filter(p => /^\d{1,2}$/.test(p))
57  return `${family[0]?.toUpperCase()}${family.slice(1).toLowerCase()}${nums.length > 0 ? ` ${nums.slice(0, 2).join('.')}` : ''}${long}`
58}
59
60export type BandOptions = {
61  /** Epoch ms the reset countdowns count from: the clock reading of the last refresh. */
62  nowMs?: number
63  /** 2 on terminals that draw `│` and `…` two cells wide (CTK_AMBIGUOUS_WIDTH=2). */
64  ambiguous?: 1 | 2
65  /**
66   * True when the CTK status line is configured. It then shows model, usage, context, cost and
67   * branch under the prompt, so the band keeps to what only the mod can know and nothing is
68   * drawn twice.
69   */
70  coordinated?: boolean
71  /**
72   * The terminal width that picks the form (full, abbreviated, essentials). Default: the width the
73   * engine reports for the band plus its margin; a forced HUD form passes its own.
74   */
75  tierColumns?: number
76  /** The guard's one-word state (`ready`, `ON`, `ERR`, ...); drawn only when it needs attention (`ERR`, `unavailable`, `–`). */
77  guard?: string
78  /** Ordinary subagents live now (not teammates); shown as `Sub 2` only when above zero. */
79  subagentsLive?: number
80  /** An option change waits for the person's Confirm in Mission Control; the band says so until it is answered. */
81  pendingChange?: boolean
82  /** The git branch of the session's directory (a short commit id when detached); left out when null or the status line shows it. */
83  branch?: string | null
84  /** Prompt-cache health of the last response; drawn only when it is not null. */
85  cache?: CacheHealth | null
86  /** Workers that look stuck, longest first as given; drawn as a warning cell only when not empty. */
87  stalled?: { name: string; forMs: number }[]
88  /** Tasks that could start and teammates with nothing to do; drawn only when both are above zero. Display only. */
89  ready?: number
90  idleWorkers?: number
91}
92
93/** Guard states that need no words: it is working, or has nothing to do yet. */
94export const GUARD_QUIET = new Set(['ON', 'ready'])
95
96/** Above this many tasks the band points at Mission Control for the whole list. */
97const MORE_TASKS = 6
98
99// Rank when the line is too wide (higher stays longer). Model, usage, context and cost are
100// the status line's too; the rest is the team's.
101const RANK = { stalled: 97, pending: 95, fiveHour: 100, sevenDay: 90, tools: 80, context: 110, model: 60, branch: 55, agents: 50, guard: 45, tasks: 40, subagents: 35, cost: 30, cache: 25, readyIdle: 20, workerModels: 10 }
102
103export const bandSegments = (s: StatsRecord, snap: Snapshot, opts: BandOptions = {}): Segment[] => {
104  const now = opts.nowMs ?? 0
105  const out: Segment[] = []
106  const mine = opts.coordinated !== true
107
108  if (mine) {
109    out.push({ id: 'model', prio: RANK.model, bold: true, ...modelSegment(s.measured.model) })
110    const ctx = s.measured.contextPct
111    const text = `Ctx ${fmtPct(ctx)}`
112    out.push({ id: 'ctx', prio: RANK.context, missing: fmtPct(ctx) === DASH, tone: pressureTone(ctx), forms: [text, text, text] })
113    out.push(
114      usageSegment('5h', '5h', RANK.fiveHour, { pct: s.measured.fiveHourPct, resetsAtMs: resetMs(s.measured.fiveHourResetsAt) }, now),
115      usageSegment('wk', 'Wk', RANK.sevenDay, { pct: s.measured.sevenDayPct, resetsAtMs: resetMs(s.measured.sevenDayResetsAt) }, now),
116    )
117  }
118  if (mine && opts.branch) {
119    const full = `git:${opts.branch}`
120    out.push({ id: 'branch', prio: RANK.branch, forms: [truncateToWidth(full, 28, opts.ambiguous), truncateToWidth(full, 20, opts.ambiguous), ''] })
121  }
122  out.push({ id: 'tools', prio: RANK.tools, forms: [`🔧 ${s.toolCalls}`, `🔧${s.toolCalls}`, `🔧${s.toolCalls}`] })
123  out.push(agentsSegment(s, snap))
124  if (opts.guard !== undefined && !GUARD_QUIET.has(opts.guard)) {
125    const text = `Guard ${opts.guard}`
126    out.push({ id: 'guard', prio: RANK.guard, missing: opts.guard === DASH, forms: [text, text, ''] })
127  }
128  if (opts.subagentsLive !== undefined && opts.subagentsLive > 0) {
129    const n = opts.subagentsLive
130    out.push({ id: 'subagents', prio: RANK.subagents, forms: [`Sub ${n}`, `S${n}`, ''] })
131  }
132  if (opts.cache) {
133    const { ratio, state } = opts.cache
134    const text = state === 'cold' ? 'Cache cold' : `Cache ${Math.round(ratio * 100)}%`
135    out.push({ id: 'cache', prio: RANK.cache, ...(state === 'ok' ? {} : { tone: state === 'cold' ? ('bad' as const) : ('warn' as const) }), forms: [text, text, ''] })
136  }
137  const stuck = opts.stalled?.[0]
138  if (stuck !== undefined) {
139    const more = opts.stalled!.length > 1 ? ` +${opts.stalled!.length - 1}` : ''
140    out.push({ id: 'stalled', prio: RANK.stalled, tone: 'warn', forms: [`⚠ ${stuck.name} stalled ${spanText(stuck.forMs, DASH)}${more}`, `⚠ ${stuck.name} ${spanText(stuck.forMs, DASH)}${more}`, `⚠ stalled${more}`] })
141  }
142  if ((opts.ready ?? 0) > 0 && (opts.idleWorkers ?? 0) > 0) {
143    const text = `${opts.ready} ready · ${opts.idleWorkers} idle`
144    out.push({ id: 'readyIdle', prio: RANK.readyIdle, forms: [text, text, ''] })
145  }
146  if (opts.pendingChange === true) out.push({ id: 'pending', prio: RANK.pending, bold: true, forms: ['Confirm setting: click here', 'Confirm: click', '!'] })
147  if (s.tasks !== null) {
148    const text = `Tasks ${s.tasks.completed}/${s.tasks.created}`
149    // Past a handful of tasks the pane lists only some of them, so say where the whole board is.
150    const more = s.tasks.created > MORE_TASKS
151    out.push({ id: 'tasks', prio: RANK.tasks, forms: [more ? `${text} (full list: Mission Control)` : text, more ? `${text} (list: click here)` : text, ''] })
152  }
153  if (mine) {
154    const cost = usd(s.measured.costUsd)
155    const elapsed = snap.elapsedMs === null || s.measured.costUsd === null ? null : fmtElapsed(snap.elapsedMs)
156    out.push({
157      id: 'cost',
158      prio: RANK.cost,
159      missing: s.measured.costUsd === null,
160      forms: [elapsed === null ? cost : `${cost} (${elapsed})`, cost, ''],
161    })
162  }
163  if (Object.keys(s.workerModels).length > 0) {
164    out.push({ id: 'workers', prio: RANK.workerModels, forms: [`models ${fmtModels(s.workerModels)}`, '', ''] })
165  }
166  return out
167}
168
169const modelSegment = (id: string | null): Pick<Segment, 'forms' | 'missing'> => {
170  const label = modelLabel(id)
171  return label === null ? { missing: true, forms: [DASH, DASH, DASH] } : { forms: [label, label, ''] }
172}
173
174// `🤖 2/3`: live teammates (busy and idle, the figure the cap counts) over the cap. A refused
175// spawn is the cap doing its job, so it travels with the segment and is dropped with it.
176const agentsSegment = (s: StatsRecord, snap: Snapshot): Segment => {
177  const live = num(snap.live)
178  const refused = s.spawnsRejected
179  const busy = snap.busy !== null && snap.live !== null && snap.live > 0 ? ` (${snap.busy} busy)` : ''
180  return {
181    id: 'agents',
182    prio: RANK.agents,
183    missing: snap.live === null,
184    forms: [
185      `🤖 ${live}/${s.maxWorkers}${refused > 0 ? ` (refused ${refused})` : busy}`,
186      `🤖${live}/${s.maxWorkers}${refused > 0 ? ` !${refused}` : ''}`,
187      `🤖${live}/${s.maxWorkers}${refused > 0 ? ` !${refused}` : ''}`,
188    ],
189  }
190}
191
192/**
193 * The band's body is 5 columns narrower than the terminal (Claude Code keeps the right edge for its
194 * own `[-]` control; measured on 2.1.295: bodyColumns 125, 115, 95, 75, 55 at terminal widths 130,
195 * 120, 100, 80, 60). The tier follows the terminal, so 120+ columns is the full form, as documented.
196 */
197export const BAND_MARGIN = 5
198
199const bandLayout = (s: StatsRecord, snap: Snapshot, bodyColumns: number, opts: BandOptions) => ({
200  segments: bandSegments(s, snap, opts),
201  layout: { columns: bodyColumns, tierColumns: opts.tierColumns ?? bodyColumns + BAND_MARGIN, ambiguous: opts.ambiguous },
202})
203
204export const formatBand = (s: StatsRecord, snap: Snapshot, bodyColumns: number, opts: BandOptions = {}): string => {
205  const { segments, layout } = bandLayout(s, snap, bodyColumns, opts)
206  return layoutLine(segments, layout)
207}
208
209/** The same line as pieces, so the band can colour a figure that needs attention (`tone`) and leave the rest dim. */
210export const bandParts = (s: StatsRecord, snap: Snapshot, bodyColumns: number, opts: BandOptions = {}): { text: string; tone?: 'warn' | 'bad' }[] => {
211  const { segments, layout } = bandLayout(s, snap, bodyColumns, opts)
212  return layoutItems(segments, layout).map(i => (i.s.tone === undefined ? { text: i.text } : { text: i.text, tone: i.s.tone }))
213}
214
215export { SEP as BAND_SEP }
216
217const limitLine = (label: string, pctValue: number | null, resetsAt: string | null, now: number): string => {
218  const left = fmtCountdown(resetMs(resetsAt), now)
219  const stale = resetMs(resetsAt) !== null && left === null
220  return `${label}: ${stale ? DASH : pct(pctValue)}${left === null ? '' : ` (resets in ${left})`}`
221}
222
223export const formatSummary = (s: StatsRecord, snap: Snapshot, nowMs = 0): string =>
224  [
225    `CTK session ${s.sessionId}`,
226    'counted by CTK:',
227    `  teammate spawns: ${s.spawnsAccepted} accepted, ${s.spawnsRejected} refused at capacity, ${s.spawnsBudgetStopped > 0 ? `${s.spawnsBudgetStopped} stopped by a usage limit, ` : ''}${s.spawnsFailedClosed} failed closed`,
228    `  guard reached by ${s.spawnsSeen} spawn event(s); named agents started outside the cap (with isolation): ${s.spawnsOutsideCap}`,
229    `  peak live teammates: ${s.peakLive} (cap ${s.maxWorkers}); now ${num(snap.live)}`,
230    `  worker models: ${fmtModels(s.workerModels) || DASH}`,
231    `  tasks created/completed: ${s.tasks === null ? `${DASH} (no task event seen)` : `${s.tasks.created}/${s.tasks.completed}`}`,
232    `  tool calls: ${s.toolCalls} (lead, subagents and teammates; each call once)`,
233    'measured (reported by Claude Code):',
234    `  model: ${modelLabel(s.measured.model) ?? DASH}  cost: ${usd(s.measured.costUsd)}  context: ${pct(s.measured.contextPct)}`,
235    `  ${limitLine('5h limit', s.measured.fiveHourPct, s.measured.fiveHourResetsAt, nowMs)}  ${limitLine('7d limit', s.measured.sevenDayPct, s.measured.sevenDayResetsAt, nowMs)}`,
236    `  elapsed: ${fmtElapsed(snap.elapsedMs)}`,
237    '  per-worker cost: not available from Claude Code',
238  ].join('\n')
239
hooks/doctor.ts 166 lines
1import type { PolicyOptions } from '../shared/policy.ts'
2
3// Pure readiness logic for /ctk-doctor and the status tool's preflight fields. The host
4// reads (env, settings, tool list) are in register.tsx; a state that could not be read is
5// null here and is reported as unknown, never guessed.
6
7export const TEAMS_FLAG = 'CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS'
8/** The Claude Code version the bundled API types were written by (first line of .claude-plugin/types/claude-code/index.d.ts). */
9export const TYPES_VERSION = '2.1.295'
10
11export const TEAMS_FIX = `Add {"env":{"${TEAMS_FLAG}":"1"}} to ~/.claude/settings.json, then restart Claude Code.`
12
13export type Facts = {
14  maxWorkers: number
15  /** Whether settings hold /pluginConfigs/ctk@…/options/maxWorkers; null when settings could not be read. */
16  capFromSettings: boolean | null
17  /** Null when neither the process environment nor settings could be read. */
18  teamsEnabled: boolean | null
19  /** True only when TaskCreate is in the tool list: a deferred tool is not listed, so absence proves nothing. */
20  taskTools: boolean | null
21  /** False when the tool list itself could not be read. */
22  toolListRead: boolean
23  statusLine: boolean | null
24  /** True when the configured status line is CTK's own script; null when settings could not be read. */
25  ctkStatusLine: boolean | null
26  hudBand: boolean
27  recordStats: boolean
28  teamHint: boolean
29  bashFilter: boolean
30  /** The guard's state and the reason for it (see guardOf); null when it was not computed. */
31  guard: { state: 'active' | 'available' | 'unavailable' | 'error'; why: string } | null
32  /** Named agents started as ordinary subagents this session (outside the cap). */
33  outsideCap: number
34  /** `$.session.version().version`; null when it could not be read. */
35  engine?: string | null
36}
37
38export type Inputs = {
39  opts: PolicyOptions
40  /** `$.env.get(TEAMS_FLAG)`: null when the read failed. It also sees values from settings.json `env`. */
41  envFlag: { value: string | undefined } | null
42  settings: Readonly<Record<string, unknown>> | null
43  toolNames: string[] | null
44  guard?: Facts['guard']
45  outsideCap?: number
46}
47
48const record = (v: unknown): Record<string, unknown> | null =>
49  typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null
50
51const truthy = (v: string): boolean => ['1', 'true', 'yes', 'on'].includes(v.trim().toLowerCase())
52
53/** Whether the merged settings point the status line at CTK's script (the command itself is never shown). */
54export const isCtkStatusLine = (settings: Readonly<Record<string, unknown>> | null): boolean => {
55  const command = record(settings?.statusLine)?.command
56  return typeof command === 'string' && command.includes('ctk-statusline')
57}
58
59export const factsFrom = ({ opts, envFlag, settings, toolNames, guard = null, outsideCap = 0 }: Inputs): Facts => {
60  const settingsFlag = record(settings?.env)?.[TEAMS_FLAG]
61  const raw = envFlag?.value ?? (typeof settingsFlag === 'string' ? settingsFlag : undefined)
62  const pluginConfigs = record(settings?.pluginConfigs)
63  return {
64    maxWorkers: opts.maxWorkers,
65    capFromSettings:
66      settings === null
67        ? null
68        : Object.entries(pluginConfigs ?? {}).some(
69            ([k, v]) => (k === 'ctk' || k.startsWith('ctk@')) && record(record(v)?.options)?.maxWorkers !== undefined,
70          ),
71    teamsEnabled: raw !== undefined ? truthy(raw) : envFlag !== null ? false : null,
72    taskTools: toolNames?.includes('TaskCreate') ? true : null,
73    toolListRead: toolNames !== null,
74    statusLine: settings === null ? null : settings.statusLine !== undefined,
75    ctkStatusLine: settings === null ? null : isCtkStatusLine(settings),
76    hudBand: opts.hudBand,
77    recordStats: opts.recordStats,
78    teamHint: opts.teamHint,
79    bashFilter: opts.bashFilter,
80    guard,
81    outsideCap,
82  }
83}
84
85type Row = { level: 'ok' | 'info' | 'action'; text: string; fix?: string }
86
87const guardRow = (f: Facts): Row => {
88  if (f.guard === null) return { level: 'info', text: 'guard: state not computed' }
89  const text = `guard: ${f.guard.state === 'active' ? 'ON' : f.guard.state} (${f.guard.why})`
90  if (f.guard.state === 'error') return { level: 'action', text, fix: 'Do not rely on the cap until this clears; /ctk-stats lists the counters, and a restart of Claude Code reloads the guard.' }
91  return { level: f.guard.state === 'active' ? 'ok' : 'info', text }
92}
93
94const minor = (v: string): string => v.split('.').slice(0, 2).join('.')
95
96const engineRow = (engine: string | null | undefined): Row => {
97  if (engine == null) return { level: 'info', text: `engine: version not readable (plugin built against ${TYPES_VERSION})` }
98  const text = `engine: ${engine} (plugin built against ${TYPES_VERSION})`
99  return minor(engine) === minor(TYPES_VERSION)
100    ? { level: 'info', text }
101    : { level: 'info', text: `${text}, minor version differs: an API the plugin uses may have changed` }
102}
103
104export const doctorRows = (f: Facts): Row[] => [
105  { level: 'ok', text: 'mod: loaded (it answered this command)' },
106  engineRow(f.engine),
107  guardRow(f),
108  {
109    level: 'ok',
110    text: `cap: ${f.maxWorkers} live teammates (${f.capFromSettings === null ? 'source not checked' : f.capFromSettings ? 'set in plugin options' : 'default'})`,
111  },
112  f.teamsEnabled === true
113    ? { level: 'ok', text: `agent teams: enabled (${TEAMS_FLAG})` }
114    : f.teamsEnabled === false
115      ? { level: 'action', text: `agent teams: not enabled (${TEAMS_FLAG} is not set to 1)`, fix: TEAMS_FIX }
116      : { level: 'info', text: `agent teams: unknown (${TEAMS_FLAG} could not be read)` },
117  f.outsideCap > 0
118    ? { level: 'info', text: `outside the cap: ${f.outsideCap} named agent(s) started as ordinary subagents this session (a call with isolation does that)` }
119    : { level: 'info', text: 'the cap counts teammates only: ordinary subagents, and named agents started with isolation, are not limited' },
120  f.taskTools === true
121    ? { level: 'ok', text: 'task tools: TaskCreate is available' }
122    : {
123        level: 'info',
124        text: f.toolListRead
125          ? 'task tools: unknown (TaskCreate is not in the listed tools; deferred tools are not listed)'
126          : 'task tools: unknown (tool list not readable)',
127      },
128  f.statusLine === null
129    ? { level: 'info', text: 'statusLine: not checked (settings not readable)' }
130    : f.ctkStatusLine === true
131      ? { level: 'info', text: 'statusLine: CTK’s, under the prompt (model, usage, context, cost); the band above it shows only tools, agents and tasks' }
132      : f.statusLine
133        ? { level: 'info', text: 'statusLine: yours is configured and left untouched; the band above the prompt shows model, usage and team figures' }
134        : { level: 'info', text: 'statusLine: none configured (optional); the band above the prompt shows model, usage and team figures' },
135  f.hudBand
136    ? { level: 'ok', text: 'team band: on' }
137    : { level: 'info', text: 'team band: off (plugin option hudBand)' },
138  f.recordStats
139    ? { level: 'ok', text: 'stats recording: on' }
140    : { level: 'info', text: 'stats recording: off (plugin option recordStats)' },
141  f.teamHint
142    ? { level: 'ok', text: 'team hint: on (a prompt that asks for several agents or a team gets one hidden hint line; plugin option teamHint)' }
143    : { level: 'info', text: 'team hint: off (plugin option teamHint)' },
144  f.bashFilter
145    ? { level: 'ok', text: 'bash filter: on (long test, build and log output is cut to its failures; the full text is kept for Read; plugin option bashFilter)' }
146    : { level: 'info', text: 'bash filter: off (plugin option bashFilter)' },
147]
148
149export const formatDoctor = (f: Facts): string => {
150  const rows = doctorRows(f)
151  const actions = rows.filter(r => r.level === 'action').length
152  const lines = rows.flatMap(r => [`[${r.level}]`.padEnd(9) + r.text, ...(r.fix === undefined ? [] : [`         fix: ${r.fix}`])])
153  return ['CTK readiness (read-only; nothing is changed):', ...lines, actions === 0 ? 'ready' : `${actions} action(s) needed`].join('\n')
154}
155
156/** Reads a formatDoctor report back into rows for the Mission Control view; the report stays the one source. */
157export const parseDoctor = (text: string): Row[] => {
158  const rows: Row[] = []
159  for (const l of text.split('\n')) {
160    const m = /^\[(ok|info|action)\]\s+(.*)$/.exec(l)
161    if (m !== null) rows.push({ level: m[1] as Row['level'], text: m[2]! })
162    else if (/^\s+fix: /.test(l) && rows.length > 0) rows[rows.length - 1]!.fix = l.replace(/^\s+fix: /, '')
163  }
164  return rows
165}
166
hooks/team.ts 249 lines
1import type { AgentInfo, AgentSpawnInput, SessionUsage } from 'claude-code'
2
3import { AGENT_TYPES, BUDGET_CODE, CAPACITY_CODE, modelFor, ROLES } from '../shared/policy.ts'
4import type { PolicyOptions, Role } from '../shared/policy.ts'
5import type { StatsRecord } from '../shared/stats.ts'
6
7// Pure team logic: no host calls here. Everything that needs `$` lives in register.tsx.
8
9export const GUARD_CODE = 'TEAM_GUARD_FAILED'
10
11/** Statuses of an agent that is done, however it ended: it holds no slot and is counted nowhere as live. */
12const TERMINAL = new Set(['completed', 'failed', 'killed'])
13
14/**
15 * The one live-status predicate (the cap, the band's subagent count and Mission Control's all read
16 * it). Anything not terminal is live — an unknown status word counts as live on purpose: the cap
17 * then refuses rather than over-admits, and no view hides an agent that may still be running.
18 */
19export const isLiveStatus = (status: string): boolean => !TERMINAL.has(status)
20
21/** Working or blocked mid-task (`waiting` is stuck on an approval, so not free to reuse). */
22const BUSY = new Set(['pending', 'running', 'waiting'])
23
24export const isLiveTeammate = (a: AgentInfo): boolean => a.teammateId !== undefined && isLiveStatus(a.status)
25
26export type Worker = { name: string; teammateId: string; agentId: string; status: string }
27
28/** An agent the roster lists without a teammate address: an ordinary subagent, which the cap neither counts nor limits. */
29export type Subagent = { agentId: string; type: string; description: string; status: string }
30
31/** What the last refresh saw. A null figure was not reported; it renders as a dash. */
32export type Snapshot = {
33  /** Null when the roster could not be read. */
34  busy: number | null
35  idle: number | null
36  done: number | null
37  /** Teammates that failed or were killed; a subset of `done`. */
38  failed: number | null
39  live: number | null
40  workers: Worker[]
41  /** Ordinary subagents the roster lists (not teammates); empty when the roster could not be read. */
42  subagents: Subagent[]
43  elapsedMs: number | null
44}
45
46export const emptySnapshot = (): Snapshot => ({ busy: null, idle: null, done: null, failed: null, live: null, workers: [], subagents: [], elapsedMs: null })
47
48export const snapshotOf = (agents: AgentInfo[] | null, usage: SessionUsage | null, now: number): Snapshot => {
49  const elapsedMs = usage !== null && usage.startedAt > 0 && now >= usage.startedAt ? now - usage.startedAt : null
50  if (agents === null) return { ...emptySnapshot(), elapsedMs }
51  const team = agents.filter(a => a.teammateId !== undefined)
52  const count = (statuses: Set<string>) => team.filter(a => statuses.has(a.status)).length
53  return {
54    busy: count(BUSY),
55    idle: team.filter(a => a.status === 'idle').length,
56    done: team.filter(a => !isLiveStatus(a.status)).length,
57    failed: team.filter(a => a.status === 'failed' || a.status === 'killed').length,
58    live: team.filter(isLiveTeammate).length,
59    workers: team.map(a => ({
60      name: (a.teammateId as string).split('@')[0] as string,
61      teammateId: a.teammateId as string,
62      agentId: a.id,
63      status: a.status,
64    })),
65    subagents: agents.filter(a => a.teammateId === undefined).map(a => ({ agentId: a.id, type: a.type, description: a.description, status: a.status })),
66    elapsedMs,
67  }
68}
69
70export const measuredOf = (usage: SessionUsage | null, model: string | null = null): StatsRecord['measured'] => {
71  const limit = (kind: string) => usage?.rateLimits.find(l => l.kind === kind)
72  return {
73    costUsd: usage?.cost?.usd ?? null,
74    contextPct: usage?.context.percent ?? null,
75    fiveHourPct: limit('five_hour')?.percentUsed ?? null,
76    sevenDayPct: limit('seven_day')?.percentUsed ?? null,
77    fiveHourResetsAt: limit('five_hour')?.resetsAt ?? null,
78    sevenDayResetsAt: limit('seven_day')?.resetsAt ?? null,
79    model,
80  }
81}
82
83/** Most tool_use_ids remembered for de-duplication; the oldest half is forgotten past this. */
84export const TOOL_SEEN_LIMIT = 4096
85
86/**
87 * Whether a `tool.call` event is a call not yet counted. A call is identified by its
88 * tool_use_id, so an event that fires twice for one call (a retried hook, a replay) counts
89 * once; an event without an id cannot be recognised again and counts every time.
90 */
91export const isNewToolCall = (seen: Set<string>, toolUseId: unknown): boolean => {
92  if (typeof toolUseId !== 'string' || toolUseId === '') return true
93  if (seen.has(toolUseId)) return false
94  seen.add(toolUseId)
95  if (seen.size > TOOL_SEEN_LIMIT) {
96    let drop = seen.size - TOOL_SEEN_LIMIT / 2
97    for (const id of seen) {
98      if (drop-- <= 0) break
99      seen.delete(id)
100    }
101  }
102  return true
103}
104
105/** A teammate spawn that arrives while a confirmed option change is being written. The skill treats this code like any guard refusal: leave the task pending and retry. */
106export const settingChangeDeny = (): string =>
107  `${GUARD_CODE}: CTK is applying a setting change you confirmed. Do not treat this worker as started; leave its task pending and retry in a moment.`
108
109export const capacityDeny = (live: number, starting: number, max: number): string =>
110  `${CAPACITY_CODE}: live=${live} starting=${starting} max=${max}. Do not treat this worker as started; leave its task pending; reuse an idle teammate via SendMessage or wait for one to finish.`
111
112/** The usage limit a teammate spawn would cross, as words; null when no limit is set or reached. A figure not reported never trips a limit. */
113export const budgetReached = (opts: PolicyOptions, m: Pick<StatsRecord['measured'], 'fiveHourPct' | 'costUsd'>): string | null => {
114  if (opts.stopAtFiveHourPct > 0 && m.fiveHourPct !== null && m.fiveHourPct >= opts.stopAtFiveHourPct) {
115    return `the 5-hour limit is at ${Math.round(m.fiveHourPct)}% (stopAtFiveHourPct=${opts.stopAtFiveHourPct})`
116  }
117  if (opts.stopAtCostUsd > 0 && m.costUsd !== null && m.costUsd >= opts.stopAtCostUsd) {
118    return `the session cost is $${m.costUsd.toFixed(2)} (stopAtCostUsd=${opts.stopAtCostUsd})`
119  }
120  return null
121}
122
123export const budgetDeny = (why: string): string =>
124  `${BUDGET_CODE}: ${why}. Do not treat this worker as started; leave its task pending and do not retry; tell the person, who can raise the limit (/ctk-config) or continue without more teammates.`
125
126export type PctSample = { t: number; pct: number }
127
128/** Samples kept for the forecast, at least this far apart. */
129const SAMPLE_GAP_MS = 30_000
130const SAMPLE_MAX = 60
131const FORECAST_MIN_SPAN_MS = 10 * 60_000
132
133/** Records the 5-hour percent. A drop means the window reset, so older samples no longer apply. Mutates `samples`. */
134export const noteSample = (samples: PctSample[], now: number, pct: number | null): void => {
135  if (pct === null || now <= 0) return
136  const last = samples[samples.length - 1]
137  if (last !== undefined && pct < last.pct) samples.length = 0
138  else if (last !== undefined && now - last.t < SAMPLE_GAP_MS) return
139  samples.push({ t: now, pct })
140  if (samples.length > SAMPLE_MAX) samples.shift()
141}
142
143/** Epoch ms at which the percent is projected to reach 100 at the pace of the samples; null without 10 minutes of rising samples, or when the reset comes first. */
144export const forecastFull = (samples: PctSample[], now: number, resetAt: number | null): number | null => {
145  const first = samples[0]
146  const last = samples[samples.length - 1]
147  if (first === undefined || last === undefined || resetAt === null || last.t - first.t < FORECAST_MIN_SPAN_MS || last.pct <= first.pct) return null
148  const full = last.t + ((100 - last.pct) * (last.t - first.t)) / (last.pct - first.pct)
149  return full > now && full < resetAt ? full : null
150}
151
152export const guardDeny = (): string =>
153  `${GUARD_CODE}: the teammate cap could not be checked. Do not treat this worker as started; leave its task pending and retry later.`
154
155/**
156 * A named agent that Claude Code started as an ordinary subagent while Agent Teams were on. Claude Code's
157 * documentation says a named call becomes a teammate unless it is a fork or passes `isolation`, and a
158 * live probe on 2.1.295 showed exactly that: the spawn carried no `isTeammate`. The cap cannot gate it
159 * (the event does not say why), so the guard only counts it, to keep "outside the cap" visible.
160 */
161export const startsOutsideCap = (e: Pick<AgentSpawnInput, 'isTeammate' | 'name' | 'fork' | 'workflow'>, teamsEnabled: boolean | null): boolean =>
162  teamsEnabled === true && e.isTeammate !== true && e.name !== undefined && e.fork !== true && e.workflow === undefined
163
164export const roleOf = (subagentType: string): Role | undefined => ROLES.find(r => AGENT_TYPES[r] === subagentType)
165
166/**
167 * Model routing by role. An explicit `model` always wins and `inherit` passes through.
168 * Effort is deliberately not overridden here: the options carry models only, so effort
169 * comes from each agent's frontmatter (`effort:` in plugins/ctk/agents/).
170 */
171export const routed = (e: AgentSpawnInput, opts: PolicyOptions): AgentSpawnInput => {
172  if (e.model !== undefined) return e
173  const role = roleOf(e.subagentType)
174  if (role === undefined) return e
175  const model = modelFor(opts, role)
176  return model === 'inherit' ? e : { ...e, model }
177}
178
179/** Full name Claude Code gives the status tool (`mcp__<plugin>__<name>`); the tool.call hook matches it. */
180export const STATUS_TOOL_NAME = 'ctk_team_status'
181export const STATUS_TOOL = `mcp__ctk__${STATUS_TOOL_NAME}`
182export const CONFIG_TOOL_NAME = 'ctk_config'
183export const CONFIG_TOOL = `mcp__ctk__${CONFIG_TOOL_NAME}`
184
185/** How long an accepted teammate stays counted while the roster has not listed it yet. */
186export const PENDING_TTL_MS = 10_000
187
188/**
189 * Drops the accepted spawns the roster has settled: one it now lists (its status governs from
190 * then on) and one older than the TTL, so a teammate that finished instantly cannot hold a slot
191 * forever. Mutates `pending`; what is left in it is still starting.
192 */
193export const prunePending = (roster: AgentInfo[], pending: Map<string, number>, now: number): void => {
194  const listed = new Set(roster.flatMap(a => (a.teammateId === undefined ? [] : [a.teammateId])))
195  for (const [id, at] of pending) {
196    if (listed.has(id) || now - at >= PENDING_TTL_MS) pending.delete(id)
197  }
198}
199
200/**
201 * Live teammates for the cap: the roster's live ones plus accepted ones the roster has not
202 * listed yet (teammateId -> accepted-at ms). Prunes `pending` first (see prunePending).
203 */
204export const effectiveLive = (roster: AgentInfo[], pending: Map<string, number>, now: number): number => {
205  prunePending(roster, pending, now)
206  return roster.filter(isLiveTeammate).length + pending.size
207}
208
209// --- Natural-language entry ----------------------------------------------------------------
210
211/**
212 * Whether a prompt asks for several agents, a team or parallel work, or to use CTK. A small, fixed set of
213 * phrases in English and Chinese: it is not a classifier. All it can do is attach a one-line hint (see
214 * TEAM_HINT) that the model reads beside the prompt; the model still decides, and the team skill's own
215 * intent gate still applies. A prompt that is a command, or already names the team skill, is left alone.
216 */
217const TEAM_ASK = [
218  // Several agents, by name: "multi-agent", "multiple subagents", "3 teammates", "多agent", "多個 Agent"
219  /多\s*(個|个|一個)?\s*(sub-?)?(agents?|代理)/i,
220  /\b(multi|multiple|several|parallel)[\s-]*(sub-?)?agents?\b/i,
221  /\b(\d+|two|three|four|five|several)\s+(sub-?agents?|teammates?|agents)\b/i,
222  // A team of agents: "agent team", "use a team", "spin up a team", "team of agents"
223  /\bagents?\s+team\b/i,
224  /\bteam\s+of\s+(sub-?)?(agents?|teammates?)\b/i,
225  /\b(use|using|spin up|assemble)\s+(a|an|the|your)?\s*team\b/i,
226  // Chinese: an action verb must follow, so "使用團隊功能" or "開團隊頁面" do not match
227  /(開|組|啟動|用|使用)\s*(一個|個)?\s*(agent\s*)?(team|團隊)\s*(來|去|做|處理|完成|幫|執行|跑)/i,
228  /(平行|並行)\s*(的)?\s*(agents?|代理|subagent)/i,
229  // CTK itself: "use ctk", "ctk 流程"
230  /\bctk\s*(的)?\s*(流程|workflow|team)/i,
231  /(?<![A-Za-z])(use|using)\s+ctk\b/i,
232  /(用|使用)\s*ctk/i,
233]
234
235export const teamIntent = (text: string): boolean => {
236  const t = text.slice(0, 2000).trim()
237  // A slash command ("/ctk:team ...", "/ctk-doctor") is not a request in words; a path such as /Users/x/repo is not a command.
238  if (t === '' || /^\/[\w:-]+(\s|$)/.test(t)) return false
239  return TEAM_ASK.some(re => re.test(t))
240}
241
242/** What the model reads beside such a prompt. Conditional on purpose: a mention of "team" in another sense is not a request. */
243export const TEAM_HINT =
244  'CTK note: if this request asks for several agents, a team or parallel work, invoke the ctk:team skill first (Skill tool) and follow it. It names every worker, which makes each one a native teammate that the worker cap and Mission Control track; an Agent call without a name is only an ordinary subagent. If the request is not about agents, ignore this note.'
245
246/** The hint for a prompt, or null. Only the person's own words count: the terminal's Enter and the Remote Control bridge. */
247export const teamHintFor = (e: { text: string; origin?: { kind: string } }): string | null =>
248  (e.origin?.kind === 'composer' || e.origin?.kind === 'bridge') && teamIntent(e.text) ? TEAM_HINT : null
249
hooks/config.ts 284 lines
1import { DEFAULT_OPTIONS, HUD_IDLE } from '../shared/policy.ts'
2import type { PolicyOptions } from '../shared/policy.ts'
3
4// Pure logic for changing CTK's own plugin options from the Mods API: what may be set, how a
5// requested value is checked, and the pending-change state machine behind the Confirm button.
6// No host calls here and nothing is written: the one write, `$.config.set`, lives in the caller
7// and runs only after `confirm` returned `confirmed`. docs/CONFIG-API-NOTES.md has the evidence.
8
9/** The plugin's name; `$.config` rows are keyed `<plugin>.<field>`. */
10export const PLUGIN_NAME = 'ctk'
11
12export const OPTION_NAMES = [
13  'maxWorkers',
14  'explorerModel',
15  'implementerModel',
16  'reviewerModel',
17  'highRiskModel',
18  'designerModel',
19  'hudBand',
20  'hudIdle',
21  'recordStats',
22  'teamHint',
23  'bashFilter',
24  'stopAtFiveHourPct',
25  'stopAtCostUsd',
26] as const satisfies readonly (keyof PolicyOptions)[]
27export type OptionName = (typeof OPTION_NAMES)[number]
28
29// Compile-time guard: a PolicyOptions field missing from OPTION_NAMES fails the typecheck here.
30type Missing = Exclude<keyof PolicyOptions, OptionName>
31const noneMissing: [Missing] extends [never] ? true : never = true
32void noneMissing
33
34export type OptionValue = number | string | boolean
35
36export const isOptionName = (name: unknown): name is OptionName => (OPTION_NAMES as readonly unknown[]).includes(name)
37
38/** The `$.config.list()` / `$.config.set` row key of an option: `ctk.maxWorkers`. */
39export const optionKey = (name: OptionName): string => `${PLUGIN_NAME}.${name}`
40
41/** The cap the CLI schema (src/core/schema.ts) and the plugin.json `min`/`max` both enforce. */
42export const WORKERS_MIN = 1
43export const WORKERS_MAX = 12
44export const MODEL_MAX_LENGTH = 100
45/** A pending change older than this cannot be confirmed. */
46export const PENDING_TTL_MS = 10 * 60_000
47
48const MODEL_PATTERN = /^[A-Za-z0-9._:\-[\]]+$/
49// Credential shapes and long opaque tokens. A model alias or id is never one of these.
50const SECRET_PATTERN = /^(?:(?:sk|pk|rk)-[A-Za-z0-9_-]{8,}|gh[pos]_[A-Za-z0-9]{8,}|xox[a-z]-|AKIA[A-Z0-9]{12,}|AIza[A-Za-z0-9_-]{20,})|[A-Za-z0-9_-]{40,}/
51
52type Meta = { label: string; hint: string; allowed: string }
53
54const MODEL_ALLOWED = 'an alias (haiku, sonnet, opus), a full model id, or inherit'
55
56const META: Record<OptionName, Meta> = {
57  maxWorkers: {
58    label: 'Max live teammates',
59    hint: 'Hard cap on teammates alive at once. Further spawns are refused.',
60    allowed: `a whole number from ${WORKERS_MIN} to ${WORKERS_MAX}`,
61  },
62  explorerModel: { label: 'Explorer model', hint: 'Model for ctk:explorer.', allowed: MODEL_ALLOWED },
63  implementerModel: { label: 'Implementer model', hint: 'Model for ctk:implementer.', allowed: MODEL_ALLOWED },
64  reviewerModel: { label: 'Reviewer model', hint: 'Model for ctk:reviewer.', allowed: MODEL_ALLOWED },
65  highRiskModel: { label: 'High-risk reviewer model', hint: 'Model for ctk:high-risk-reviewer.', allowed: MODEL_ALLOWED },
66  designerModel: { label: 'Designer model', hint: 'Model for ctk:designer.', allowed: MODEL_ALLOWED },
67  hudBand: { label: 'Team band', hint: 'Show the one-line team status band above the prompt.', allowed: 'on or off' },
68  hudIdle: { label: 'Band while no team runs', hint: 'What the band shows until a teammate has started.', allowed: 'full, minimal or hidden' },
69  recordStats: { label: 'Record stats', hint: 'Write small per-session counters for the ctk stats command.', allowed: 'on or off' },
70  teamHint: { label: 'Team hint', hint: 'Add one hidden hint line to a prompt that asks for several agents or a team.', allowed: 'on or off' },
71  bashFilter: { label: 'Bash output filter', hint: 'Shrink long test, build and log output to its failures; the full text stays recallable.', allowed: 'on or off' },
72  stopAtFiveHourPct: { label: 'Stop at 5-hour usage', hint: 'Refuse new teammates once the 5-hour limit has used this percent. 0 is off.', allowed: 'a number from 1 to 100, or 0 for off' },
73  stopAtCostUsd: { label: 'Stop at session cost', hint: 'Refuse new teammates once the session cost reaches this many dollars. 0 is off.', allowed: 'a dollar amount above 0, or 0 for off' },
74}
75
76/** The sections Mission Control groups the options into, in display order. */
77export const OPTION_GROUPS: { title: string; names: OptionName[] }[] = [
78  { title: 'Team', names: ['maxWorkers'] },
79  { title: 'Models', names: ['explorerModel', 'implementerModel', 'reviewerModel', 'highRiskModel', 'designerModel'] },
80  { title: 'Band', names: ['hudBand', 'hudIdle'] },
81  { title: 'Limits', names: ['stopAtFiveHourPct', 'stopAtCostUsd'] },
82  { title: 'Other', names: ['recordStats', 'teamHint', 'bashFilter'] },
83]
84
85/** The group title for an option label as the pane receives it; unknown labels fall under Other. */
86export const groupOfLabel = (label: string): string => {
87  const name = OPTION_NAMES.find(n => META[n].label === label)
88  return OPTION_GROUPS.find(g => name !== undefined && g.names.includes(name))?.title ?? 'Other'
89}
90
91export type OptionRow = {
92  name: OptionName
93  label: string
94  /** The value now, typed. */
95  value: OptionValue
96  /** The value now as text (`on` / `off` for a switch). */
97  shown: string
98  hint: string
99  allowed: string
100  /** The shipped default, as text. */
101  defaultShown: string
102}
103
104export const showValue = (v: OptionValue): string => (typeof v === 'boolean' ? (v ? 'on' : 'off') : String(v))
105
106/** Every option with its current value, for display in a pane or a `show` answer. */
107export const describeOptions = (opts: PolicyOptions): OptionRow[] =>
108  OPTION_NAMES.map(name => ({
109    name,
110    label: META[name].label,
111    value: opts[name],
112    shown: showValue(opts[name]),
113    hint: META[name].hint,
114    allowed: META[name].allowed,
115    defaultShown: showValue(DEFAULT_OPTIONS[name]),
116  }))
117
118export type Change = {
119  name: OptionName
120  /** The key `$.config.set` takes. */
121  key: string
122  /** The validated, correctly typed new value. */
123  value: OptionValue
124  /** The value when the change was proposed. */
125  from: OptionValue
126  /** One line for the person: `Max live teammates (maxWorkers): 3 -> 2`. */
127  text: string
128}
129
130export type ValidateOk = { ok: true } & Change
131export type ValidateFail = {
132  ok: false
133  /** What went wrong, in words the model can relay. Never echoes a rejected string. */
134  reason: string
135  code: 'unknown_option' | 'invalid_value' | 'unchanged'
136}
137export type ValidateResult = ValidateOk | ValidateFail
138
139const fail = (code: ValidateFail['code'], reason: string): ValidateFail => ({ ok: false, reason, code })
140
141const SAFE_NAME = /^[A-Za-z0-9_.-]{1,40}$/
142
143const parseWorkers = (raw: unknown): number | string => {
144  let n: number | undefined
145  if (typeof raw === 'number') n = raw
146  else if (typeof raw === 'string' && /^\s*\d{1,3}\s*$/.test(raw)) n = Number(raw)
147  if (n === undefined) return `maxWorkers takes ${META.maxWorkers.allowed}, not ${typeof raw === 'string' ? 'that text' : typeof raw}.`
148  if (!Number.isInteger(n) || n < WORKERS_MIN || n > WORKERS_MAX) {
149    return `maxWorkers takes ${META.maxWorkers.allowed}; ${Number.isFinite(n) ? n : 'that value'} does not qualify.`
150  }
151  return n
152}
153
154const parseBudget = (name: 'stopAtFiveHourPct' | 'stopAtCostUsd', raw: unknown): number => {
155  const text = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
156  const n = typeof raw === 'number' ? raw : text === 'off' ? 0 : /^\d{1,6}(\.\d{1,2})?$/.test(text) ? Number(text) : NaN
157  if (!Number.isFinite(n) || n < 0 || (name === 'stopAtFiveHourPct' && (n > 100 || (n > 0 && n < 1)))) throw new Error(`${name} takes ${META[name].allowed}.`)
158  return n
159}
160
161const parseModel = (name: OptionName, raw: unknown): string => {
162  if (typeof raw !== 'string') throw new Error(`${name} takes ${MODEL_ALLOWED}, not ${typeof raw}.`)
163  const v = raw.trim()
164  if (v === '') throw new Error(`${name} cannot be empty; use inherit to follow the session model.`)
165  if (v.length > MODEL_MAX_LENGTH) throw new Error(`${name} is limited to ${MODEL_MAX_LENGTH} characters.`)
166  if (!MODEL_PATTERN.test(v)) {
167    throw new Error(`${name} takes ${MODEL_ALLOWED}: letters, digits and . _ : - [ ] only, no spaces.`)
168  }
169  if (SECRET_PATTERN.test(v)) throw new Error(`${name} looks like a credential, not a model; nothing was accepted.`)
170  return v
171}
172
173const parseIdle = (name: OptionName, raw: unknown): string => {
174  const v = typeof raw === 'string' ? raw.trim().toLowerCase() : ''
175  if ((HUD_IDLE as readonly string[]).includes(v)) return v
176  throw new Error(`${name} takes ${META[name].allowed}.`)
177}
178
179const parseSwitch = (name: OptionName, raw: unknown): boolean => {
180  if (typeof raw === 'boolean') return raw
181  if (typeof raw === 'string') {
182    const v = raw.trim().toLowerCase()
183    if (v === 'true' || v === 'on') return true
184    if (v === 'false' || v === 'off') return false
185  }
186  throw new Error(`${name} takes ${META[name].allowed} (true or false).`)
187}
188
189/**
190 * Check a requested change against CTK's schema and the current options. Rejects unknown
191 * names, out-of-range or non-integer caps, malformed model ids, non-boolean switches, and a
192 * value equal to the current one. A rejection never echoes a rejected string.
193 */
194export const validateChange = (name: string, raw: unknown, opts: PolicyOptions): ValidateResult => {
195  if (!isOptionName(name)) {
196    const shown = SAFE_NAME.test(String(name)) ? ` "${String(name)}"` : ''
197    return fail('unknown_option', `Unknown option${shown}. Valid options: ${OPTION_NAMES.join(', ')}.`)
198  }
199  let value: OptionValue
200  if (name === 'maxWorkers') {
201    const n = parseWorkers(raw)
202    if (typeof n === 'string') return fail('invalid_value', n)
203    value = n
204  } else {
205    try {
206      if (name === 'stopAtFiveHourPct' || name === 'stopAtCostUsd') value = parseBudget(name, raw)
207      else value = name === 'hudBand' || name === 'recordStats' || name === 'teamHint' || name === 'bashFilter' ? parseSwitch(name, raw) : name === 'hudIdle' ? parseIdle(name, raw) : parseModel(name, raw)
208    } catch (err) {
209      return fail('invalid_value', (err as Error).message)
210    }
211  }
212  const from = opts[name]
213  if (value === from) return fail('unchanged', `${name} is already ${showValue(from)}; nothing to change.`)
214  return {
215    ok: true,
216    name,
217    key: optionKey(name),
218    value,
219    from,
220    text: `${META[name].label} (${name}): ${showValue(from)} -> ${showValue(value)}`,
221  }
222}
223
224// ---- pending change: proposed by the model, applied only after the person confirms ----
225
226export type Pending = { id: string; change: Change; createdAt: number }
227
228/** At most one change waits at a time; `seq` numbers the proposals so a stale button cannot match a newer one. */
229export type PendingState = { pending: Pending | null; seq: number }
230
231export const emptyPending = (): PendingState => ({ pending: null, seq: 0 })
232
233export const isExpired = (p: Pending, now: number): boolean => now - p.createdAt > PENDING_TTL_MS
234
235export type ProposeOutcome = { kind: 'proposed'; pending: Pending; replaced: Pending | null }
236export type ConfirmOutcome =
237  | { kind: 'confirmed'; change: Change }
238  | { kind: 'none' }
239  | { kind: 'mismatch'; pendingId: string }
240  | { kind: 'expired'; change: Change }
241export type CancelOutcome = { kind: 'cancelled'; change: Change } | { kind: 'none' } | { kind: 'mismatch'; pendingId: string }
242
243/** Store a validated change as the pending one. A change already waiting is replaced and reported. */
244export const propose = (
245  state: PendingState,
246  change: Change,
247  now: number,
248): { state: PendingState; outcome: ProposeOutcome } => {
249  const seq = state.seq + 1
250  const pending: Pending = { id: `c${seq}`, change, createdAt: now }
251  return { state: { pending, seq }, outcome: { kind: 'proposed', pending, replaced: state.pending } }
252}
253
254/**
255 * The person pressed Confirm on proposal `id`. Only a live, matching proposal is released, once:
256 * the state is cleared so a second press finds nothing. A different id leaves the waiting one alone;
257 * an expired one is dropped and not released. The caller then calls `$.config.set` with `change.key`
258 * and `change.value`, and re-runs `validateChange` against the options as they are at that moment.
259 */
260export const confirm = (
261  state: PendingState,
262  id: string,
263  now: number,
264): { state: PendingState; outcome: ConfirmOutcome } => {
265  const p = state.pending
266  if (p === null) return { state, outcome: { kind: 'none' } }
267  if (p.id !== id) return { state, outcome: { kind: 'mismatch', pendingId: p.id } }
268  const cleared: PendingState = { pending: null, seq: state.seq }
269  if (isExpired(p, now)) return { state: cleared, outcome: { kind: 'expired', change: p.change } }
270  return { state: cleared, outcome: { kind: 'confirmed', change: p.change } }
271}
272
273/** The person pressed Cancel on proposal `id`: discarded, nothing applied. */
274export const cancel = (state: PendingState, id: string): { state: PendingState; outcome: CancelOutcome } => {
275  const p = state.pending
276  if (p === null) return { state, outcome: { kind: 'none' } }
277  if (p.id !== id) return { state, outcome: { kind: 'mismatch', pendingId: p.id } }
278  return { state: { pending: null, seq: state.seq }, outcome: { kind: 'cancelled', change: p.change } }
279}
280
281/** Drop an expired proposal (for a redraw); a live one is returned as it was. */
282export const sweep = (state: PendingState, now: number): PendingState =>
283  state.pending !== null && isExpired(state.pending, now) ? { pending: null, seq: state.seq } : state
284
shared/hudline.ts 253 lines
1// Width-aware layout for the one-line HUD, shared by the Mods band (hooks/band.ts). The
2// dependency-free status line script (statusline/ctk-statusline.mjs) carries a copy of the
3// same functions because it is installed as a single file; tests/hudline.test.ts runs both
4// over one matrix so the two cannot drift. Pure, no imports.
5
6export const DASH = '–'
7export const SEP = ' │ '
8
9/** Terminal width used when none is known: narrow enough to be safe in an 80-column terminal. */
10export const DEFAULT_COLUMNS = 80
11
12/** 0 = 120+ columns (full), 1 = 80-119 (abbreviated), 2 = under 80 (only the essentials). */
13export type Tier = 0 | 1 | 2
14
15/** At most this many segments are drawn in the narrowest tier. */
16export const MIN_TIER_SEGMENTS = 3
17
18export const tierOf = (columns: number): Tier => (columns >= 120 ? 0 : columns >= 80 ? 1 : 2)
19
20export type Segment = {
21  id: string
22  /** Higher is kept longer when the line is too wide. */
23  prio: number
24  /** The text per tier, richest first; '' means the segment is not drawn at that tier. */
25  forms: readonly [string, string, string]
26  /** True when the figure was not reported: drawn as a dash and dropped before any real figure. */
27  missing?: boolean
28  bold?: boolean
29  /** Reminder colour when colour is on: yellow for `warn`, bold red for `bad`. */
30  tone?: 'warn' | 'bad'
31}
32
33// --- Display width -----------------------------------------------------------------------
34
35// CSI and OSC sequences. They take no cells.
36const ANSI = /\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g
37
38export const stripAnsi = (s: string): string => s.replace(ANSI, '')
39
40type Range = readonly [number, number]
41
42const inRanges = (cp: number, ranges: readonly Range[]): boolean => {
43  for (const [lo, hi] of ranges) if (cp >= lo && cp <= hi) return true
44  return false
45}
46
47// Combining marks, joiners and variation selectors take no cell of their own.
48const ZERO: readonly Range[] = [
49  [0x0300, 0x036f], [0x0483, 0x0489], [0x0591, 0x05bd], [0x0610, 0x061a], [0x064b, 0x065f],
50  [0x200b, 0x200f], [0x202a, 0x202e], [0x2060, 0x2064], [0x20d0, 0x20ff], [0x1ab0, 0x1aff],
51  [0x1dc0, 0x1dff], [0xfe00, 0xfe0f], [0xfe20, 0xfe2f], [0xe0100, 0xe01ef],
52]
53
54// East Asian Wide and Fullwidth, plus the emoji blocks terminals draw two cells wide.
55const WIDE: readonly Range[] = [
56  [0x1100, 0x115f], [0x231a, 0x231b], [0x23e9, 0x23ec], [0x2705, 0x2705], [0x2e80, 0x303e], [0x3041, 0x33ff],
57  [0x3400, 0x4dbf], [0x4e00, 0x9fff], [0xa000, 0xa4cf], [0xa960, 0xa97f], [0xac00, 0xd7a3],
58  [0xf900, 0xfaff], [0xfe30, 0xfe6f], [0xff00, 0xff60], [0xffe0, 0xffe6], [0x1f300, 0x1f64f],
59  [0x1f680, 0x1f6ff], [0x1f900, 0x1f9ff], [0x20000, 0x3fffd],
60]
61
62// East Asian Ambiguous characters this file or a branch name is likely to hold: one cell in
63// most terminals, two in terminals set to a CJK ambiguous width (CTK_AMBIGUOUS_WIDTH=2).
64const AMBIGUOUS: readonly Range[] = [
65  [0x00a1, 0x00a1], [0x00a4, 0x00a4], [0x00a7, 0x00a8], [0x00aa, 0x00aa], [0x00ad, 0x00ae],
66  [0x00b0, 0x00b4], [0x00b6, 0x00ba], [0x00bc, 0x00bf], [0x00d7, 0x00d7], [0x00f7, 0x00f7],
67  [0x2010, 0x2027], [0x2030, 0x203b], [0x2190, 0x21ff], [0x2460, 0x24ff], [0x2500, 0x257f],
68  [0x2580, 0x258f], [0x2592, 0x2595], [0x25a0, 0x25ff],
69]
70
71export const charWidth = (cp: number, ambiguous: 1 | 2 = 1): number => {
72  if (cp < 0x20 || (cp >= 0x7f && cp <= 0x9f)) return 0
73  if (cp < 0x300) return ambiguous === 2 && inRanges(cp, AMBIGUOUS) ? 2 : 1
74  if (inRanges(cp, ZERO)) return 0
75  if (inRanges(cp, WIDE)) return 2
76  return ambiguous === 2 && inRanges(cp, AMBIGUOUS) ? 2 : 1
77}
78
79/** Terminal cells the text takes: ANSI sequences take none, CJK and emoji take two. */
80export const displayWidth = (s: string, ambiguous: 1 | 2 = 1): number => {
81  let w = 0
82  for (const ch of stripAnsi(s)) w += charWidth(ch.codePointAt(0) ?? 0, ambiguous)
83  return w
84}
85
86/** Cuts to at most `max` cells, ending with `…` when something was cut; never splits a wide character. */
87export const truncateToWidth = (s: string, max: number, ambiguous: 1 | 2 = 1): string => {
88  if (max < 1) return ''
89  const plain = stripAnsi(s)
90  if (displayWidth(plain, ambiguous) <= max) return plain
91  const ell = charWidth(0x2026, ambiguous)
92  let out = ''
93  let used = 0
94  for (const ch of plain) {
95    const w = charWidth(ch.codePointAt(0) ?? 0, ambiguous)
96    if (used + w + ell > max) break
97    out += ch
98    used += w
99  }
100  return ell > max ? '' : `${out}…`
101}
102
103// --- Figures -----------------------------------------------------------------------------
104
105const finite = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null)
106
107/** How loud a pressure figure (context, a rate-limit window) is: yellow from 60%, red from 80%, plain below or when unknown. */
108export const pressureTone = (pct: number | null | undefined): 'warn' | 'bad' | undefined => {
109  const n = finite(pct)
110  return n === null ? undefined : n >= 80 ? 'bad' : n >= 60 ? 'warn' : undefined
111}
112
113/** A usage percentage, rounded; null (a dash) when it was not reported. */
114export const fmtPct = (v: number | null | undefined): string => {
115  const n = finite(v)
116  return n === null || n < 0 ? DASH : `${Math.round(n)}%`
117}
118
119/**
120 * Reset time to epoch milliseconds. Claude Code's status line gives epoch seconds, the Mods
121 * API an ISO 8601 string; anything else (or a non-date) is null, never a guess.
122 */
123export const resetMs = (v: unknown): number | null => {
124  if (typeof v === 'number') {
125    if (!Number.isFinite(v) || v <= 0) return null
126    return v < 1e11 ? v * 1000 : v
127  }
128  if (typeof v === 'string' && v.trim() !== '') {
129    const t = Date.parse(v)
130    return Number.isNaN(t) ? null : t
131  }
132  return null
133}
134
135/** `34m`, `2h34m`, `3d12h`; `<1m` under a minute; null once the reset time has passed. */
136export const fmtCountdown = (resetAtMs: number | null, nowMs: number): string | null => {
137  if (resetAtMs === null || !Number.isFinite(nowMs) || resetAtMs <= nowMs) return null
138  const mins = Math.floor((resetAtMs - nowMs) / 60_000)
139  if (mins < 1) return '<1m'
140  if (mins < 60) return `${mins}m`
141  const hours = Math.floor(mins / 60)
142  if (hours < 24) return `${hours}h${String(mins % 60).padStart(2, '0')}m`
143  return `${Math.floor(hours / 24)}d${hours % 24}h`
144}
145
146export type Window = { pct: number | null | undefined; resetsAtMs: number | null }
147
148/**
149 * One rate-limit window. A window whose reset time has passed is stale (the percentage
150 * belongs to the window that ended), so it renders as a dash rather than a number that is
151 * no longer true. A percentage without a reset time still shows; the countdown is left out.
152 */
153export const windowFigures = (w: Window, nowMs: number): { pct: string; countdown: string | null; missing: boolean } => {
154  const stale = w.resetsAtMs !== null && Number.isFinite(nowMs) && w.resetsAtMs <= nowMs
155  const pct = stale ? DASH : fmtPct(w.pct)
156  return { pct, countdown: stale ? null : fmtCountdown(w.resetsAtMs, nowMs), missing: pct === DASH }
157}
158
159/** `5h 28% (2h34m)` / `5h 28% 2h34m`; a missing figure is `5h –`. */
160export const usageSegment = (id: string, label: string, prio: number, w: Window, nowMs: number): Segment => {
161  const f = windowFigures(w, nowMs)
162  if (f.missing) return { id, prio, missing: true, forms: [`${label} ${DASH}`, `${label} ${DASH}`, `${label} ${DASH}`] }
163  const base = `${label} ${f.pct}`
164  const tone = pressureTone(w.pct)
165  return {
166    id,
167    prio,
168    ...(tone === undefined ? {} : { tone }),
169    forms: f.countdown === null ? [base, base, base] : [`${base} (${f.countdown})`, `${base} ${f.countdown}`, `${base} ${f.countdown}`],
170  }
171}
172
173// --- Layout ------------------------------------------------------------------------------
174
175export type LayoutOptions = {
176  /** Cells the line may take. */
177  columns: number
178  /** The terminal width that picks the tier, when `columns` is less than the terminal (a margin). */
179  tierColumns?: number
180  /** 2 for terminals that draw East Asian Ambiguous characters (│ · …) two cells wide. */
181  ambiguous?: 1 | 2
182  /** Wrap `bold` segments in bold cyan, `tone` segments in their reminder colour, and dim the separators. The width maths ignores the sequences. */
183  color?: boolean
184}
185
186const BOLD = ['\x1b[1;36m', '\x1b[22;39m'] as const
187const TONE = { warn: ['\x1b[33m', '\x1b[39m'], bad: ['\x1b[1;31m', '\x1b[22;39m'] } as const
188// Dim separators set the status line apart from the band above, which is all one dim colour.
189const DIM_SEP = `\x1b[2m${SEP}\x1b[22m`
190
191// A figure that was not reported is dropped before one that was, whatever its rank.
192const effective = (s: Segment): number => (s.missing === true ? s.prio - 1000 : s.prio)
193
194/**
195 * Lays the segments out on one line that is never wider than `columns` cells.
196 *
197 * The tier follows the width (120+ full, 80-119 abbreviated, under 80 the essentials only).
198 * When the tier's text is still too wide, whole segments are dropped lowest rank first and the
199 * line is never cut mid-figure. Only when a single segment alone does not fit is it shortened
200 * (a more abbreviated form first, then `…`). Segments keep their given display order.
201 */
202export const layoutItems = (segments: readonly Segment[], opts: LayoutOptions): { s: Segment; text: string }[] => {
203  const columns = Number.isFinite(opts.columns) && opts.columns >= 1 ? Math.floor(opts.columns) : DEFAULT_COLUMNS
204  const amb = opts.ambiguous === 2 ? 2 : 1
205  const tier = tierOf(Number.isFinite(opts.tierColumns) && (opts.tierColumns as number) >= 1 ? (opts.tierColumns as number) : columns)
206  const sepWidth = displayWidth(SEP, amb)
207  const width = (items: readonly { text: string }[]): number =>
208    items.reduce((n, i) => n + displayWidth(i.text, amb), 0) + sepWidth * Math.max(0, items.length - 1)
209
210  let items = segments
211    .map(s => ({ s, text: s.forms[tier] }))
212    .filter(i => i.text !== '')
213  if (tier === 2 && items.length > MIN_TIER_SEGMENTS) {
214    const keep = new Set(
215      [...items]
216        .sort((a, b) => effective(b.s) - effective(a.s))
217        .slice(0, MIN_TIER_SEGMENTS)
218        .map(i => i.s.id),
219    )
220    items = items.filter(i => keep.has(i.s.id))
221  }
222  while (items.length > 1 && width(items) > columns) {
223    let drop = 0
224    let lowest = Infinity
225    items.forEach((item, i) => {
226      if (effective(item.s) <= lowest) {
227        lowest = effective(item.s)
228        drop = i
229      }
230    })
231    items = items.filter((_, i) => i !== drop)
232  }
233  const only = items.length === 1 ? items[0] : undefined
234  if (only !== undefined && width(items) > columns) {
235    let text = only.text
236    for (let t = tier + 1; t <= 2 && displayWidth(text, amb) > columns; t++) {
237      const form = only.s.forms[t]
238      if (form !== undefined && form !== '') text = form
239    }
240    items = [{ s: only.s, text: truncateToWidth(text, columns, amb) }]
241  }
242  return items
243}
244
245export const layoutLine = (segments: readonly Segment[], opts: LayoutOptions): string => {
246  const items = layoutItems(segments, opts)
247  const paint = (i: { s: Segment; text: string }): string => {
248    const wrap = opts.color === true ? (i.s.bold === true ? BOLD : i.s.tone === undefined ? undefined : TONE[i.s.tone]) : undefined
249    return wrap ? `${wrap[0]}${i.text}${wrap[1]}` : i.text
250  }
251  return items.map(paint).join(opts.color === true ? DIM_SEP : SEP)
252}
253
hooks/branch.ts 45 lines
1// The git branch for the band, read from .git/HEAD only: no `git` process, no network. Pure apart
2// from the `read` it is handed ($.fs.read in the mod); a missing file is "not a repository".
3
4type Read = (path: string) => Promise<string>
5
6const MAX_UP = 40
7const ABSOLUTE = /^(?:[\\/]|[A-Za-z]:)/
8
9const parentOf = (dir: string): string | null => {
10  const up = dir.replace(/[\\/][^\\/]*[\\/]*$/, '')
11  return up === dir || up === '' ? null : up
12}
13
14/** The branch name, a 7-character commit id when HEAD is detached, or null when it cannot be told. */
15export const parseHead = (head: string): string | null => {
16  const text = head.trim()
17  const ref = /^ref:\s*(.+)$/.exec(text)
18  if (ref) return (ref[1] as string).replace(/^refs\/heads\//, '').trim() || null
19  return /^[0-9a-f]{7,64}$/.test(text) ? text.slice(0, 7) : null
20}
21
22const tryRead = async (read: Read, path: string): Promise<string | null> => {
23  try {
24    return await read(path)
25  } catch {
26    return null
27  }
28}
29
30/** Walks up from `cwd` to the first `.git` (a directory, or the file a linked worktree has). */
31export const readBranch = async (read: Read, cwd: string): Promise<string | null> => {
32  let dir: string | null = cwd.replace(/[\\/]+$/, '')
33  for (let i = 0; dir !== null && i < MAX_UP; i++, dir = parentOf(dir)) {
34    const head = await tryRead(read, `${dir}/.git/HEAD`)
35    if (head !== null) return parseHead(head)
36    const link = await tryRead(read, `${dir}/.git`)
37    const gitdir = link === null ? null : /^gitdir:\s*(.+)$/m.exec(link)?.[1]?.trim()
38    if (gitdir) {
39      const linked = await tryRead(read, `${ABSOLUTE.test(gitdir) ? gitdir : `${dir}/${gitdir}`}/HEAD`)
40      return linked === null ? null : parseHead(linked)
41    }
42  }
43  return null
44}
45
hooks/ui/workers.tsx 172 lines
1import { DASH, displayWidth } from '../../shared/hudline.ts'
2import { modelLabel } from '../band.ts'
3import { BACK_KEY, collisionLine, fmtAge, fmtCount, fmtSpan, fmtTokens, UNAVAILABLE, workerKey } from '../mission.ts'
4import type { McState, Mission, WorkerRow } from '../mission.ts'
5import { moreText } from './ctx.tsx'
6import type { Ctx } from './ctx.tsx'
7import { glyphProps } from './motion.ts'
8import { COLOR, GLYPH, statusColor, statusOf } from './theme.ts'
9import type { Status } from './theme.ts'
10import type { Extras, Kit } from './types.ts'
11
12/** Press id of a worker's "Open transcript" button; the host answers it with `$.ui.view({ agentId })`. */
13export const TRANSCRIPT_PREFIX = 'mc:transcript:'
14export const transcriptKey = (agentId: string): string => `${TRANSCRIPT_PREFIX}${agentId}`
15
16const ACT_W = 4
17const RAMP = '▁▃▅▇'
18/** Most ordinary subagents listed; the rest are counted. Few when workers share the page. */
19const SUBAGENT_ROWS = 8
20const SUBAGENT_ROWS_BESIDE_WORKERS = 2
21const NAME_MIN = 10
22const NAME_MAX = 28
23const TASK_MIN = 12
24
25/** `m:ss`, or `h:mm:ss` past an hour. */
26export const fmtClock = (ms: number): string => {
27  const t = Math.floor(ms / 1000)
28  const two = (n: number) => String(n).padStart(2, '0')
29  return t >= 3600 ? `${Math.floor(t / 3600)}:${two(Math.floor((t % 3600) / 60))}:${two(t % 60)}` : `${Math.floor(t / 60)}:${two(t % 60)}`
30}
31
32export const renderWorkers = (kit: Kit, m: Mission, mc: McState, _extras: Extras, ctx: Ctx) => {
33  const { Text } = kit
34  const { line, field, para, pad, compact, room, ambiguous } = ctx
35
36  const BODY_ROWS = ctx.rows
37  const subTotal = m.subagents.total
38  const subMax = m.workers.length === 0 ? SUBAGENT_ROWS : SUBAGENT_ROWS_BESIDE_WORKERS
39  const collision = collisionLine(m.signals.collisions)
40  const subRows = (collision === null ? 0 : 1) + (subTotal === 0 ? 0 : 1 + Math.min(subTotal, subMax) + (subTotal > subMax ? 1 : 0))
41  // Two lines per worker at any width while they fit under the hint (so the task is always visible); past that, one line each with a TASK column.
42  const twoLine = m.workers.length * 2 <= BODY_ROWS - 1 - subRows
43
44  const gw = displayWidth(GLYPH.running, ambiguous) + 1
45  const widest = (xs: string[], min = 0) => Math.max(min, ...xs.map(x => displayWidth(x, ambiguous)))
46  const pill = (w: WorkerRow) => (w.stalled !== null ? 'STALLED' : statusOf(w.status) === 'done' ? 'DONE' : w.status.toUpperCase())
47  const modelOf = (w: WorkerRow) => modelLabel(w.model) ?? DASH
48  // Activity is observed tool calls relative to the busiest worker, never progress.
49  const busiest = Math.max(0, ...m.workers.map(w => w.toolCalls ?? 0))
50  const act = (w: WorkerRow) => (w.toolCalls === null ? DASH.repeat(ACT_W) : [...RAMP].map((g, i) => (w.toolCalls! > 0 && i < Math.ceil((ACT_W * w.toolCalls!) / busiest) ? g : '·')).join(''))
51  const cellOf: Record<string, (w: WorkerRow) => string> = {
52    status: pill,
53    activity: act,
54    tools: w => (w.toolCalls === null ? DASH : String(w.toolCalls)),
55    idle: w => (w.idleMs === null ? DASH : fmtSpan(w.idleMs)),
56    time: w => (w.elapsedMs === null ? DASH : fmtClock(w.elapsedMs)),
57    model: modelOf,
58    last: w => (w.lastActivityMs === null ? DASH : fmtAge(w.lastActivityMs)),
59    tokens: w => (w.usage === null ? DASH : fmtCount(w.usage.input + w.usage.output)),
60  }
61  const heads: Record<string, string> = { status: 'STATUS', activity: 'ACTIV', tools: 'TOOLS', idle: 'IDLE', time: 'TIME', model: 'MODEL', last: 'LAST', tokens: 'TOKENS' }
62  // Columns after the name, in the order they are given up when the room is short; widths follow the content.
63  const cols = ['status', 'activity', 'tools', 'idle', ...(compact || twoLine ? [] : ['time']), 'model', 'last', 'tokens'].map(id => ({ id, head: heads[id]!, w: widest([heads[id]!, ...m.workers.map(w => cellOf[id]!(w))]) }))
64  // A one-line row keeps the TASK column in preference to the optional columns.
65  const reserve = twoLine ? 0 : TASK_MIN
66  let left = room - gw - reserve
67  const shown = cols.filter(c => (left - c.w - 1 >= NAME_MIN ? ((left -= c.w + 1), true) : false))
68  const longest = widest(m.workers.map(w => w.name), 4)
69  const pillW = widest(m.workers.map(pill))
70  const modelW = widest(m.workers.map(modelOf))
71  const nameW = twoLine ? Math.min(NAME_MAX, longest, Math.max(NAME_MIN, room - gw - pillW - modelW - 2 - (compact ? 0 : ACT_W + 1))) : Math.min(NAME_MAX, longest, left)
72  const taskW = twoLine ? 0 : Math.min(left + reserve - nameW - 1, widest(m.workers.map(w => w.currentTask ?? DASH), 4))
73  const rest = (get: (id: string) => string) => shown.map(c => ` ${pad(get(c.id), c.w)}`).join('')
74
75  const oneLine = (w: WorkerRow) => {
76    const st = statusOf(w.status)
77    return (
78      <kit.Button key={workerKey(w.agentId)} plain label={`Worker ${w.name}`} onPress={() => {}}>
79        <Text wrap="truncate-end">
80          <Text color={statusColor(st)} {...glyphProps(ctx.motion, st === 'running', `worker:${w.agentId}`)}>{GLYPH[st]} </Text>
81          <Text bold>{pad(w.name, nameW)}</Text>
82          <Text dimColor={w.currentTask === null}>{taskW <= 0 ? '' : ` ${pad(w.currentTask ?? DASH, taskW)}`}</Text>
83          {shown.map(c => (
84            <Text key={c.id} color={c.id === 'status' || c.id === 'activity' ? statusColor(st) : undefined} dimColor={cellOf[c.id]!(w) === DASH}>{` ${pad(cellOf[c.id]!(w), c.w)}`}</Text>
85          ))}
86        </Text>
87      </kit.Button>
88    )
89  }
90  // Wide: name, status pill, model and activity on one row; the task, tool calls and times under it. Only observed values; the rest are a dash.
91  const twoLines = (w: WorkerRow) => {
92    const st = statusOf(w.status)
93    // The numbers are never cut: from the narrowest room, 'last' and 'ago' go first, then the time since spawn, then the tool count; the task is what gets the ellipsis.
94    const task = w.currentTask ?? DASH
95    // An idle worker shows how long it has been idle (from TeammateIdle), a dash when not observed; any other shows its last activity.
96    const idle = w.status === 'idle'
97    const age = idle ? (w.idleMs === null ? DASH : fmtSpan(w.idleMs)) : w.lastActivityMs === null ? DASH : fmtAge(w.lastActivityMs)
98    const word = idle ? 'idle' : 'last'
99    const tools = `${w.toolCalls ?? DASH} tools${w.usage === null ? '' : ` · ${fmtCount(w.usage.input + w.usage.output)} tok`}`
100    const clock = w.elapsedMs === null ? DASH : fmtClock(w.elapsedMs)
101    const tails = [[tools, clock, `${word} ${age}`], [tools, clock, age.replace(/ ago$/, '')], [tools, age.replace(/ ago$/, '')], [age.replace(/ ago$/, '')]].map(t => t.join(' · '))
102    const need = Math.min(displayWidth(task, ambiguous), TASK_MIN)
103    const tail = tails.find(t => room - gw - displayWidth(t, ambiguous) - 3 >= need) ?? tails[tails.length - 1]!
104    const detail = `${ctx.clip(task, Math.max(1, room - gw - displayWidth(tail, ambiguous) - 3))} · ${tail}`
105    return [
106      <kit.Button key={workerKey(w.agentId)} plain label={`Worker ${w.name}`} onPress={() => {}}>
107        <Text wrap="truncate-end">
108          <Text color={statusColor(st)} {...glyphProps(ctx.motion, st === 'running', `worker:${w.agentId}`)}>{GLYPH[st]} </Text>
109          <Text bold>{pad(w.name, nameW)}</Text>
110          <Text color={statusColor(st)} bold>{` ${pad(pill(w), pillW)}`}</Text>
111          <Text dimColor={w.model === null}>{` ${pad(modelOf(w), modelW)} `}</Text>
112          {compact ? null : <Text color={w.toolCalls === null ? COLOR.muted : statusColor(st)}> {act(w)}</Text>}
113        </Text>
114      </kit.Button>,
115      // A Button holds only Text, so the second row sits beside it, not inside.
116      line(`${workerKey(w.agentId)}-d`, `${' '.repeat(gw)}${detail}`, { dim: true }),
117    ]
118  }
119
120  const picked = mc.selected?.kind === 'worker' ? m.workers.find(w => w.agentId === mc.selected?.id) : undefined
121  if (picked !== undefined) {
122    return [
123      line('w-name', picked.name, { bold: true }),
124      field('w-id', 'Agent id', picked.agentId),
125      field('w-model', 'Model', picked.model ?? `${UNAVAILABLE} (the spawn did not report one)`),
126      field('w-status', 'Status', picked.stalled === null ? picked.status : `${picked.status}, stalled: ${picked.stalled.reason} for ${fmtSpan(picked.stalled.forMs)}`),
127      field('w-task', 'Current task', picked.currentTask ?? `${UNAVAILABLE} (no in-progress task owned by this worker was observed)`),
128      field('w-tools', 'Tool calls', picked.toolCalls === null ? UNAVAILABLE : `${picked.toolCalls} (its own loop)`),
129      field('w-recent', 'Recent', picked.recent.length === 0 ? `${UNAVAILABLE} (no tool call of its own loop was seen)` : picked.recent.join(' ‹ ')),
130      field('w-tokens', 'Tokens', picked.usage === null ? `${UNAVAILABLE} (no turn of its own was reported)` : `${fmtTokens(picked.usage)} · ${fmtCount(picked.usage.cacheRead)} cache read`),
131      field('w-last', 'Last activity', fmtAge(picked.lastActivityMs)),
132      field('w-idle', 'Idle for', picked.status === 'idle' ? fmtSpan(picked.idleMs) : 'not idle'),
133      <kit.Box key="w-actions" flexDirection="row" columnGap={2}>
134        {ctx.button(BACK_KEY, 'Back')}
135        {ctx.button(transcriptKey(picked.agentId), 'Open transcript')}
136      </kit.Box>,
137    ]
138  }
139  const subagents = () =>
140    subTotal === 0
141      ? []
142      : [
143          line('sa-head', `SUBAGENTS (${subTotal}) · outside the cap`, { bold: true }),
144          ...m.subagents.rows.slice(-subMax).map((a, i) => line(`sa-${i}`, `${pad(a.type, Math.min(compact ? 12 : 20, widest(m.subagents.rows.map(r => r.type))))} ${pad(a.status, 9)} ${a.description}`, { dim: true })),
145          ...(subTotal > subMax ? [line('sa-more', `+${subTotal - subMax} earlier`, { dim: true })] : []),
146        ]
147  if (m.workers.length === 0) return [...para('w-none', m.empty.workers ?? 'No teammate has started this session.'), ...subagents()]
148
149  // The hint (and in the compact table a header) take rows; the subagent block keeps what it needs; workers get the rest.
150  const per = twoLine ? 2 : 1
151  const avail = BODY_ROWS - (twoLine ? 1 : 2) - subRows
152  const over = m.workers.length * per > avail
153  const visible = over ? m.workers.slice(0, Math.max(1, Math.floor((avail - 1) / per))) : m.workers
154  const hidden = m.workers.slice(visible.length)
155  const hiddenBy = (st: Status) => hidden.filter(w => statusOf(w.status) === st).length
156  const summary = (['running', 'idle', 'failed'] as const)
157    .map(st => [hiddenBy(st), st] as const)
158    .filter(([n]) => n > 0)
159    .map(([n, st]) => `${n} ${st}`)
160    .join(', ')
161  const hints = ['Select a worker for details · bars: tool calls vs the busiest (activity)', 'Select a worker for details', 'Select for details']
162  const hint = hints.find(h => displayWidth(h, ambiguous) <= room) ?? hints[2]!
163  return [
164    ...(!twoLine ? [line('w-head', `${' '.repeat(gw)}${pad('NAME', nameW)}${taskW <= 0 ? '' : ` ${pad('TASK', taskW)}`}${rest(id => shown.find(c => c.id === id)?.head ?? '')}`, { dim: true })] : []),
165    ...visible.flatMap(twoLine ? twoLines : w => [oneLine(w)]),
166    ...(hidden.length > 0 ? [line('w-more', `${moreText(hidden.length, room)}${summary === '' ? '' : ` (${summary})`}`, { dim: true })] : []),
167    ...(collision === null ? [] : [line('w-coll', collision, { color: COLOR.ready })]),
168    line('w-hint', hint, { dim: true }),
169    ...subagents(),
170  ]
171}
172
hooks/outfilter.ts 105 lines
1// Pure logic for the opt-in `bashFilter` option: shrink the output of a test, build or log
2// command to its failures. No host calls here; the caller stores `original` under `hash` so the
3// full text can be recalled. It fails open: any doubt returns the original, and the result is
4// never longer than the original.
5
6/**
7 * A test, build, lint or log program at the start of one step of a command (after `VAR=x`
8 * assignments and a runner such as `npx`). Matched per step, so a file path that merely contains
9 * `test` or `build` (`cat test/a.ts`, `git diff -- src/build.ts`) is never filtered.
10 */
11const NOISY_STEP =
12  /^(?:\w+=\S*\s+)*(?:(?:npx|bunx|pnpm exec|uv run|poetry run)\s+)?(?:jest|vitest|pytest|mocha|tsc|make|cargo|gradle|\.\/gradlew|mvn|eslint|ruff|mypy|journalctl|(?:npm|pnpm|yarn|bun)\s+(?:test|t|run|build|ci|install|lint)|go\s+(?:test|build|vet)|(?:docker|kubectl)\s+(?:compose\s+)?logs|node\s+--test|python3?\s+-m\s+(?:pytest|unittest))\b/
13const FAILURE_LINE = /\b(fail(ed|ure|s)?|error|panic|exception|traceback|assert(ion)?|fatal|not ok|expected|received)\b|[✗✖×●]|\bat \S+:\d+/i
14/** A passing test line: it can say `error` or `fail` in its name without being a failure. */
15const PASS_LINE = /^\s*(?:[✓✔√]|ok\s|PASS\b)/
16/** Lines kept after a failure line: the expected/received diff and the first stack frames. */
17const CONTEXT_AFTER = 5
18
19export const isNoisyCommand = (command: string): boolean =>
20  command.split(/&&|\|\||;|\|/).some(step => NOISY_STEP.test(step.trim()))
21
22/** Output at or under this many lines is only de-duplicated, never cut. */
23export const MAX_LINES = 120
24const HEAD_LINES = 20
25const TAIL_LINES = 30
26const MAX_FAILURE_LINES = 40
27/** Skipping a short output saves nothing and risks the fail-open rule. */
28const MIN_CHARS = 2000
29/** A rewrite must save at least this much, or the note the caller adds can make it longer. */
30export const MIN_SAVING = 500
31
32export type FilterResult = {
33  /** What the model should see: the filtered text, or the original when nothing was gained. */
34  text: string
35  /** hash of the original (see hashOutput); the key under which the caller keeps the full output. */
36  hash: string
37  changed: boolean
38}
39
40// shortcut: cyrb53 (not cryptographic) because a hooks module may import nothing but its own files; fine as a recall key, upgrade if keys must resist forgery.
41export const hashOutput = (output: string): string => {
42  let h1 = 0xdeadbeef
43  let h2 = 0x41c6ce57
44  for (let i = 0; i < output.length; i++) {
45    const c = output.charCodeAt(i)
46    h1 = Math.imul(h1 ^ c, 2654435761)
47    h2 = Math.imul(h2 ^ c, 1597334677)
48  }
49  h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
50  h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
51  return `${(h2 >>> 0).toString(16).padStart(8, '0')}${(h1 >>> 0).toString(16).padStart(8, '0')}-${output.length.toString(16)}`
52}
53
54const collapseRuns = (lines: string[]): string[] => {
55  const out: string[] = []
56  for (let i = 0; i < lines.length; ) {
57    let j = i + 1
58    while (j < lines.length && lines[j] === lines[i]) j++
59    // The line itself stays verbatim: a marker on it would read as part of the program's output.
60    out.push(lines[i]!)
61    if (j - i > 1) out.push(`... previous line repeated ${j - i - 1} more times ...`)
62    i = j
63  }
64  return out
65}
66
67const cap = (lines: string[]): string[] => {
68  if (lines.length <= MAX_LINES) return lines
69  const keep = new Set<number>()
70  for (let i = 0; i < HEAD_LINES; i++) keep.add(i)
71  for (let i = lines.length - TAIL_LINES; i < lines.length; i++) keep.add(i)
72  let kept = 0
73  // From the end: the final FAIL or assertion block is the one the reader needs, so it gets the budget first.
74  for (let i = lines.length - TAIL_LINES - 1; i >= HEAD_LINES && kept < MAX_FAILURE_LINES; i--) {
75    if (PASS_LINE.test(lines[i]!) || !FAILURE_LINE.test(lines[i]!)) continue
76    for (let k = i; k <= i + CONTEXT_AFTER && k < lines.length && kept < MAX_FAILURE_LINES; k++) {
77      if (!keep.has(k)) kept++
78      keep.add(k)
79    }
80  }
81  const out: string[] = []
82  let skipped = 0
83  for (let i = 0; i < lines.length; i++) {
84    if (keep.has(i)) {
85      if (skipped > 0) out.push(`... ${skipped} lines omitted ...`)
86      skipped = 0
87      out.push(lines[i]!)
88    } else skipped++
89  }
90  return out
91}
92
93export const filterBashOutput = (command: string, output: string): FilterResult => {
94  const hash = hashOutput(typeof output === 'string' ? output : '')
95  const same: FilterResult = { text: output, hash, changed: false }
96  try {
97    if (typeof command !== 'string' || typeof output !== 'string') return same
98    if (output.length < MIN_CHARS || !isNoisyCommand(command)) return same
99    const text = cap(collapseRuns(output.split('\n'))).join('\n')
100    return text.length <= output.length - MIN_SAVING ? { text, hash, changed: true } : same
101  } catch {
102    return same
103  }
104}
105
hooks/report.ts 74 lines
1import { fmtModels, usd } from '../shared/format.ts'
2import type { StatsRecord } from '../shared/stats.ts'
3import { fmtElapsed } from './band.ts'
4import type { TaskRec } from './mission.ts'
5
6// The /ctk-report text, written to be pasted into a PR body. Pure: register.tsx hands in what was observed.
7
8export type ReportInput = {
9  stats: StatsRecord
10  tasks: Iterable<TaskRec>
11  /** Paths the write tools changed, in first-change order. */
12  files: Iterable<string>
13  /** Older paths dropped to keep the record bounded. */
14  filesDropped?: number
15  /** The session's working directory: paths inside it are shown relative, the rest only counted. */
16  cwd?: string | null
17  /** Milliseconds since the first teammate started; null when none did. */
18  teamMs: number | null
19  /** Session events that cost the team time; the report lists the non-zero ones. */
20  friction?: { compactions: number; coldCache: number; failed: number; echoes?: number; lifecycle?: number }
21}
22
23/** Most files listed; the rest is a count. */
24export const REPORT_FILES_MAX = 50
25
26const models = (m: Record<string, number>): string => fmtModels(m) || '–'
27
28// A path under cwd, relative to it; null for one outside (a memory file, a temp dir), which a PR body should not carry.
29const inside = (path: string, cwd: string | null | undefined): string | null => {
30  if (!cwd) return path
31  const root = cwd.replace(/[\\/]+$/, '') + '/'
32  const p = path.replace(/\\/g, '/')
33  return p.startsWith(root.replace(/\\/g, '/')) ? p.slice(root.length) : null
34}
35
36const frictionLine = (s: StatsRecord, f: ReportInput['friction']): string => {
37  const items = [
38    [s.spawnsRejected, 'spawn(s) refused at capacity'],
39    [s.spawnsBudgetStopped, 'spawn(s) stopped by a usage limit'],
40    [f?.compactions ?? 0, 'compaction(s)'],
41    [f?.coldCache ?? 0, 'time(s) the cache went cold'],
42    [f?.failed ?? 0, 'failed teammate(s)'],
43    [f?.echoes ?? 0, 'own task_assignment echo(es) dropped'],
44    [f?.lifecycle ?? 0, 'shutdown notice(s) dropped'],
45  ].filter(([n]) => (n as number) > 0)
46  return items.length === 0 ? 'none' : items.map(([n, t]) => `${n} ${t}`).join('; ')
47}
48
49export const formatReport = ({ stats: s, tasks, files, teamMs, filesDropped = 0, cwd, friction }: ReportInput): string => {
50  const live = [...tasks].filter(t => t.status !== 'deleted')
51  const all = [...files].map(f => inside(f, cwd))
52  const changed = all.filter((f): f is string => f !== null)
53  const outside = all.length - changed.length
54  return [
55    '## Team report',
56    '',
57    `Team duration: ${fmtElapsed(teamMs)}. Spawns: ${s.spawnsAccepted} accepted, ${s.spawnsRejected} refused at capacity, ${s.spawnsBudgetStopped} stopped by a usage limit.`,
58    `Session: cost ${usd(s.measured.costUsd)}, ${s.toolCalls} tool calls.`,
59    `Models: lead ${s.measured.model ?? '–'}; teammates ${models(s.workerModels)}; subagents ${models(s.subagentModels)}.`,
60    '',
61    '### Friction',
62    frictionLine(s, friction),
63    '',
64    '### Tasks',
65    ...(live.length === 0 ? ['No task list was recorded.'] : live.map(t => `- #${t.id} [${t.status}] ${t.subject}${t.owner === null ? '' : ` (${t.owner})`}`)),
66    '',
67    `### Files changed (${changed.length})`,
68    ...(changed.length === 0 ? ['None recorded.'] : changed.slice(0, REPORT_FILES_MAX).map(f => `- ${f}`)),
69    ...(changed.length > REPORT_FILES_MAX ? [`- and ${changed.length - REPORT_FILES_MAX} more`] : []),
70    ...(outside > 0 ? [`- ${outside} outside the working directory, not listed`] : []),
71    ...(filesDropped > 0 ? [`- ${filesDropped} earlier changes not kept`] : []),
72  ].join('\n')
73}
74