SLOPSHOPPER

session-info

Session pane: context, cost and turns, the prompt cache with the time until it expires, keep warm and a guard that holds a prompt that would write an expired…

panebandguardcommandtoastprompt
★ 4v0.37.3MITupdated 2026-10-23dougcunha/claude-mods/session-info
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · session-info
│ ┃ Session info ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ ╭──────────────────────────╮╭─────────────── │ session-info │ │ ┃ │ $0.42 cost ││ 9176h 48m elap ⏺ Read(src/auth.ts) │ session-info: TypeError: undefined is not │ │ ┃ ╰──────────────────────────╯╰─────────────── ⎿ Read 6 lines │ an object (evaluating 'path.replace') │ │ ┃ ╭─────────────────────────────────────────── ⏺ Update(src/auth.ts) ╰────────────────────────────────────────────╯ │ ┃ │ section:#session ⎿ Added 2 lines, re╭────────────────────────────────────────────╮ │ ┃ │ ▸ Context 97k / 200k ⏺ Bash(bun test) │ session-info │ │ ┃ │ ███████████████████████─────────────────── ⎿ 3 pass, 1 fail │ session-info: TypeError: undefined is not │ │ ┃ │ · Cache 1h TTL · after the next reply │ an object (evaluating 'path.replace') │ │ ┃ │ 1 turn · ~1.5k output tok/turn · last 4… ● Done. refresh now re╰────────────────────────────────────────────╯ │ ┃ ╰─────────────────────────────────────────── │ ┃ ╭──────────────────────────────────────────╮ ✻ Worked for 42s · done 4:20 PM │ ┃ │ section:#turn ✓ answer · 42s · $0.00 │ │ ┃ │ claude-opus-5-5 │ › /session-info │ ┃ │ in 2.1k · out 1.5k · cache 91k read / 4… │ ⎿ session-info: Session info pane opened. │ ┃ │ detail:turn:tools │ │ ┃ ╰──────────────────────────────────────────╯ │ ┃ ╭──────────────────────────────────────────╮ │ ┃ │ section:#todos │ │ ┃ │ No task list yet. Claude writes one for │ │ ┃ │ work with several steps. │ │ ┃ │ continue-switch │ │ ┃ ╰──────────────────────────────────────────╯ │ ┃ ╭─────────────────────────────────────────── │ ┃ │ section:#autopick off │ ┃ │ autopick-switch after autopick-less 10 min ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Session info
╭──────────────────────────╮ ╭──────────────────────────╮ │ $0.42 cost │ │ 9176h 48m elapsed │ ╰──────────────────────────╯ ╰──────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ section:#session │ │ ▸ Context 97k / 200k │ │ ███████████████████████─────────────────────── 49% │ │ · Cache 1h TTL · after the next reply │ │ 1 turn · ~1.5k output tok/turn · last 42s │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ section:#turn ✓ answer · 42s · $0.00 │ │ claude-opus-5-5 │ │ in 2.1k · out 1.5k · cache 91k read / 4.3k write · 93% … │ │ detail:turn:tools │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ section:#todos │ │ No task list yet. Claude writes one for work with │ │ several steps. │ │ continue-switch │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ section:#autopick off │ │ autopick-switch after autopick-less 10 min autopick-more │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ section:#skills │ │ No skill loaded in this conversation yet. │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ section:#ci │ │ detail:ci:error │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ section:#usage │ │ Current session │ │ ██████████████──────────────────────────────── 31% │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ section:#agents none │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ section:#background none │ │ No command started in the background in this │ │ conversation yet. │ ╰──────────────────────────────────────────────────────────╯ ╭──────────────────────────────────────────────────────────╮ │ section:#checks ✖ tests │ │ ✖ Testsdetail:check:test:result 0s ago │ │ detail:check:test:command │ │ guard-switch │ ╰──────────────────────────────────────────────────────────╯ ╭─────────────────────────────────────────────────────────── │ section:#changes+git tab:#changes │ tab:#git0 files ✚ 0 │ No files changed in this session yet. │ │ [ collapse ] [ expand ] [ clear ] │ Click or Enter: new file opens in the editor, changed or │ deleted one as a diff · folder collapses or expands ╰─────────────────────────────────────────────────────────── l: layout
README

<h1 align="center">🧭 session-info</h1>

A Claude Code mod with one pane and thirteen sections.

<img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fraw.githubusercontent.com%2Fdougcunha%2Fclaude-mods%2Fmain%2Fsession-info%2F.claude-plugin%2Fplugin.json&query=%24.version&label=version&color=blue" alt="Version"> <a href="../LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License: MIT"></a> <img src="https://img.shields.io/badge/Claude%20Code-2.1.296-d97757.svg" alt="Tested on Claude Code 2.1.296">

<a href="#-install">Install</a> · <a href="#-use">Use</a> · <a href="#-settings">Settings</a> · <a href="#-limitations">Limitations</a> · <a href="#-development">Development</a>

✨ Sections

  • 📊 Session: the context window's fill, compactions and /clear commands, the prompt cache with the time until it expires and a Keep warm button, the session's cost and duration, and turn stats. A cache guard holds a prompt that would write an expired cache again.
  • 🔁 Last turn: how the last turn ended, how long it took and what it cost, its model, effort and request count, its token and cache counts, the tools it called, and the calls the permission check refused.
  • ✅ Todos: the task list Claude keeps for work with several steps, like OpenCode's todo list. The mod gives Claude a todo_write tool for it, and a switch that keeps Claude working while tasks remain open.
  • ⏳ Autopick: a switch that answers a question Claude asked and you left unanswered with the option Claude marked as recommended, after a wait you set. A countdown shows the time left, with Pick now and Cancel. The switch starts off.
  • 🧠 Skills: the skills the conversation loaded, which agent loaded each one, and the ones still active.
  • 🚦 CI: the GitHub Actions runs that a push, a pull request, a workflow dispatch or a rerun of the session started, with their jobs, a link and a notification when each run ends.
  • 🎫 Jira: the Jira issues the chat mentions, with summary, status, priority and assignee, read through the Atlassian MCP server you connected.
  • 📈 Usage: your plan's rate-limit windows as bars, like /usage, updated live.
  • 🤖 Agents: the session's subagents and teammates with their status, model and effort, children under the agent that spawned them.
  • 🛰️ Background: the shell commands Claude started in the background, such as a dev server or a long build, with their status and how long they ran.
  • 🧪 Checks: whether the last build and the last test run the session started passed, with the error lines of a failed build or the names of the failed tests, and a prompt that asks Claude to fix a failure, and a switch that skips a build or test run when nothing changed since the same command passed. .NET, Node, Bun, Rust, Go and Python tools are recognized.
  • 🌿 Git: the branch and whether it is on the remote, the working-tree counts, the last commit, a merge or rebase in progress, the submodules that changed, and every file git status lists, in a treeview like the Changes one. Pressing a file opens its diff against HEAD; pressing the branch name opens your Git client, such as lazygit, in a new terminal window.
  • 📝 Changes: every file the current session created, modified or deleted, in a treeview. Pressing a new file opens it in your editor; pressing a modified or deleted file opens its diff in the diff viewer configured on your machine.

🔔 It also raises a native notification when a usage window reaches 80% or 90%, or the context window reaches 85%, even with the pane closed. See Alerts.

🎨 Cards, tabs and order

Each section is a card with a rounded frame that lights up under the pointer in the fullscreen terminal, and a row of tiles above them shows the cost and the elapsed time at a glance. Bars fill in whole cells, so the line after the filled run starts flush against it in every bar. In a terminal pane narrower than 44 columns the frames and tiles step aside and the sections draw bare, as in earlier versions. The desktop app always draws the frames and tiles, sizing them and the bars by percentage instead of terminal cells.

Sections can share one card as tabs, to make the pane shorter. By default Changes and Git do: the card opens on Changes, and pressing a tab shows that section in the same place. A tab that is not active shows a count, such as Changes 12, so a hidden section still says it has something. The tabGroups option sets the groups, for example changes+git, ci+jira+skills.

The sectionOrder option sets the order of the sections, top to bottom, for example changes, git, session. The sections it does not name follow in the default order: Session, Last turn, Todos, Skills, CI, Jira, Usage, Agents, Background, Checks, Git, Changes. A tab group card sits where its first shown section sits in this order, and it stays there when you press another tab. The order of the tabs in the card, and the tab it opens on, come from tabGroups. For example, with sectionOrder set to git, session and the default group changes+git, the Changes and Git card is at the top and opens on Changes. A group typed whole, such as changes+git, also counts as its sections in order.

🔍 Reading a text that a row cuts

A row that does not fit the pane ends in …. Pressing a cut text opens the whole of it in place of the sections, with a ← Back button (b) that returns to them and a Copy button (y) that puts the text on the clipboard. The text is wrapped to the pane and scrolls with it. These texts open that way:

SectionTexts
Last turnThe tools called and the refused calls
AutopickThe recommended options of a question that waits, the Picked line (why it happened, then each pick on its own line) and the warning about the ask-autopick mod
CIThe error that stopped the polling
JiraAn issue's summary and the error of a failed read
AgentsAn agent's model, effort and task description
BackgroundA command's name and its whole command, every line of it
ChecksThe command, the result line and the error lines or failed test names, shown together
GitThe commit subject and the operation in progress

The view keeps the first 4,000 characters of a text. It is not saved: /clear closes it, and so does a reload.

📸 Screenshot

The pane in a fullscreen terminal at the start of a task: an autopick countdown on a question, a task list with its first task in progress, and an active skill:

The session-info pane: tiles, Session with the stacked context bar, Usage, Autopick with a countdown, Todos, Last turn, Skills, Agents, Checks and Changes

Each section that follows has its own screenshot from the same session.

🚀 Install

At the Claude Code prompt:

/plugin install session-info --marketplace dougcunha/claude-mods

Answer y to add the marketplace and choose a scope. If you already added the marketplace:

/plugin install session-info@claude-mods

🎮 Use

ActionHow
Open the pane/session-info (or /changes). To open it when the session starts, set session-info.openOnStart to true
Fold or unfold a sectionPress its header, for example ▾ Session or ▾ Changes
Open the Git clientPress the branch name in the ▾ Git header, or press g while the pane has the focus
Show the legend of the context barPress ▸ Context
Keep the prompt cache warm, or stopPress Keep warm or Stop on the cache row of the Session section
Send a prompt the cache guard heldPress Enter again, or press Compact or New session on the band above the prompt
Open a fileClick the file in the fullscreen terminal, or move to it with Tab or the arrow keys and press Enter. A new file (A, or ?? in the Git tree) opens in the editor; a modified (M) or deleted (D) file opens as a diff. In the Git tree, the diff is against HEAD
Collapse or expand a folderPress the folder
Scroll a long treeA tree taller than the room the terminal leaves draws a window of rows with a scrollbar (┃ on the track │) at its right edge, and under it ▲ and ▼ with the rows above and below. Press ▲ or ▼, or u and d, to move a page; press the track to jump to that place. The wheel over a list moves that list, a page at most per turn of the wheel; elsewhere on a pane taller than its window it scrolls the whole pane, and so does the wheel over a list that has reached its end. A list always shows at least 6 rows. The arrow keys move the first tree on screen while the pane fits its window. In the Git tree u and d work while the Changes tree is not on screen
Collapse all, expand all, clear the listc, e, x, or the buttons at the bottom. The Git tree has collapse and expand only; c and e go to it while the Changes tree is not on screen
Turn autopick on or offPress [ ] Answer unanswered questions in the Autopick section, or run /autopick on or /autopick off
Set the autopick waitPress − or + in the Autopick section, or run /autopick <minutes>, 1 to 120
Answer a waiting question now, or stop its countdownPress Pick now or Cancel on its row in the Autopick section
Move or hide a cardPress ≡ Layout at the bottom of the pane, or press l while the pane has the focus. Each card header then shows ↑, ↓ and ✕. Press ≡ Done or l again to leave layout mode. See Arrange the cards
Show a hidden card againPress its name after Hidden: at the bottom of the pane, or press [ ] before its name in the Sections list of layout mode
Return to the promptEsc

Status colors follow your theme: green for created (A), yellow for modified (M), red and struck through for deleted (D). Chains of single-child folders collapse into one row, for example src/app/ui.

📊 What the Session section shows

The Session section with the context legend unfolded: each category's tokens and share, the free space, the compact buffer, the cache row with the time left, the TTL and Keep warm, and the turn stats

RowSource
Cost and elapsed (tiles)The session's cost as /cost totals it and the time since the session started. In a narrow pane, they move to the section header
Context barThe live context window: tokens used, the window size, where auto-compaction runs (compacts at 967k) and the percentage. The bar is stacked, one color per category (system prompt, tools, memory files, skills, messages), then the free space as a thin line and the compaction buffer shaded. Pressing ▸ Context unfolds a legend with each category's tokens and share. The categories are estimated locally after each turn and compaction; before the first reading the bar has one color
CompactionsCompactions that went through in the main conversation
Clears/clear commands run since the mod loaded, by hand or by another mod (· 3 clears); it shows after the first reply that follows a /clear
CacheThe prompt cache of the main conversation: the state in its color on the left, ● Cache warm · 42m left, ◐ Cache cools in 3m in bold in the last 5 minutes (the last minute of a 5-minute TTL), ○ Cache cold for 12m in bold, or ◆ Cache kept warm · 3h 55m left while keep warm runs; and the details on the right, dim: the TTL, next prompt re-caches 412k when cold (after a compaction, until its reply, the size /context counts), the pings of keep warm, and 2 re-caches (380k), which counts the requests that wrote most of the context to the cache again. Before the first reply it shows the TTL alone
TurnsMain-thread turns, their average output tokens, and how long the last one took

The compaction and clear counts start when the mod loads, so a newly installed mod starts them at zero. When the mod joins a conversation that already has turns, after a resume or an install, the turn count starts from the prompts in its transcript.

After a /clear or a /resume in the same process, Claude Code starts the next conversation with empty pane state and raises no start event for it. The mod waits until the session id changes, then reads the context, the repository, the Autopick switch and the Jira server again and, on a resume, the task list from the transcript. On a /clear it also empties the sections that belonged to the old conversation, if the classic.SessionStart event did not already.

⏱ How the cache time is found

Each request of the main conversation reads the cache, writes it, or both. The mod notes when the last one ended and how much context it sent. The cache expires one TTL after that request.

The TTL comes from these sources, the first one that applies:

  1. The cacheTtl setting, when you set 5m or 1h.
  2. The TTL Claude Code reports when you switch the model.
  3. The session's own requests. A request that writes most of a 30k+ context to the cache again after 5.5 to 60 idle minutes shows a 5-minute TTL. A request that reads most of it from the cache after more than 5.5 idle minutes shows a 1-hour TTL.
  4. The account: 1 hour when Claude Code reports plan rate limits, 5 minutes on an API key. The first reply of a session keeps 1 hour, because the limits can come after it.

A switch to another model starts the cache over, so the row waits for the next reply. After a reload or an install in a session with a finished turn, the mod dates the cache from the end of that turn until the next request. The first request after a compaction writes the shorter context and does not count as a re-cache.

Resumed sessions

A session resumed with claude --resume or /resume has turns behind it and no request seen yet, so the mod dates its cache this way:

  1. The classic.SessionStart event of the resume, when it reaches the mod: it says how long ago the last response came and how much context it left.
  2. The touch the mod kept in its store: every request of the main conversation, and every keep-warm ping, writes when it ended and how much context it held, for the 24 most recent sessions. A resume reads the entry of its session, so the age is known even when the event never arrives.
  3. No touch on record, as for a session last used before this version: the cache is taken as expired, since a resume starts after the process before it ended. The row reads probably cold · resumed, and the guard's band says the cache has probably expired instead of how long ago.

✋ Cache guard

When the cache expired and the context has at least cacheGuardMinTokens tokens (150k by default), the prompt you type does not go in. Claude Code puts it back in the prompt box, and a band above the prompt shows how long ago the cache expired and how many tokens the prompt would write to the cache again:

  • Enter sends the prompt here, as typed.
  • Compact runs /compact. The prompt stays in the box, and Enter sends it over the shorter context.
  • New session runs /clear and leaves the prompt in the box of the new session.

The mod never sends the prompt for you, so it goes in as your own, with its images and @ mentions. The guard checks only a prompt you type at an idle session: slash commands, prompts typed during a turn and prompts from Remote Control, a plugin or a background task go in at once. After a compaction, from the band or a /compact you type, the next prompt goes in at once: it writes only the summary to the cache. Set cacheGuard to false to turn it off.

🔥 Keep warm

Keep warm on the cache row sends one small request shortly before the cache expires, so the cache lives a full TTL again. The request forks the conversation as the main thread last sent it, with the text session-info keep-warm ping. Reply with only: ok; its reply is thrown away. Each ping costs a cache read of the whole context, about a tenth of a write. Keep warm runs for keepWarmHours (4 by default) and stops by itself when:

  • a ping writes to the cache instead of reading it, or gets no answer;
  • the cache had already expired;
  • the time runs out.

A toast says why it stopped. /clear stops it too.

🔁 What the Last turn section shows

The section shows the last turn of the main conversation. It updates when the turn ends.

The Last turn section: the turn number, result, duration and cost, then the model, effort and request count, the token and cache counts, and the tools called

RowSource
HeaderThe turn's number (#14), how the turn ended (✓ answer, ⊘ aborted, ✖ refusal, ✖ error), its duration, and its cost: the session's cost when the turn ended minus the cost when it started, so it includes the subagents that ran during the turn
ModelThe model of the last request of the turn, the effort it sent, and how many model requests the turn made
TokensInput, output, cache read and cache write tokens, summed over the turn's requests, and the share of the input that the prompt cache served (cache read / (input + cache read + cache write))
ToolsThe tools the main conversation called in the turn, most-called first, four names and then +N more. An MCP tool shows by its own name. Then the subagents the turn spawned and the tokens of the subagent runs that ended during the turn
RefusedThe calls of the main conversation that the permission check refused in the turn (⊘ 2 refused: Bash (Bash(rm:*)) · WebFetch (mode)), in order, four and then +N more. Each names what decided: the settings rule as written, the hook (PreToolUse), the setting, or mode for the permission mode. The row shows only when a call was refused

The token counts of the main turn do not include its subagents; the Tools row shows them apart. The Refused row reads the verdict that Claude Code's rules, permission mode and hooks give before a call runs. A call that you refuse in the permission dialog, or that the auto-mode classifier refuses, is not in it: the mod gets no verdict for those. A subagent that runs in the background and ends after the turn is not counted. When the mod loads while a turn runs, for example after a reload, that turn's record has no effort, request count, tools or cost. /clear empties the section.

🤖 What the Agents section shows

The Agents section with two completed Explore subagents, each with its model, effort and task

Every agent loop of the session, as Claude Code lists it: subagents the model or a plugin spawned and teammates. Each row shows a status glyph, the agent's name (or its type), its model and effort, and its task description:

GlyphStatus
⟳running
⏸waiting
◌pending
○idle (a teammate waiting for a message)
✓completed
✖failed
⊘killed

Active agents come first; an agent spawned by another is indented under it. Claude Code drops a finished agent from its list some time after it ends, and the row leaves with it. The section redraws when an agent starts or finishes a turn, and once a minute. Up to 8 rows are shown.

The model comes from the agent's spawn and then from each of its model requests; the effort comes from its requests only, so it shows after the agent's first request. The last request wins, so a fallback model shows too. An agent that started before the mod loaded shows its model and effort after its next request; one that ended before that shows neither. /clear forgets them.

🛰️ What the Background section shows

The shell commands that Claude started with run_in_background, in a Bash or PowerShell call of the main conversation or of a subagent. Each row shows a status glyph, the task's name, and its state in words with the time it has run or ran for:

GlyphStateMeaning
⟳running · 3m 2sThe command runs, and the time counts up
✓done · 12sThe task ended with the status completed
✖failed · 4sThe task ended with any other status than completed or killed
⊘stopped · 1m 1sThe task was killed, or Claude stopped it with TaskStop
•ended · 2m 5sClaude Code no longer lists the task as running, and no notification gave its status

The name is the description Claude wrote for the call, with the command on a dim line under it; with no description, the command's first line is the name (the detail view shows the whole command). Running tasks come first, then the ended ones, newest first. The header counts them by state, and a tab that is not active shows how many run. Up to 8 rows are shown, then a count of the rest, and the section keeps the last 30 commands.

A command is running until its task notification reaches the session: Claude Code sends one when a background task ends, and the mod marks the task ended then, not at the moment the command exits. The mod reads the notification from the session's message queue, so a notification that lands in a running turn, or goes to a subagent, ends the task too. The time of an ended task is the time the notification took to arrive.

A task that Claude stops with TaskStop sends no notification, so the mod marks it stopped when the call succeeds. A task that ends in another way with no notification, for example one you stop from the tasks dialog, stays running until the end of the next turn: the mod then compares the list with the background tasks that Claude Code reports as in flight, and marks each task that is not there ended. A notification that arrives later replaces ended with the real status. A foreground command is not listed, and neither is a task that Claude Code started without a shell call, such as a background subagent (the Agents section has those). The section keeps only the command, the description and the state: it never keeps a command's output. /clear empties it. Commands that the Checks section recognizes as a build or test run show in both sections.

🧪 What the Checks section shows

The Checks section with a passed build and a passed test run of 112 tests

One row for the last build and one for the last test run, from any shell command the session ran, a subagent's included (marked agent). A command counts when one of its segments runs a known tool, so cd app && npm test and rtk dotnet test … count too. The runners in front of a tool and their options are skipped: rtk, env, time, npx/bunx/uvx (so npx -y -p typescript tsc is tsc), pnpm/yarn exec and dlx, uv/poetry/pipenv/hatch run, bundle exec and variable assignments such as CI=1.

CheckCommands

| Build | dotnet build, dotnet publish, dotnet pack, dotnet msbuild, msbuild, npm/pnpm/yarn/bun run build, compile, typecheck or type-check, bun build, tsc, vue-tsc, tsgo, tsup, esbuild, webpack, rollup, vite/next/nuxt/astro/ng/parcel/turbo/nx/flutter build, claude plugin validate, cargo build, cargo check, cargo clippy, go build, go vet, Gradle and Maven builds, swift/zig/stack/cabal build, mix compile, xcodebuild, cmake --build, ninja, and

Source 36 files
hooks/register.tsx 2691 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderChildren, RenderSurface, ToolCallResult } from 'claude-code'
3
4import type { AgentModel, AutoContinue, AutopickPick, AutopickSettings, AutopickWait, BackgroundTask, CacheHold, CacheState, ChangeStatus, CheckKind, Checks, CiRun, ContinueRun, CiWatch, ContextReading, Detail, FileChange, Guard, GuardRun, GuardSkip, InlineDiff, JiraIssue, KeepWarm, Repo, RepoFile, SkillUse, Todo, TurnRecord, VersionInfo } from '../types'
5
6import { AGENT_STATUS, agentLabel, agentModelText, agentRows, agentSummary, withAgentModel } from './agents'
7import { crossings } from './alerts'
8import { CONTINUE_STORE, continueLog, continueReason, continueText, lastContinueText, NO_CONTINUE, withContinue, withPrompt } from './autocontinue'
9import { AUTOPICK_USAGE, autopickPrompt, autopickSummary, countdown, DEFAULT_SETTINGS, hasRival, minutesOf, pickDetail, pickedLog, pickedNote, picksDetail, picksOf, picksText, settingsOf, statusText, stepMinutes, STORE_MINUTES, STORE_ON } from './autopick'
10import type { Question } from './autopick'
11import type { AgentRow } from './agents'
12import { BACKGROUND_ROOM, BACKGROUND_STATUS, backgroundSummary, firstLine, hasCommandLine, inFlightIds, orderedTasks, startedTask, STOP_TOOL, stoppedTaskId, taskLabel, taskRowCount, taskState, withEnd, withInFlight, withStopped, withTask } from './background'
13import { CACHE_STATUS, cacheParts, cacheStatus, contextOf, holdAge, holdText, holdTitle, isPingDue, isSameMessage, KEEP_WARM_PROMPT, moveToNewSession, NO_CACHE, pingVerdict, readTouches, shouldHold, span, totalOf, TOUCH_STORE, ttlOf, ttlSetting, withCompact, withCounted, withPing, withRecovered, withRequest, withResume, withSeed, withSwitch, withTouch } from './cache'
14import type { TtlSetting } from './cache'
15import { BANNER_ROWS, FRAME_COLUMNS, FRAME_ROWS, isFramed, tileLayout, widgets } from './cards'
16import type { Tile } from './cards'
17import { openClient } from './client'
18import { clip, detailLines, detailOf } from './detail'
19import { cellWidths, contextText, GLYPH, LEGEND_GAP, legendLines, legendText, SWATCH, toReading } from './context'
20import { CHECK_STATUS, checkRowCount, checkRuns, checkSummary, checkViews, checkWhen, classify, fixSuggestion, NO_CHECKS, toPattern } from './checks'
21import { CI_POLL_MS, CI_ROOM, CI_STATUS, ciTrigger, isWatching, nativeDir, pollWatch, runDetail, startWatch, stateOf, waitingText, watchState } from './ci'
22import type { CheckView, Patterns } from './checks'
23import { gitStatus } from './git'
24import { GUARD_STORE, guardReply, isBypassed, NO_GUARD, passedResults, reusable, savedText, skipText, treeKey, withoutRun, withRun, withSkip } from './guard'
25import type { Host } from './host'
26import { fileIcon, folderIcon, STATUS } from './icons'
27import type { IconSet } from './icons'
28import { allowRequest, browseUrl, errorText, isAllowed, isIssueKey, isRefusal, issueDetail, issueKeys, JIRA_FIELDS, JIRA_ROOM, mention, needsRead, readIssue, readSite, serverNames, serverOf, siteSetting, statusColor, toKeyPattern } from './jira'
29import { age, branchText, codeParts, countParts, fileStatus, isConflict, ISSUE_COLOR, issueText, operationText, readRepo, repoRowCount, SUBMODULE_ROWS } from './repo'
30import { endSkills, isSameSkill, SKILL_ROOM, SKILL_STATUS, skillSummary, startSkill } from './skills'
31import { moveCard, ORDER, orderText, parseSectionOrder, parseTabGroups, showOption, TITLES } from './tabs'
32import type { SectionKey, TabGroup } from './tabs'
33import { clampOffset, MIN_LIST_ROWS, movedTo, offsetAt, POINTER_SLACK, scrollbar, targetAt, targetNear } from './scrollbar'
34import type { ScrollTarget, ScrollView } from './scrollbar'
35import { blocksText, finishedRuns, isPersonOrigin, taskEnds, withFinished } from './tasks'
36import { SHELLS, track } from './track'
37import { cost, countText, duration, NO_TURNS, tokens, turnLine } from './session'
38import { latestTodos, minSteps, parseTodos, TODO_ROOM, TODO_SPEC, TODO_STATUS, TODO_TOOL, todoPrompt, todoReply, todoSummary, todoText } from './todos'
39import { buildTree, flatten } from './tree'
40import { checkUpdate, installedVersion, newerVersion, NO_VERSION, readRecord, UPDATE_COMMAND, UPDATE_STORE, UPDATE_TICK_MS, updateToast } from './update'
41import { modelText, refusedText, RESULT, resultText, startDraft, toolsText, tokensText, toRecord, turnLines, withRefusal, withSpawn, withStep, withSubagentUsage, withTool } from './turn'
42import type { TurnDraft } from './turn'
43import type { Row } from './tree'
44import { customTitle, DEFAULT_TITLE, titleAlign, titleColor } from './title'
45import { bar, colorOf, labelOf, ordered, percentText, resetIn } from './usage'
46import type { Limit } from './usage'
47import { openChange, openRepoFile, openUrl } from './viewer'
48import type { Editor, Prefs, Viewer } from './viewer'
49
50const files = atom({ plugin: 'session-info', key: 'files' } as const, {} as Record<string, FileChange>)
51const collapsed = atom({ plugin: 'session-info', key: 'collapsed' } as const, [] as string[])
52const inline = atom({ plugin: 'session-info', key: 'inline' } as const, null as InlineDiff | null)
53const now = atom({ plugin: 'session-info', key: 'now' } as const, 0)
54const version = atom({ plugin: 'session-info', key: 'version' } as const, NO_VERSION as VersionInfo)
55const turns = atom({ plugin: 'session-info', key: 'turns' } as const, NO_TURNS)
56const compactions = atom({ plugin: 'session-info', key: 'compactions' } as const, 0)
57const breakdown = atom({ plugin: 'session-info', key: 'breakdown' } as const, false)
58const contextState = atom({ plugin: 'session-info', key: 'context' } as const, null as ContextReading | null)
59const alerted = atom({ plugin: 'session-info', key: 'alerted' } as const, [] as string[])
60const checks = atom({ plugin: 'session-info', key: 'checks' } as const, NO_CHECKS as Checks)
61const guard = atom({ plugin: 'session-info', key: 'guard' } as const, NO_GUARD as Guard)
62const guardOn = atom({ plugin: 'session-info', key: 'guardOn' } as const, false)
63const background = atom({ plugin: 'session-info', key: 'background' } as const, [] as BackgroundTask[])
64const detail = atom({ plugin: 'session-info', key: 'detail' } as const, null as Detail | null)
65const repoState = atom({ plugin: 'session-info', key: 'repo' } as const, null as Repo | 'outside' | null)
66const lastTurn = atom({ plugin: 'session-info', key: 'lastTurn' } as const, null as TurnRecord | null)
67const todos = atom({ plugin: 'session-info', key: 'todos' } as const, [] as Todo[])
68const autoContinue = atom({ plugin: 'session-info', key: 'autoContinue' } as const, NO_CONTINUE as AutoContinue)
69const autoContinueOn = atom({ plugin: 'session-info', key: 'autoContinueOn' } as const, false)
70const skills = atom({ plugin: 'session-info', key: 'skills' } as const, [] as SkillUse[])
71const ciState = atom({ plugin: 'session-info', key: 'ci' } as const, null as CiWatch | null)
72const jiraServer = atom({ plugin: 'session-info', key: 'jiraServer' } as const, null as string | null)
73const jiraIssues = atom({ plugin: 'session-info', key: 'jiraIssues' } as const, [] as JiraIssue[])
74const agentModels = atom({ plugin: 'session-info', key: 'agentModels' } as const, {} as Record<string, AgentModel>)
75const tabs = atom({ plugin: 'session-info', key: 'tabs' } as const, {} as Record<string, string>)
76const autopick = atom({ plugin: 'session-info', key: 'autopick' } as const, DEFAULT_SETTINGS as AutopickSettings)
77const autopickWaits = atom({ plugin: 'session-info', key: 'autopickWaits' } as const, [] as AutopickWait[])
78const autopickLast = atom({ plugin: 'session-info', key: 'autopickLast' } as const, null as AutopickPick | null)
79const autopickConflict = atom({ plugin: 'session-info', key: 'autopickConflict' } as const, false)
80const layout = atom({ plugin: 'session-info', key: 'layout' } as const, false)
81const changesTop = atom({ plugin: 'session-info', key: 'changesTop' } as const, 0)
82const gitTop = atom({ plugin: 'session-info', key: 'gitTop' } as const, 0)
83const cache = atom({ plugin: 'session-info', key: 'cache' } as const, NO_CACHE as CacheState)
84const keepWarm = atom({ plugin: 'session-info', key: 'keepWarm' } as const, null as KeepWarm | null)
85const cacheHold = atom({ plugin: 'session-info', key: 'cacheHold' } as const, null as CacheHold | null)
86const cacheMove = atom({ plugin: 'session-info', key: 'cacheMove' } as const, null as 'compact' | 'clear' | null)
87
88const PANE = 'session-info'
89/** Why the Autopick switch stays off while the ask-autopick mod answers the same questions. */
90const RIVAL_TEXT = 'The ask-autopick mod is loaded and answers questions too: this switch stays off until you disable it.'
91const MINUTE = 60_000
92/** Cells an Autopick row keeps free so its text, cut with `…`, never meets the edge. */
93const ROW_SPARE_COLUMNS = 1
94/** Cells a wait row spends beside its picks: the countdown, its gap, Pick now, Cancel and their gaps; and, with no countdown, the glyph and its gap. */
95const WAIT_COUNTING_COLUMNS = 26
96const WAIT_IDLE_COLUMNS = 2
97
98/** Tools whose calls can change the working tree, so the Git section reads the repository again after them. */
99const FILE_TOOLS: readonly string[] = [...SHELLS, 'Write', 'Edit', 'NotebookEdit']
100
101let reading: Promise<void> | undefined
102let isStale = false
103/** The main-thread turn that runs now; a reload during a turn starts without it. */
104let draft: TurnDraft | undefined
105/** Skill tool calls in flight: the skill.prompt each raises takes the calling loop from here. */
106const pendingSkills: { name: string; agentId?: string; isSeen: boolean }[] = []
107/** The GitHub poll that runs now; a tick while it runs is skipped. */
108let polling: Promise<void> | undefined
109/** The Jira site the reads go to, found once per load; the keys whose read runs now. */
110let jiraSite: { cloudId: string; url?: string } | undefined
111/** The name `$.mcp.call` took for the Jira server, found by the first call that went through. */
112let jiraName: string | undefined
113/** /clear commands run since this load; $.state starts over with each /clear, so the count lives here. */
114let clearCount = 0
115/** How long layout mode waits for the draw that adds the Sections checklist before it scrolls the pane to its end. */
116const LAYOUT_SCROLL_MS = 50
117
118/** How long a fix suggestion the busy prompt box refused waits for its second try. */
119const FIX_RETRY_MS = 1_500
120/** The fix the prompt box proposes after a turn left a failed check, until the next prompt; the key names the run it is for. */
121let fix: { key: string; text: string; isOpen: boolean } | undefined
122/** After a session.end the state switches at once, but the session id and its usage only some time later. */
123const SWITCH_POLL_MS = 200
124const SWITCH_LIMIT_MS = 10_000
125/** The engine swaps the transcript in only after session.compact resolves, so the context is read again until its total moves. */
126const COMPACT_POLL_MS = 250
127const COMPACT_LIMIT_MS = 5_000
128const reads = new Set<string>()
129/** How often keep warm looks whether the cache cools; a short TTL cools over its last minute. */
130const KEEP_WARM_TICK_MS = 30_000
131const HOUR = 60 * MINUTE
132/** The keep-warm ping that runs now; a tick while it runs is skipped. */
133let pinging: Promise<void> | undefined
134
135/**
136 * The countdowns of one load of the module: the Pick now and Cancel actions of each question whose countdown runs, by
137 * tool_use_id, and the one-second tick that redraws them, stopped while none runs.
138 */
139type Countdowns = { controls: Map<string, { pick: () => void; cancel: () => void }>; ticker?: { cancel: () => void } }
140
141const toggle = (list: readonly string[], key: string): string[] =>
142  list.includes(key) ? list.filter(one => one !== key) : [...list, key]
143
144const isSection = (key: string): boolean => key.startsWith('#')
145
146/** Folded folders of the Git tree carry this prefix, so they never mix with the Changes tree's. */
147const GIT_FOLD = 'git:'
148
149const isGitFold = (key: string): boolean => key.startsWith(GIT_FOLD)
150
151function summary(changes: readonly FileChange[]): string {
152  const count = (status: FileChange['status']) => changes.filter(one => one.status === status).length
153
154  return (['created', 'modified', 'deleted'] as const).map(s => `${STATUS[s].glyph} ${count(s)}`).join('  ')
155}
156
157function hostOf($: EngineInterface): Host {
158  return {
159    run: (argv, cwd) => $.process.run(argv, cwd === undefined ? undefined : { cwd }),
160    spawn: (argv, cwd) => $.process.spawn(cwd === undefined ? { argv } : { argv, cwd }),
161    readFile: path => $.fs.read(path),
162    writeFile: (path, text) => $.fs.write(path, text),
163    exists: path => $.fs.exists(path),
164    env: async () => ({
165      temp: await $.env.get('TEMP'),
166      tmpdir: await $.env.get('TMPDIR'),
167      os: await $.env.get('OS'),
168      home: (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME')),
169    }),
170    sessionId: () => $.session.id(),
171    cwd: () => $.session.cwd(),
172    toast: text => $.ui.toast(text),
173    files: () => read($, files),
174    updateFiles: async fn => void (await update($, files, all => fn(all ?? {}))),
175    showInline: async diff => void (await update($, inline, () => diff)),
176    sleep: ms => $.clock.sleep(ms),
177    clear: async () => void (await $.command.run({ command: 'clear' })),
178    readBox: async () => (await $.prompt.read()).text,
179    fill: async text => void (await $.prompt.fill({ text })),
180    fetchText: async url => {
181      const { ok, text } = await $.http.fetch(url)
182
183      return { ok, text }
184    },
185  }
186}
187
188/**
189 * Reads the version this copy runs and, when checks are on, asks GitHub whether a newer one is published (at most once a day).
190 * A new version is told once in a toast and stays in the footer as a button.
191 */
192async function refreshVersion($: EngineInterface, isChecked: boolean): Promise<void> {
193  const current = await installedVersion(hostOf($), $.plugin.root)
194  if (current === undefined) return
195  await update($, version, shown => ({ current, latest: shown?.latest ?? null }))
196  if (!isChecked) return
197
198  const stored = readRecord(await $.store.get(UPDATE_STORE))
199  const checked = await checkUpdate(hostOf($), stored, await $.clock.now())
200  const latest = newerVersion(checked, current)
201  const record = latest !== null && checked.notified !== latest ? { ...checked, notified: latest } : checked
202  if (record !== stored) await $.store.set(UPDATE_STORE, record)
203  await update($, version, () => ({ current, latest }))
204  if (latest !== null && record.notified !== stored.notified) $.ui.toast(updateToast(latest, current))
205}
206
207/** Puts the marketplace update command in an empty prompt for the person to send, so nothing is installed unasked; a draft is never replaced. */
208async function offerUpdate($: EngineInterface): Promise<void> {
209  const isDraft = (await $.prompt.read()).text.trim() !== ''
210  const filled = isDraft ? { isFilled: false } : await $.prompt.fill({ text: UPDATE_COMMAND }).catch(() => ({ isFilled: false }))
211  $.ui.toast(
212    filled.isFilled
213      ? 'session-info: send the command in the prompt to update, then reload the plugins.'
214      : `session-info: to update, send ${UPDATE_COMMAND} and then reload the plugins.`,
215  )
216}
217
218/** A folder folds or unfolds; a file opens in the editor or as a diff. */
219async function press($: EngineInterface, row: Row, prefs: Prefs): Promise<void> {
220  try {
221    if (row.isDir) await update($, collapsed, list => toggle(list ?? [], row.key))
222    else if (row.change) await openChange(hostOf($), row.change, prefs)
223  } catch (error) {
224    $.ui.toast(`session-info: ${String(error)}`)
225  }
226}
227
228/** A folder of the Git tree folds or unfolds; a file opens in the editor or as a diff against HEAD. */
229async function pressRepo($: EngineInterface, repo: Repo, row: Row<RepoFile>, prefs: Prefs): Promise<void> {
230  try {
231    if (row.isDir) await update($, collapsed, list => toggle(list ?? [], `${GIT_FOLD}${row.key}`))
232    else if (row.change) await openRepoFile(hostOf($), repo.root, row.change, repo.at, prefs)
233  } catch (error) {
234    $.ui.toast(`session-info: ${String(error)}`)
235  }
236}
237
238/** Notifies each usage or context threshold the measurement crosses, once; a toast stands in where notifications are off. */
239async function alert($: EngineInterface, limits: readonly Limit[], context: { percent?: number; tokens?: number; window: number }): Promise<void> {
240  const { alerts, standing } = crossings(limits, context, await read($, alerted), Date.now())
241  await update($, alerted, () => standing)
242  for (const { title, body } of alerts) {
243    const sent = await $.ui.notify(body, { title }).catch(() => ({ isSent: false }))
244    if (!sent.isSent) $.ui.toast(`${title}: ${body}`)
245  }
246}
247
248/** Records a shell call that ran a build or tests as the last one of its kind; any agent's call counts. */
249async function inspect($: EngineInterface, input: Record<string, unknown>, ran: Record<string, unknown>, patterns: Patterns): Promise<void> {
250  const command = typeof input.command === 'string' ? input.command : ''
251  const kinds = classify(command, patterns)
252  if (kinds.length === 0 || ran.deny !== undefined) return
253
254  const isError = ran.isError === true
255  const result = !isError && typeof ran.result === 'object' && ran.result !== null ? (ran.result as Record<string, unknown>) : {}
256  const fallback = typeof ran.result === 'string' ? ran.result : `${result.stdout ?? ''}\n${result.stderr ?? ''}`
257  const runs = await checkRuns(hostOf($), kinds, {
258    command,
259    text: typeof ran.text === 'string' ? ran.text : fallback,
260    isError,
261    taskId: typeof result.backgroundTaskId === 'string' ? result.backgroundTaskId : undefined,
262    isAgent: input.agentId !== undefined,
263    persistedPath: typeof result.persistedOutputPath === 'string' ? result.persistedOutputPath : undefined,
264  }, Date.now())
265  await update($, checks, current => runs.reduce((all, run) => ({ ...all, [run.kind]: run }), current ?? NO_CHECKS))
266}
267
268/** Reads the auto-continue switch from the store, which every window shares, into the pane's mirror. */
269async function loadContinue($: EngineInterface): Promise<boolean> {
270  const isOn = (await $.store.get(CONTINUE_STORE)) === true
271  if ((await read($, autoContinueOn)) !== isOn) await update($, autoContinueOn, () => isOn)
272
273  return isOn
274}
275
276async function switchContinue($: EngineInterface): Promise<void> {
277  const isOn = !(await loadContinue($))
278  await $.store.set(CONTINUE_STORE, isOn)
279  await update($, autoContinueOn, () => isOn)
280}
281
282/**
283 * The end of a main-loop turn: while the switch is on and the task list has open tasks, the stop is blocked with a
284 * text that sends Claude on with the next task. A block from a hook beneath stays as it is.
285 */
286async function continueOnStop($: EngineInterface, stop: { last_assistant_message?: string; background_tasks?: unknown[]; session_crons?: unknown[] }, stopped: { block?: string; preventContinuation?: true }): Promise<string | undefined> {
287  if (stopped.block !== undefined || stopped.preventContinuation === true) return undefined
288  const list = await read($, todos)
289  const state = await read($, autoContinue)
290  const reason = continueReason({
291    isOn: await loadContinue($),
292    todos: list,
293    lastMessage: stop.last_assistant_message ?? '',
294    // Background work or a scheduled wake-up starts the next turn by itself; a continue now would only wait for it.
295    hasPendingWork: (stop.background_tasks?.length ?? 0) > 0 || (stop.session_crons?.length ?? 0) > 0,
296    state,
297  })
298  if (reason === undefined) return undefined
299  const next = await update($, autoContinue, current => withContinue(current ?? NO_CONTINUE, list, Date.now(), reason))
300  // A line in the transcript marks where the mod sent Claude on, even with the pane closed; the model does not read it.
301  if (next.lastRun !== undefined) $.ui.log(continueLog(next.lastRun))
302
303  return reason
304}
305
306/** Reads the build guard switch from the store, which every window shares, into the pane's mirror. */
307async function loadGuard($: EngineInterface): Promise<boolean> {
308  const isOn = (await $.store.get(GUARD_STORE)) === true
309  if ((await read($, guardOn)) !== isOn) await update($, guardOn, () => isOn)
310
311  return isOn
312}
313
314async function switchGuard($: EngineInterface): Promise<void> {
315  const isOn = !(await loadGuard($))
316  await $.store.set(GUARD_STORE, isOn)
317  await update($, guardOn, () => isOn)
318}
319
320/**
321 * A shell call that runs a build or tests, while the guard is on. When the same command passed on the same working
322 * tree less than the TTL ago, the call is answered with that run's result and does not run; otherwise it runs, and a
323 * pass is kept under the tree's fingerprint. The fingerprint is taken before the run: what the run itself writes
324 * (a lock file, generated code) changes the next fingerprint, so the next run is never skipped by mistake.
325 */
326async function guardRun($: EngineInterface, command: string, kinds: CheckKind[], next: () => Promise<ToolCallResult>, onSkip: () => void): Promise<ToolCallResult> {
327  const at = Date.now()
328  let key: string | undefined
329  let reused: GuardRun | undefined
330  try {
331    key = await treeKey(hostOf($), await $.session.cwd(), command)
332    reused = key === undefined || isBypassed(command) ? undefined : reusable(await read($, guard), key, at)
333  } catch {
334    key = undefined
335  }
336  if (key === undefined) return next()
337  if (reused !== undefined) {
338    onSkip()
339    const reply = guardReply(reused, at)
340    const skip: GuardSkip = { kinds: reused.kinds, command: reused.command, reply, at, from: reused.at, ms: reused.ms }
341    const run = reused
342    await update($, guard, current => withSkip(current ?? NO_GUARD, run, skip)).catch(() => undefined)
343
344    // Bash and PowerShell share these fields of their output schema, which core checks an answer against.
345    return { result: { stdout: reply, stderr: '', interrupted: false } } as never
346  }
347
348  const ran = await next()
349  // From here on nothing may throw: the hook's catch would run the command a second time.
350  try {
351    // The general tool.call hook beneath this one has already read the run into Checks; a background run is still running there.
352    const results = ran.deny === undefined && !ran.isError ? passedResults(await read($, checks), kinds, at) : undefined
353    const chars = typeof ran.text === 'string' ? ran.text.length : 0
354    const ended = Date.now()
355    const shown = (command.split('\n')[0] ?? '').trim()
356    await update($, guard, current =>
357      results === undefined
358        ? withoutRun(current ?? NO_GUARD, key)
359        : withRun(current ?? NO_GUARD, key, { kinds, command: shown, results, at: ended, ms: ended - at, chars }))
360  } catch (error) {
361    $.ui.toast(`session-info: ${String(error)}`)
362  }
363
364  return ran
365}
366
367/** A Bash or PowerShell call: a build or test run goes through the guard while it is on; any other command runs as usual. */
368async function guardShell($: EngineInterface, e: { tool: string; agentId?: string }, next: () => Promise<ToolCallResult>, patterns: Patterns, isTurnShown: boolean): Promise<ToolCallResult> {
369  const input = e as Record<string, unknown>
370  const command = typeof input.command === 'string' ? input.command : ''
371  const kinds = classify(command, patterns)
372  // A background run ends after the call returns, so there is no result yet to keep or to reuse.
373  if (kinds.length === 0 || input.run_in_background === true || !(await loadGuard($).catch(() => false))) return next()
374  // The general hook counts the call for the Last turn section; a skipped call never reaches it.
375  const noteSkip = () => {
376    if (isTurnShown && e.agentId === undefined && draft !== undefined) draft = withTool(draft, e.tool)
377  }
378
379  return guardRun($, command, kinds, next, noteSkip)
380}
381
382/** Proposes a fix of the failed check in the empty prompt box, once per failed run; a box still busy gets one more try. */
383async function suggestFix($: EngineInterface): Promise<void> {
384  const suggestion = fixSuggestion(await read($, checks))
385  if (suggestion === undefined || suggestion.key === fix?.key) return
386  const open = { ...suggestion, isOpen: true }
387  fix = open
388  const shown = await $.prompt.suggest({ text: open.text }).catch(() => ({ isShown: false }))
389  if (!shown.isShown)
390    $.clock.after(FIX_RETRY_MS, () => {
391      if (fix === open && open.isOpen) void $.prompt.suggest({ text: open.text }).catch(() => undefined)
392    })
393}
394
395/** A conversation the mod joins with turns behind it, by a resume or an install, counts them from the prompts in its transcript. */
396/** A load with a last turn on record and no request seen yet dates the cache from that turn's end. */
397async function seedCache($: EngineInterface): Promise<void> {
398  const last = await read($, lastTurn)
399  if (last === null || (await read($, cache)).touchedAt !== undefined) return
400  const context = (await $.session.usage()).context.tokens ?? 0
401  await update($, cache, state => withSeed(state ?? NO_CACHE, last.at, context))
402}
403
404/**
405 * A resume dates its cache from the touch the store kept for the session, since the engine's own SessionStart reaches
406 * a plugin only where nothing above it ends the event, and not under an organization's security plugin. A session with
407 * turns behind it, no finished turn to date it from and no request seen here is a resume.
408 */
409async function recoverCache($: EngineInterface): Promise<void> {
410  if ((await $.session.turns()) === 0) return
411  if ((await read($, lastTurn)) !== null || (await read($, cache)).touchedAt !== undefined) return
412  const touches = readTouches(await $.store.get(TOUCH_STORE))
413  const found = touches[await $.session.id()]
414  const now = await $.clock.now()
415  const context = (await $.session.usage()).context.tokens ?? 0
416  await update($, cache, state => withRecovered(state ?? NO_CACHE, found, now, context))
417  $.ui.invalidate('ui.render')
418}
419
420/** Keeps when this session touched the cache, so a resume in another process can date it. */
421async function rememberTouch($: EngineInterface, at: number, context: number): Promise<void> {
422  const touches = readTouches(await $.store.get(TOUCH_STORE))
423  await $.store.set(TOUCH_STORE, withTouch(touches, await $.session.id(), { at, tokens: context }))
424}
425
426async function seedTurns($: EngineInterface): Promise<void> {
427  const sent = await $.session.turns()
428  await update($, turns, stats => ((stats ?? NO_TURNS).count > 0 ? (stats ?? NO_TURNS) : { ...(stats ?? NO_TURNS), count: sent }))
429}
430
431/** Which sections a task notification can change: the Background list marks the task ended, Checks reads the run it ran. */
432type TaskSections = { isBackground: boolean; isChecks: boolean }
433
434/** Marks each background task the notification says ended, and reads the checks of its command. */
435async function finishTasks($: EngineInterface, text: string, { isBackground, isChecks }: TaskSections): Promise<void> {
436  for (const end of taskEnds(text)) {
437    if (isBackground) await update($, background, tasks => withEnd(tasks ?? [], end, Date.now()))
438    if (!isChecks) continue
439    const runs = await finishedRuns(hostOf($), await read($, checks), end, Date.now())
440    if (runs.length > 0) await update($, checks, current => withFinished(current ?? NO_CHECKS, end, runs))
441  }
442}
443
444/** Reads the repository into the Git section; a call made while a read runs makes that read go once more. */
445function refreshRepo($: EngineInterface): Promise<void> {
446  if (reading !== undefined) {
447    isStale = true
448
449    return reading
450  }
451  reading = (async () => {
452    do {
453      isStale = false
454      // A read that fails keeps the last state on screen; only git's own answer says the folder is outside a repository.
455      const repo = await readRepo(hostOf($), Date.now()).catch(() => undefined)
456      if (repo !== undefined) await update($, repoState, () => repo ?? 'outside')
457    } while (isStale)
458  })().finally(() => {
459    reading = undefined
460  })
461
462  return reading
463}
464
465/** Keeps what a subagent runs on; a step that repeats the model and effort writes nothing, so the pane does not redraw. */
466async function noteAgentModel($: EngineInterface, agentId: string, model: string, effort?: string | number): Promise<void> {
467  const known = await read($, agentModels)
468  const next = withAgentModel(known, agentId, model, effort)
469  if (next !== known) await update($, agentModels, () => next)
470}
471
472/** Reads /context's breakdown, estimated locally (no token-count calls), for the stacked bar. */
473async function refreshContext($: EngineInterface): Promise<void> {
474  const usage = await $.session.usage({ breakdown: 'summary' })
475  const reading = usage.context.breakdown ? toReading(usage.context.breakdown) : null
476  if (reading === null) return
477  await update($, contextState, () => reading)
478  // After a /clear or a resume the pane's reads no longer redraw it on a write: it is drawn again here.
479  $.ui.invalidate('ui.render')
480}
481
482/** Reads the context again after a compaction until its total differs from `before`, or the limit passes. */
483function refreshAfterCompact($: EngineInterface, before: number | undefined): void {
484  let waited = 0
485  const poll = async (): Promise<void> => {
486    await refreshContext($)
487    const total = (await read($, contextState))?.total
488    waited += COMPACT_POLL_MS
489    if (total !== before || waited >= COMPACT_LIMIT_MS) return
490    $.clock.after(COMPACT_POLL_MS, () => void poll().catch(() => undefined))
491  }
492  $.clock.after(COMPACT_POLL_MS, () => void poll().catch(() => undefined))
493}
494
495/**
496 * Runs `reload` once the session id is the next conversation's. A /clear or a resume raises session.end and no start
497 * event; the state switches at once, but the session id and its usage only some time later, and a read made before
498 * would put the ended conversation's figures in the next one's state.
499 */
500function afterSwitch($: EngineInterface, endedId: string, reload: () => Promise<void>): void {
501  let waited = 0
502  const poll = async (): Promise<void> => {
503    if ((await $.session.id().catch(() => endedId)) !== endedId) return reload()
504    waited += SWITCH_POLL_MS
505    if (waited < SWITCH_LIMIT_MS) $.clock.after(SWITCH_POLL_MS, () => void poll())
506  }
507  $.clock.after(SWITCH_POLL_MS, () => void poll())
508}
509
510/** The sections a /clear empties; the same keys as the `show*` options that turn them on. */
511type ClearedSections = { todos: boolean; turn: boolean; skills: boolean; jira: boolean; agents: boolean; background: boolean; autopick: boolean }
512
513/** Empties what belonged to the conversation a /clear ended; it is safe to run twice. */
514async function clearConversation($: EngineInterface, shows: ClearedSections): Promise<void> {
515  if (shows.todos) await update($, todos, () => [])
516  if (shows.todos) await update($, autoContinue, () => NO_CONTINUE)
517  if (shows.turn) await update($, lastTurn, () => null)
518  if (shows.skills) await update($, skills, () => [])
519  if (shows.jira) await update($, jiraIssues, () => [])
520  if (shows.agents) await update($, agentModels, () => ({}))
521  if (shows.background) await update($, background, () => [])
522  await update($, detail, () => null)
523  if (shows.autopick) await update($, autopickLast, () => null)
524}
525
526/** Reads the context when the session has no reading yet: after a /clear or a resume, before any turn ends. */
527async function readMissingContext($: EngineInterface): Promise<void> {
528  if ((await read($, contextState)) === null) await refreshContext($).catch(() => undefined)
529}
530
531/** A resumed session starts with no list in its state: the last todo_write call of the transcript gives it back. */
532async function restoreTodos($: EngineInterface): Promise<void> {
533  if ((await read($, todos)).length > 0) return
534  const messages = await $.session.messages()
535  const found = Array.isArray(messages) ? latestTodos(messages) : undefined
536  if (found !== undefined) await update($, todos, () => found)
537}
538
539/** Asks GitHub about the watched runs once, and notifies each run that completed. */
540function pollCi($: EngineInterface): Promise<void> {
541  polling ??= (async () => {
542    const watch = await read($, ciState)
543    if (!isWatching(watch, Date.now())) return
544    const cwd = watch.dir
545    const { watch: polled, finished } = await pollWatch(argv => $.process.run(argv, cwd === undefined ? undefined : { cwd }), watch, Date.now())
546    // A push made while the poll ran started a new watch: the old poll's answer is dropped.
547    await update($, ciState, current => (current?.since === watch.since ? polled : current))
548    for (const run of finished) {
549      const body = `${run.workflow} · ${run.conclusion} · ${runDetail(run, Date.now())}`
550      const sent = await $.ui.notify(body, { title: 'GitHub Actions' }).catch(() => ({ isSent: false }))
551      if (!sent.isSent) $.ui.toast(`GitHub Actions: ${body}`)
552    }
553  })().finally(() => {
554    polling = undefined
555  })
556
557  return polling
558}
559
560/** Starts following the runs a push, a pull request, a dispatch or a rerun started. */
561async function watchCi($: EngineInterface, command: string, output: string): Promise<void> {
562  const found = ciTrigger(command, output)
563  if (found === undefined) return
564  // A command run in another folder (`cd <dir> &&`, `git -C <dir>`) pushed that folder's repository.
565  const trigger = found.dir === undefined ? found : { ...found, dir: nativeDir(await $.session.cwd(), found.dir) }
566  const cwd = trigger.dir
567  const git = async (args: string[]) => {
568    const done = await $.process.run(['git', ...args], cwd === undefined ? undefined : { cwd }).catch(() => undefined)
569
570    return done?.exitCode === 0 ? done.stdout.trim() : undefined
571  }
572  const isCommit = trigger.kind === 'push' || trigger.kind === 'pr'
573  const sha = isCommit ? await git(['rev-parse', 'HEAD']) : undefined
574  const branch = await git(['rev-parse', '--abbrev-ref', 'HEAD'])
575  // A folder that is no repository the mod can read gives no commit to follow: no watch beats a wrong one.
576  if (cwd !== undefined && branch === undefined) return
577  await update($, ciState, () =>
578    startWatch(trigger, { ...(sha === undefined ? {} : { sha }), ...(branch === undefined ? {} : { branch }) }, Date.now()),
579  )
580  await pollCi($)
581}
582
583/** The connected MCP server that serves getJiraIssue; servers connect after the session starts, so a miss asks again later. */
584async function findJiraServer($: EngineInterface): Promise<string | null> {
585  const known = await read($, jiraServer)
586  if (known !== null) return known
587  const server = (await $.tool.list()).map(tool => serverOf(tool.name)).find(name => name !== undefined) ?? null
588  if (server !== null) await update($, jiraServer, () => server)
589
590  return server
591}
592
593/** Calls a tool of the Jira server by each name it may go by until one goes through; all failing, the first error stands. */
594async function callJira($: EngineInterface, server: string, tool: string, args: Record<string, unknown>) {
595  let first: unknown
596  for (const name of jiraName === undefined ? serverNames(server) : [jiraName]) {
597    try {
598      const result = await $.mcp.call(name, tool, args)
599      jiraName = name
600
601      return result
602    } catch (error) {
603      first ??= error
604    }
605  }
606  throw first
607}
608
609/** The site from the jiraSite setting, else the first Jira site the server's account reaches. */
610async function findJiraSite($: EngineInterface, server: string, setting: unknown): Promise<{ cloudId: string; url?: string } | undefined> {
611  jiraSite ??= siteSetting(setting) ?? readSite(await callJira($, server, 'getAccessibleAtlassianResources', {}))
612
613  return jiraSite
614}
615
616async function readJira($: EngineInterface, key: string, setting: unknown): Promise<void> {
617  if (reads.has(key)) return
618  reads.add(key)
619  const started = Date.now()
620  const store = (fn: (issue: JiraIssue) => JiraIssue) =>
621    update($, jiraIssues, list => (list ?? []).map(issue => (issue.key === key ? fn(issue) : issue)))
622  try {
623    const server = await findJiraServer($)
624    if (server === null) return void (await store(issue => ({ ...issue, readAt: Date.now(), error: 'No Atlassian MCP server is connected.' })))
625    const site = await findJiraSite($, server, setting)
626    if (site === undefined) return void (await store(issue => ({ ...issue, readAt: Date.now(), error: 'No Jira site found: set jiraSite.' })))
627    const result = await callJira($, server, 'getJiraIssue', { cloudId: site.cloudId, issueIdOrKey: key, fields: JIRA_FIELDS })
628    const url = browseUrl(site.url, key)
629    await store(issue => ({ ...readIssue(issue, result, Date.now()), ...(url === undefined ? {} : { url }) }))
630  } catch (error) {
631    const message = error instanceof Error ? error.message : String(error)
632    // The row has room for one line; the transcript keeps the whole message.
633    $.ui.log(`session-info: Jira ${key}: ${message}`)
634    const server = await read($, jiraServer)
635    const blocked = server !== null && isRefusal(message) ? { blockedTool: `mcp__${server}__getJiraIssue` } : {}
636    // Claude's own read may land while this one fails: a good reading newer than this read stays.
637    await store(issue =>
638      issue.error === undefined && issue.readAt !== undefined && issue.readAt >= started
639        ? issue
640        : { ...issue, readAt: Date.now(), error: errorText(error), ...blocked },
641    )
642  } finally {
643    reads.delete(key)
644  }
645}
646
647/** Puts the request for the allow rule in the prompt, after any draft: the person sends it, and Claude edits the settings. */
648async function askAllow($: EngineInterface, tool: string): Promise<void> {
649  const filled = await $.prompt.fill({ text: allowRequest(tool), mode: 'append' }).catch(() => ({ isFilled: false }))
650  $.ui.toast(filled.isFilled ? 'session-info: send the request in the prompt to add the rule.' : 'session-info: the prompt could not take the request.')
651}
652
653async function copyRule($: EngineInterface, tool: string, surface: RenderSurface): Promise<void> {
654  const copied = await $.ui.copy({ text: tool, surface }).catch(() => ({ isCopied: false as const, reason: 'refused' as const }))
655  $.ui.toast(copied.isCopied ? `session-info: copied ${tool}` : `session-info: could not copy the rule (${copied.reason}).`)
656}
657
658/** The issue as the model's own getJiraIssue call answered it: no call of the mod's, so no permission to ask. */
659async function takeIssue($: EngineInterface, key: string, text: string, cloudId: unknown, setting: unknown): Promise<void> {
660  const at = Date.now()
661  const site = siteSetting(setting)?.url ?? jiraSite?.url ?? (typeof cloudId === 'string' ? siteSetting(cloudId)?.url : undefined)
662  const url = browseUrl(site, key)
663  await update($, jiraIssues, list => {
664    const [top, ...rest] = mention(list ?? [], key, at)
665    const issue = readIssue(top ?? { key, at }, { content: [{ type: 'text', text }] }, at)
666
667    return [{ ...issue, ...(url === undefined ? {} : { url }) }, ...rest]
668  })
669}
670
671/** Puts the mentioned keys on top of the Jira section and reads the ones not read in the last minutes. */
672async function noteIssues($: EngineInterface, keys: readonly string[], setting: unknown): Promise<void> {
673  if (keys.length === 0) return
674  const at = Date.now()
675  const before = await read($, jiraIssues)
676  await update($, jiraIssues, list => [...keys].reverse().reduce((all, key) => mention(all, key, at), list ?? []))
677  for (const key of keys) if (needsRead(before.find(issue => issue.key === key), at)) await readJira($, key, setting)
678}
679
680/** The reads run on after the hook that saw the keys returns, so a slow server never holds the prompt. */
681function noteText($: EngineInterface, text: string, pattern: RegExp | undefined, setting: unknown): void {
682  void noteIssues($, issueKeys(text, pattern), setting).catch(() => undefined)
683}
684
685/** Reads the autopick settings from the store, which every window shares, into the pane's mirror. */
686async function loadAutopick($: EngineInterface): Promise<AutopickSettings> {
687  const settings = settingsOf(await $.store.get(STORE_ON), await $.store.get(STORE_MINUTES))
688  const shown = await read($, autopick)
689  if (shown.isOn !== settings.isOn || shown.minutes !== settings.minutes) await update($, autopick, () => settings)
690
691  return settings
692}
693
694/** Whether ask-autopick is loaded; it answers the same questions, so autopick here stands aside while it is. */
695async function checkRival($: EngineInterface): Promise<boolean> {
696  const isLoaded = hasRival(await $.command.list())
697  if ((await read($, autopickConflict)) !== isLoaded) await update($, autopickConflict, () => isLoaded)
698
699  return isLoaded
700}
701
702/** Turning autopick off stops every countdown that runs: those questions wait for the person. */
703async function saveAutopick($: EngineInterface, live: Countdowns, change: Partial<AutopickSettings>): Promise<AutopickSettings> {
704  const settings = { ...(await loadAutopick($)), ...change }
705  await $.store.set(STORE_ON, settings.isOn)
706  await $.store.set(STORE_MINUTES, settings.minutes)
707  await update($, autopick, () => settings)
708  if (!settings.isOn) for (const control of [...live.controls.values()]) control.cancel()
709
710  return settings
711}
712
713async function switchAutopick($: EngineInterface, live: Countdowns): Promise<void> {
714  const isOn = !(await loadAutopick($)).isOn
715  if (isOn && (await checkRival($))) return void $.ui.toast('session-info: ask-autopick is loaded and answers questions too; disable it first.')
716  await saveAutopick($, live, { isOn })
717}
718
719/** `/autopick`, `/autopick on | off` and `/autopick <minutes>`. */
720async function runAutopick($: EngineInterface, live: Countdowns, args: string): Promise<{ text: string }> {
721  const arg = args.trim().toLowerCase()
722  const isBlocked = await checkRival($)
723  let settings = await loadAutopick($)
724  if (arg === 'on' || arg === 'off') {
725    if (arg === 'off' || !isBlocked) settings = await saveAutopick($, live, { isOn: arg === 'on' })
726  } else if (arg !== '') {
727    const minutes = minutesOf(arg)
728    if (minutes === undefined) return { text: AUTOPICK_USAGE }
729    settings = await saveAutopick($, live, { minutes })
730  }
731
732  return { text: statusText(settings, isBlocked) }
733}
734
735/** Redraws the pane each second while a countdown runs. */
736function syncTicker($: EngineInterface, live: Countdowns): void {
737  if (live.controls.size === 0) {
738    live.ticker?.cancel()
739    live.ticker = undefined
740  } else live.ticker ??= $.clock.every(1_000, () => $.ui.invalidate('ui.render'))
741}
742
743const dropWait = ($: EngineInterface, id: string) => update($, autopickWaits, list => (list ?? []).filter(wait => wait.id !== id))
744
745/**
746 * An AskUserQuestion call while autopick is on: the dialog opens as usual, and when the wait runs out (or the person
747 * presses Pick now) the hook answers the call with the recommended options in the person's place. The engine then
748 * closes the dialog and settles the abandoned `next(e)` as rejected, which the hook absorbs.
749 */
750async function answerOrPick($: EngineInterface, live: Countdowns, input: { tool_use_id?: string }, questions: readonly Question[], pending: Promise<ToolCallResult>): Promise<ToolCallResult> {
751  const settings = await read($, autopick)
752  const picks = picksOf(questions)
753  const at = await $.clock.now()
754  const id = input.tool_use_id ?? `ask-${at}`
755  const ms = settings.minutes * MINUTE
756  await update($, autopickWaits, list => [...(list ?? []), { id, picks: picks ?? null, at, ...(picks ? { deadline: at + ms } : {}) }])
757  if (picks === undefined) {
758    try {
759      return await pending
760    } finally {
761      await dropWait($, id)
762    }
763  }
764  let fire: (isByHand: boolean) => void = () => undefined
765  const fired = new Promise<boolean>(resolve => {
766    fire = resolve
767  })
768  const timer = $.clock.after(ms, () => fire(false))
769  live.controls.set(id, {
770    pick: () => {
771      timer.cancel()
772      fire(true)
773    },
774    cancel: () => {
775      timer.cancel()
776      live.controls.delete(id)
777      syncTicker($, live)
778      // The wait keeps its row without a deadline: the question is the person's again.
779      void update($, autopickWaits, list => (list ?? []).map(wait => (wait.id === id ? { id, picks: wait.picks, at: wait.at } : wait)))
780    },
781  })
782  syncTicker($, live)
783  try {
784    const first = await Promise.race([pending, fired])
785    if (typeof first !== 'boolean') return first
786    // Turned off in another window during the wait: the question stays for the person.
787    if (!first && !(await loadAutopick($)).isOn) {
788      live.controls.get(id)?.cancel()
789
790      return await pending
791    }
792    pending.catch(() => undefined)
793    const pick: AutopickPick = { picks, at: await $.clock.now(), minutes: settings.minutes, isByHand: first }
794    await update($, autopickLast, () => pick)
795    $.ui.log(pickedLog(pick))
796
797    return { result: { questions, answers: picks, annotations: {} }, context: [pickedNote(pick)] } as never
798  } finally {
799    timer.cancel()
800    live.controls.delete(id)
801    syncTicker($, live)
802    await dropWait($, id)
803  }
804}
805
806/** The cache guard's and keep warm's settings, read once per load. */
807type CacheOptions = { ttl: TtlSetting; isGuarded: boolean; minTokens: number; keepWarmHours: number }
808
809/** A main-thread request reached the cache: the cache's state takes its usage, and the plan limits decide the default TTL. */
810async function noteRequest($: EngineInterface, usage: { input_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }, startedAt: number): Promise<void> {
811  const limits = await $.session.usage().then(read => read.rateLimits, () => [])
812  const endedAt = await $.clock.now()
813  await update($, cache, state => withRequest(state ?? NO_CACHE, { usage, startedAt, endedAt, hasPlanLimits: limits.length > 0 }))
814  await rememberTouch($, endedAt, totalOf(usage)).catch(() => undefined)
815}
816
817/** Starts keep warm for the configured hours, or stops it. */
818async function switchKeepWarm($: EngineInterface, hours: number): Promise<void> {
819  const at = await $.clock.now()
820  const isOn = (await read($, keepWarm)) === null
821  await update($, keepWarm, () => (isOn ? { until: at + hours * HOUR, pings: 0 } : null))
822  $.ui.toast(isOn ? `session-info: keep warm runs for ${span(hours * HOUR)}. A ping reads the cache shortly before it expires.` : 'session-info: keep warm is off.')
823  $.ui.invalidate('ui.render')
824}
825
826const stopKeepWarm = async ($: EngineInterface, why: string): Promise<void> => {
827  await update($, keepWarm, () => null)
828  $.ui.toast(`session-info: keep warm stopped: ${why}.`)
829  $.ui.invalidate('ui.render')
830}
831
832/**
833 * While keep warm runs and the cache cools, one fork of the conversation reads the cache, so its entry lives a full
834 * TTL again. A ping that misses the cache, or gets no answer, stops keep warm: pinging on would pay for writes.
835 */
836function keepWarmTick($: EngineInterface, setting: TtlSetting): Promise<void> {
837  pinging ??= (async () => {
838    const keep = await read($, keepWarm)
839    if (keep === null) return
840    const at = await $.clock.now()
841    if (keep.until <= at) return stopKeepWarm($, 'its time ran out')
842    const state = await read($, cache)
843    const ttl = ttlOf(state, setting)
844    // A ping now would write the whole context, the cost keep warm is there to avoid.
845    if (cacheStatus(state, keep, ttl, at).kind === 'cold') return stopKeepWarm($, 'the cache had already expired')
846    if (!isPingDue(state, keep, ttl, at)) return
847    const reply = await $.model.fork({ prompt: KEEP_WARM_PROMPT }).catch(() => undefined)
848    const verdict = pingVerdict(reply !== undefined && 'usage' in reply ? reply.usage : undefined)
849    if (verdict === 'none') return stopKeepWarm($, 'the ping got no answer')
850    if (verdict === 'miss') return stopKeepWarm($, 'the ping wrote the cache instead of reading it')
851    const pinged = await $.clock.now()
852    await update($, cache, current => withPing(current ?? NO_CACHE, pinged))
853    await rememberTouch($, pinged, state.tokens).catch(() => undefined)
854    await update($, keepWarm, current => (current === null ? null : { ...current, pings: current.pings + 1 }))
855    $.ui.invalidate('ui.render')
856  })().finally(() => {
857    pinging = undefined
858  })
859
860  return pinging
861}
862
863/** Claims the band for one move and returns true, or returns false when a move already runs. */
864async function claimMove($: EngineInterface, move: 'compact' | 'clear'): Promise<boolean> {
865  let isClaimed = false
866  await update($, cacheMove, current => {
867    isClaimed = current === null
868
869    return current ?? move
870  })
871  $.ui.invalidate('ui.render')
872
873  return isClaimed
874}
875
876/** What a compaction updates: the cache when the guard or the row follows it, the context bar when the Session section shows. */
877type CompactionNotes = { isCacheTracked: boolean; isSessionShown: boolean }
878
879/** The context total and the compaction count before a /compact runs, to tell afterwards whether session.compact noted it. */
880type CompactMark = { before: number | undefined; count: number }
881
882/** Counts a compaction of the main conversation, marks the cache compacted and reads the context again until it moves. */
883async function noteCompaction($: EngineInterface, before: number | undefined, notes: CompactionNotes): Promise<void> {
884  await update($, compactions, count => (count ?? 0) + 1)
885  if (notes.isCacheTracked) await update($, cache, state => withCompact(state ?? NO_CACHE))
886  if (notes.isSessionShown) refreshAfterCompact($, before)
887}
888
889async function markCompact($: EngineInterface): Promise<CompactMark> {
890  return { before: (await read($, contextState))?.total, count: await read($, compactions) }
891}
892
893/**
894 * Notes a /compact that ran when the session.compact hook did not count it: a managed plugin in a tier above can send
895 * session.compact past every user plugin, while the command still reaches the mod.
896 */
897async function noteMissedCompaction($: EngineInterface, mark: CompactMark, notes: CompactionNotes): Promise<void> {
898  if ((await read($, compactions)) === mark.count) await noteCompaction($, mark.before, notes)
899}
900
901/** Compacts the conversation and leaves the held prompt in the box, where Enter sends it over the shorter context. */
902async function compactHeld($: EngineInterface, notes: CompactionNotes): Promise<void> {
903  if (!(await claimMove($, 'compact'))) return
904  try {
905    const mark = await markCompact($)
906    await $.command.run({ command: 'compact' })
907    await noteMissedCompaction($, mark, notes).catch(() => undefined)
908    await update($, cacheHold, () => null)
909  } catch {
910    $.ui.toast('session-info: the conversation was not compacted. The prompt is still in the box.')
911  } finally {
912    await update($, cacheMove, () => null).catch(() => undefined)
913    $.ui.invalidate('ui.render')
914  }
915}
916
917/** Clears the session and leaves the held prompt in the new session's box; a failure keeps this session. */
918async function newSessionHeld($: EngineInterface): Promise<void> {
919  if (!(await claimMove($, 'clear'))) return
920  try {
921    const hold = await read($, cacheHold)
922    if (hold !== null) await moveToNewSession(hostOf($), hold.text)
923  } catch {
924    $.ui.toast('session-info: the session was not cleared. The prompt is still in the box.')
925  } finally {
926    await update($, cacheMove, () => null).catch(() => undefined)
927    $.ui.invalidate('ui.render')
928  }
929}
930
931/**
932 * The cache guard: a prompt typed at an idle session over a cold cache and a big context is held, and the engine
933 * puts it back in the box. Sending it again lets it through; another prompt replaces it and is checked.
934 */
935async function guardPrompt($: EngineInterface, e: { text: string; origin: { kind: string }; turnId?: string; command?: unknown; isMeta?: true }, minTokens: number, setting: TtlSetting): Promise<{ drop: string } | undefined> {
936  const standing = e.origin.kind === 'composer' ? await read($, cacheHold) : null
937  if (standing !== null) {
938    await update($, cacheHold, () => null)
939    $.ui.invalidate('ui.render')
940    if (isSameMessage(e.text, standing.text)) return undefined
941  }
942  const state = await read($, cache)
943  if (state.touchedAt === undefined) return undefined
944  const status = cacheStatus(state, await read($, keepWarm), ttlOf(state, setting), await $.clock.now())
945  const context = contextOf((await $.session.usage()).context.tokens, state)
946  if (!shouldHold(e, { status, tokens: context, minTokens, isAfterCompact: state.isAfterCompact })) return undefined
947  const hold: CacheHold = { text: e.text, tokens: context, coldMs: status.kind === 'cold' ? status.ms : 0, isAgeUnknown: state.isAgeUnknown === true }
948  await update($, cacheHold, () => hold)
949  $.ui.invalidate('ui.render')
950
951  return { drop: holdText(hold) }
952}
953
954type OpenPaneArgs = { title: string; isGitShown: boolean; isSessionShown: boolean }
955
956async function openPane($: EngineInterface, { title, isGitShown, isSessionShown }: OpenPaneArgs): Promise<{ text: string }> {
957  if (isGitShown) void refreshRepo($)
958  if (isSessionShown) void refreshContext($).catch(() => undefined)
959  await $.ui.open({ id: PANE, title, focus: true })
960
961  return { text: 'Session info pane opened.' }
962}
963
964export const register: Register = (on, options) => {
965  const prefs: Prefs = {
966    viewer: (options.viewer as Viewer | undefined) ?? 'auto',
967    editor: (options.editor as Editor | undefined) ?? 'auto',
968    markdownEditor: typeof options.markdownEditor === 'string' ? options.markdownEditor.trim() : '',
969  }
970  const icons = (options.icons as IconSet | undefined) ?? 'unicode'
971  const shows = {
972    session: options.showSession !== false,
973    turn: options.showLastTurn !== false,
974    todos: options.showTodos !== false,
975    skills: options.showSkills !== false,
976    ci: options.showCi !== false,
977    usage: options.showUsage !== false,
978    agents: options.showAgents !== false,
979    background: options.showBackground !== false,
980    checks: options.showChecks !== false,
981    git: options.showGit !== false,
982    changes: options.showChanges !== false,
983    jira: options.showJira !== false,
984    autopick: options.showAutopick !== false,
985  }
986  const live: Countdowns = { controls: new Map() }
987  const keyPattern = toKeyPattern(options.jiraKeyPattern)
988  const gitClient = typeof options.gitClient === 'string' ? options.gitClient.trim() : 'lazygit'
989  const paneBackground = typeof options.paneBackground === 'string' ? options.paneBackground.trim() : ''
990  const paneTitle = customTitle(options.paneTitle)
991  const paneTitleColor = titleColor(options.paneTitleColor)
992  const paneTitleAlign = titleAlign(options.paneTitleAlign)
993  const openArgs: OpenPaneArgs = { title: paneTitle || DEFAULT_TITLE, isGitShown: shows.git, isSessionShown: shows.session }
994  const patterns: Patterns = { build: toPattern(options.buildPattern), test: toPattern(options.testPattern) }
995  const isAlerting = options.alerts !== false
996  const isSuggestingFix = shows.checks && options.suggestFix !== false
997  const order = parseSectionOrder(options.sectionOrder)
998  const groups = parseTabGroups(options.tabGroups)
999  const groupOf = new Map(groups.flatMap(group => group.members.map(key => [key, group] as const)))
1000  /** A grouped section folds with its group, whichever members show now. */
1001  const foldOf = (key: SectionKey): string => groupOf.get(key)?.key ?? key
1002  const isLive = shows.session || shows.usage || shows.agents || shows.checks || shows.background
1003  const isOpenOnStart = options.openOnStart === true
1004  const isUpdateChecked = options.checkUpdates !== false
1005  const positive = (value: unknown, fallback: number): number => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback)
1006  const cacheOptions: CacheOptions = {
1007    ttl: ttlSetting(options.cacheTtl),
1008    isGuarded: options.cacheGuard !== false,
1009    minTokens: positive(options.cacheGuardMinTokens, 150_000),
1010    keepWarmHours: positive(options.keepWarmHours, 4),
1011  }
1012  /** The Session section draws the cache, and the guard reads it: either one needs the requests followed. */
1013  const isCacheTracked = shows.session || cacheOptions.isGuarded
1014  const compactionNotes: CompactionNotes = { isCacheTracked, isSessionShown: shows.session }
1015
1016  /** The pane's layout mode toggles the sections, so /config leaves out their thirteen show* rows. */
1017  on('config.describe', { key: ORDER.map(key => `session-info.${showOption(key)}`) }, async ($, e, next) => ({ ...(await next(e)), isHidden: true }))
1018
1019  on('session.start', async ($, e, next) => {
1020    clearCount = 0
1021    await $.command.register({
1022      name: 'session-info',
1023      description: 'Show the session, plan usage and the files this session created, modified or deleted',
1024    })
1025    await $.command.register({ name: 'changes', description: 'Same as /session-info' })
1026    if (shows.todos) {
1027      await $.tool.register(TODO_SPEC).catch(error => $.ui.toast(`session-info: ${String(error)}`))
1028      await restoreTodos($).catch(() => undefined)
1029    }
1030    if (isLive || shows.git)
1031      $.clock.every(MINUTE, () => {
1032        if (isLive) void update($, now, () => Date.now())
1033        // The write alone redraws nothing after a /clear or a resume.
1034        if (isLive) $.ui.invalidate('ui.render')
1035        if (shows.session) void readMissingContext($)
1036        if (shows.git) void refreshRepo($)
1037      })
1038    if (shows.git) void refreshRepo($)
1039    if (shows.session) void refreshContext($).catch(() => undefined)
1040    if (isCacheTracked) $.clock.every(KEEP_WARM_TICK_MS, () => void keepWarmTick($, cacheOptions.ttl).catch(() => undefined))
1041    void seedTurns($).catch(() => undefined)
1042    if (isCacheTracked && shows.turn) void seedCache($).catch(() => undefined)
1043    if (isCacheTracked) void recoverCache($).catch(() => undefined)
1044    if (shows.ci) {
1045      $.clock.every(CI_POLL_MS, () => void pollCi($).catch(() => undefined))
1046      // A reload during a run picks the watch up again from the state.
1047      void pollCi($).catch(() => undefined)
1048    }
1049    if (shows.jira) void findJiraServer($).catch(() => undefined)
1050    void refreshVersion($, isUpdateChecked).catch(() => undefined)
1051    if (isUpdateChecked) $.clock.every(UPDATE_TICK_MS, () => void refreshVersion($, true).catch(() => undefined))
1052    if (shows.checks) await loadGuard($).catch(() => undefined)
1053    if (shows.todos) await loadContinue($).catch(() => undefined)
1054    if (shows.autopick) {
1055      await $.command.register({
1056        name: 'autopick',
1057        description: 'Pick the recommended option of a question left unanswered: status, on, off, <minutes>',
1058        argumentHint: '[on | off | <minutes>]',
1059        immediate: true,
1060      })
1061      await loadAutopick($).catch(() => undefined)
1062      // The other plugins register their commands in their own session.start: the check waits for them.
1063      $.clock.after(5_000, () => void checkRival($).catch(() => undefined))
1064    }
1065    // The engine draws a pane that the person did not ask for only on a wide terminal; a narrow one keeps it until /session-info.
1066    if (isOpenOnStart && e.isInteractive) await $.ui.open({ id: PANE, title: openArgs.title })
1067
1068    return next(e)
1069  })
1070
1071  // /clear starts a new conversation in the same process and raises no session.start: what belonged to the old one goes here.
1072  // Where an organization manages Claude Code this event never reaches the mod; session.end below does the same reset.
1073  on('classic.SessionStart', async ($, e, next) => {
1074    const started = await next(e)
1075    if (e.source === 'clear') {
1076      draft = undefined
1077      await clearConversation($, shows)
1078    }
1079    // A resume at launch says how long ago the last response came, so the cache's age is known before the first request.
1080    const secondsSince = e.seconds_since_last_response
1081    if (isCacheTracked && (e.source === 'resume' || e.source === 'fork') && secondsSince !== undefined) {
1082      const at = await $.clock.now()
1083      await update($, cache, state => withResume(state ?? NO_CACHE, { secondsSince, contextTokens: e.context_tokens }, at))
1084    }
1085
1086    return started
1087  })
1088
1089  if (isCacheTracked) {
1090    // The engine reports the TTL only here; a new model starts with no cache, and a resume restores the same one.
1091    on('classic.PostModelSwitch', async ($, e, next) => {
1092      const switched = await next(e)
1093      await update($, cache, state => withSwitch(state ?? NO_CACHE, e.cache_ttl, e.from_model !== e.to_model))
1094
1095      return switched
1096    }).catch(($, e, next) => next(e))
1097  }
1098
1099  if (cacheOptions.isGuarded) {
1100    on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1101      if (e.props.hasSurvey) return next(e)
1102      const move = await read($, cacheMove)
1103      const hold = await read($, cacheHold)
1104      if (move === null && hold === null) return next(e)
1105      const below = await next(e)
1106      const { Box, Button, Text } = $.ui.resolve(e)
1107      const isTerminal = e.surface === 'terminal'
1108
1109      // The same quiet frame as topic-guard's band: dim at rest, full under the pointer.
1110      const band = (
1111        <Box
1112          key="session-info-cache"
1113          flexDirection="column"
1114          borderStyle="round"
1115          borderColor="suggestion"
1116          borderDimColor
1117          paddingX={1}
1118          {...(isTerminal ? {} : { paddingY: 1, rowGap: 1 })}
1119          hover={{ borderDimColor: false }}
1120        >
1121          {move !== null || hold === null ? (
1122            <Text dimColor>
1123              <Text color="suggestion">◌ session-info</Text>
1124              {move === 'compact' ? ' · compacting the conversation…' : ' · clearing the session…'}
1125            </Text>
1126          ) : (
1127            <>
1128              <Box flexDirection="row" justifyContent="space-between">
1129                <Text>
1130                  <Text color="suggestion" bold>
1131                    ◇ session-info
1132                  </Text>
1133                  <Text dimColor>{` · ${holdTitle(hold)}`}</Text>
1134                </Text>
1135                <Text dimColor>{holdAge(hold)}</Text>
1136              </Box>
1137              <Text>{`Sending this prompt writes ${tokens(hold.tokens)} tokens of context to the cache again.`}</Text>
1138              <Box flexDirection="row">
1139                <Button key="cache-compact" label="Compact" variant="primary" onPress={() => void compactHeld($, compactionNotes).catch(() => undefined)} />
1140                <Text>  </Text>
1141                <Button key="cache-new" label="New session" onPress={() => void newSessionHeld($).catch(() => undefined)} />
1142                <Text dimColor>  or press Enter to send it here</Text>
1143              </Box>
1144            </>
1145          )}
1146        </Box>
1147      )
1148
1149      return below ? (
1150        <Box flexDirection="column">
1151          {band}
1152          {below}
1153        </Box>
1154      ) : band
1155    })
1156  }
1157
1158  // A /clear ends the session as session.end with reason clear; the module and its count go on.
1159  on('session.end', async ($, e, next) => {
1160    if (e.reason === 'clear') {
1161      clearCount += 1
1162      // The count is no state value: nothing else draws it.
1163      if (shows.session) $.ui.invalidate('ui.render')
1164    }
1165    // The next conversation's state starts empty and a draw may not write: what session.start loads is loaded here.
1166    if (e.reason === 'clear' || e.reason === 'resume') {
1167      const isResume = e.reason === 'resume'
1168      afterSwitch($, e.sessionId, async () => {
1169        // The classic.SessionStart reset may never arrive; the new conversation is clean until its first prompt is sent,
1170        // so this reset cannot wipe anything it wrote.
1171        if (!isResume && (await $.session.turns().catch(() => 1)) === 0) {
1172          draft = undefined
1173          await clearConversation($, shows).catch(() => undefined)
1174        }
1175        if (shows.todos && isResume) await restoreTodos($).catch(() => undefined)
1176        if (isResume) await seedTurns($).catch(() => undefined)
1177        if (isResume && isCacheTracked) await recoverCache($).catch(() => undefined)
1178        if (shows.git) void refreshRepo($)
1179        // The footer's version was read in session.start; the next conversation's state starts without it.
1180        void refreshVersion($, isUpdateChecked).catch(() => undefined)
1181        if (shows.jira) await findJiraServer($).catch(() => undefined)
1182        if (shows.checks) await loadGuard($).catch(() => undefined)
1183        if (shows.todos) await loadContinue($).catch(() => undefined)
1184        if (shows.autopick) {
1185          await loadAutopick($).catch(() => undefined)
1186          await checkRival($).catch(() => undefined)
1187        }
1188        // A CI watch belongs to the conversation that pushed.
1189        if (shows.ci) await update($, ciState, () => null)
1190        if (shows.session) await refreshContext($).catch(() => undefined)
1191        $.ui.invalidate('ui.render')
1192      })
1193    }
1194
1195    return next(e)
1196  })
1197
1198  on('command.run', { command: 'session-info' }, async $ => openPane($, openArgs))
1199
1200  on('command.run', { command: 'changes' }, async $ => openPane($, openArgs))
hooks/agents.ts 80 lines
1import type { AgentModel } from '../types'
2
3/** One agent loop as `$.agent.list()` reports it. */
4export type Agent = {
5  id: string
6  type: string
7  description: string
8  status: 'pending' | 'running' | 'waiting' | 'idle' | 'completed' | 'failed' | 'killed'
9  parentId?: string
10  name?: string
11}
12
13export type AgentRow = { agent: Agent; depth: number }
14
15export const AGENT_STATUS = {
16  running: { glyph: '⟳', color: 'suggestion' },
17  pending: { glyph: '◌', color: 'inactive' },
18  waiting: { glyph: '⏸', color: 'warning' },
19  idle: { glyph: '○', color: 'inactive' },
20  completed: { glyph: '✓', color: 'success' },
21  failed: { glyph: '✖', color: 'error' },
22  killed: { glyph: '⊘', color: 'error' },
23} as const satisfies Record<Agent['status'], { glyph: string; color: string }>
24
25const RANK: Record<Agent['status'], number> = {
26  running: 0, waiting: 1, pending: 2, idle: 3, failed: 4, killed: 5, completed: 6,
27}
28
29const isActive = (agent: Agent): boolean => RANK[agent.status] <= RANK.pending
30
31/** Active agents first, each followed by the agents it spawned, indented under it. */
32export function agentRows(agents: readonly Agent[]): AgentRow[] {
33  const ids = new Set(agents.map(agent => agent.id))
34  const byRank = [...agents].sort((a, b) => RANK[a.status] - RANK[b.status])
35  const rows: AgentRow[] = []
36  const walk = (parentId: string | undefined, depth: number): void => {
37    for (const agent of byRank) {
38      const isChild = parentId === undefined ? agent.parentId === undefined || !ids.has(agent.parentId) : agent.parentId === parentId
39      if (!isChild) continue
40      rows.push({ agent, depth })
41      walk(agent.id, depth + 1)
42    }
43  }
44  walk(undefined, 0)
45
46  return rows
47}
48
49export const agentLabel = (agent: Agent): string => agent.name ?? agent.type
50
51/** The models with this agent's entry set; the same object when nothing changed, so a step that repeats them redraws nothing. */
52export function withAgentModel(
53  models: Readonly<Record<string, AgentModel>>,
54  agentId: string,
55  model: string,
56  effort?: string | number,
57): Record<string, AgentModel> {
58  const known = models[agentId]
59  // The spawn names no effort: the effort a request already reported stays.
60  const next = effort === undefined ? (known?.model === model ? known : { model }) : { model, effort: String(effort) }
61  if (known !== undefined && known.model === next.model && known.effort === next.effort) return models
62
63  return { ...models, [agentId]: next }
64}
65
66/** ` · claude-haiku-5-5 · low`, or '' when the agent's model is unknown. */
67export const agentModelText = (run: AgentModel | undefined): string =>
68  run === undefined ? '' : [run.model, run.effort].filter(part => part !== undefined).map(part => ` · ${part}`).join('')
69
70/** `2 running · 1 idle · 3 done`, or `none`. */
71export function agentSummary(agents: readonly Agent[]): string {
72  if (agents.length === 0) return 'none'
73  const active = agents.filter(isActive).length
74  const idle = agents.filter(agent => agent.status === 'idle').length
75  const done = agents.length - active - idle
76  const parts = [[active, 'running'], [idle, 'idle'], [done, 'done']] as const
77
78  return parts.filter(([count]) => count > 0).map(([count, word]) => `${count} ${word}`).join(' · ')
79}
80
hooks/alerts.ts 54 lines
1import { tokens } from './session'
2import { labelOf, resetIn } from './usage'
3import type { Limit } from './usage'
4
5export const USAGE_THRESHOLDS = [80, 90] as const
6
7export const CONTEXT_THRESHOLD = 85
8
9export type Alert = { key: string; title: string; body: string }
10
11type Context = { percent?: number; tokens?: number; window: number }
12
13/** A usage alert's key names its window instance, so a window that resets can alert again. */
14const usageKey = (limit: Limit, threshold: number): string => `${limit.kind}@${limit.resetsAt ?? ''}:${threshold}`
15
16const CONTEXT_KEY = `context:${CONTEXT_THRESHOLD}`
17
18/**
19 * The thresholds this measurement crosses that have not alerted yet, and the alert keys still standing:
20 * a reset window drops its keys, a context back under the threshold drops its key.
21 */
22export function crossings(
23  limits: readonly Limit[],
24  context: Context,
25  alerted: readonly string[],
26  now: number,
27): { alerts: Alert[]; standing: string[] } {
28  const live = new Set(limits.flatMap(limit => USAGE_THRESHOLDS.map(threshold => usageKey(limit, threshold))))
29  const isContextHigh = (context.percent ?? 0) >= CONTEXT_THRESHOLD
30  const standing = alerted.filter(key => live.has(key) || (key === CONTEXT_KEY && isContextHigh))
31  const alerts: Alert[] = []
32
33  for (const limit of limits) {
34    const crossed = USAGE_THRESHOLDS.filter(threshold => limit.percentUsed >= threshold)
35    const top = crossed[crossed.length - 1]
36    if (top === undefined || crossed.every(threshold => standing.includes(usageKey(limit, threshold)))) continue
37    const reset = resetIn(limit.resetsAt, now)
38    alerts.push({
39      key: usageKey(limit, top),
40      title: 'Claude usage',
41      body: `${labelOf(limit.kind)} at ${Math.round(limit.percentUsed)}%${reset === undefined ? '' : ` · ${reset}`}`,
42    })
43    standing.push(...crossed.map(threshold => usageKey(limit, threshold)))
44  }
45
46  if (isContextHigh && !standing.includes(CONTEXT_KEY)) {
47    const size = context.tokens === undefined ? '' : ` (${tokens(context.tokens)} / ${tokens(context.window)})`
48    alerts.push({ key: CONTEXT_KEY, title: 'Claude context', body: `Context at ${Math.round(context.percent ?? 0)}%${size}: compaction is near` })
49    standing.push(CONTEXT_KEY)
50  }
51
52  return { alerts, standing }
53}
54
hooks/autocontinue.ts 92 lines
1import type { AutoContinue, ContinueRun, Todo } from '../types'
2
3/** The `$.store` key of the auto-continue switch; the store outlives the session, so the switch stays as the person left it. */
4export const CONTINUE_STORE = 'autoContinueOn'
5
6export const NO_CONTINUE: AutoContinue = { count: 0, total: 0, last: null }
7
8/** Continues in a row after one prompt of the person's; past them the turn ends, so a loop that makes no progress stops. */
9export const MAX_CONTINUES = 5
10
11/** The last lines of a reply that may hold its question: a status line or a note can follow it. */
12const QUESTION_LINES = 3
13
14/** Markdown that can close a line after its question mark: emphasis, code and a closing bracket. */
15const TRAILING_MARKUP = /[\s*_`)\]]+$/
16
17/** What the Stop event and the state say at the end of a main-loop turn. */
18export type StopFacts = {
19  isOn: boolean
20  todos: readonly Todo[]
21  lastMessage: string
22  hasPendingWork: boolean
23  state: AutoContinue
24}
25
26const isOpen = (todo: Todo): boolean => todo.status === 'pending' || todo.status === 'in_progress'
27
28/** The open tasks as one text, so a stop with the same open tasks as the last continue shows that nothing moved. */
29export const openTasksKey = (todos: readonly Todo[]): string =>
30  todos.filter(isOpen).map(todo => `${todo.status}:${todo.content}`).join('\n')
31
32/** Whether one of the last lines of the reply asks something: the turn then waits for the person's answer. */
33export function endsWithQuestion(text: string): boolean {
34  const lines = text
35    .split('\n')
36    .map(line => line.replace(TRAILING_MARKUP, ''))
37    .filter(line => line !== '' && !line.startsWith('```'))
38
39  return lines.slice(-QUESTION_LINES).some(line => line.endsWith('?'))
40}
41
42/**
43 * The text that sends Claude on with the next task, or undefined when the turn should end: the switch is off, no task
44 * is open, background work or a scheduled wake-up will start the next turn, the reply asks the person something, the
45 * limit of continues in a row is reached, or the open tasks are the same as at the last continue.
46 */
47export function continueReason(facts: StopFacts): string | undefined {
48  const open = facts.todos.filter(isOpen)
49  if (!facts.isOn || open.length === 0 || facts.hasPendingWork) return undefined
50  if (endsWithQuestion(facts.lastMessage)) return undefined
51  if (facts.state.count >= MAX_CONTINUES || facts.state.last === openTasksKey(facts.todos)) return undefined
52
53  return [
54    `session-info auto-continue: the task list still has ${open.length} open ${open.length === 1 ? 'task' : 'tasks'}. Next: ${nextTask(facts.todos)}.`,
55    'Continue with it now, and keep the task list current.',
56    'If the next step needs the person: a decision, an approval, a push, a deploy, a message to other people or a change that cannot be undone, stop and ask instead.',
57    'If a task is no longer needed, mark it cancelled.',
58  ].join('\n')
59}
60
61/** The task a continue sends Claude on: the one in progress, else the first pending one. */
62export function nextTask(todos: readonly Todo[]): string {
63  const open = todos.filter(isOpen)
64
65  return (open.find(todo => todo.status === 'in_progress') ?? open[0])?.content ?? ''
66}
67
68/** The state after a continue at `at`: one more in a row and in all, the open tasks it was sent on, and its record. */
69export function withContinue(state: AutoContinue, todos: readonly Todo[], at: number, reason: string): AutoContinue {
70  const count = state.count + 1
71
72  return {
73    count,
74    total: state.total + 1,
75    last: openTasksKey(todos),
76    lastRun: { at, count, next: nextTask(todos), reason },
77  }
78}
79
80/** The state after a prompt of the person's: the count in a row starts over; the last continue's row stays. */
81export const withPrompt = (state: AutoContinue): AutoContinue => ({ ...state, count: 0, last: null })
82
83/** The switch row's right side: `3 continues`; empty before the first one. */
84export const continueText = (state: AutoContinue): string =>
85  state.total === 0 ? '' : `${state.total} ${state.total === 1 ? 'continue' : 'continues'}`
86
87/** The last continue's row: `Continued 2/5 · next: Write the hook`. */
88export const lastContinueText = (run: ContinueRun): string => `Continued ${run.count}/${MAX_CONTINUES} · next: ${run.next}`
89
90/** The transcript line of a continue, as the person reads it: `session-info: auto-continue 2/5, next: Write the hook`. */
91export const continueLog = (run: ContinueRun): string => `session-info: auto-continue ${run.count}/${MAX_CONTINUES}, next: ${run.next}`
92
hooks/autopick.ts 158 lines
1import type { AutopickPick, AutopickSettings } from '../types'
2
3// The pick rules follow ask-autopick by Kerem Gok (MIT): https://github.com/KilimcininKorOglu/claude-code-mods/tree/main/plugins/ask-autopick
4
5/** One question of an AskUserQuestion call, as far as autopick reads it. */
6export type Question = { question: string; multiSelect?: boolean; options?: { label: string }[] }
7
8/** The `$.store` keys of the two settings. */
9export const STORE_ON = 'autopickOn'
10export const STORE_MINUTES = 'autopickMinutes'
11
12export const DEFAULT_MINUTES = 10
13
14/** The waits the − and + buttons step through; `/autopick <minutes>` takes any whole number from the first to the last. */
15export const MINUTE_STEPS: readonly number[] = [1, 2, 3, 5, 10, 15, 20, 30, 45, 60, 90, 120]
16
17const MIN_MINUTES = MINUTE_STEPS[0] ?? 1
18const MAX_MINUTES = MINUTE_STEPS.at(-1) ?? 120
19
20export const DEFAULT_SETTINGS: AutopickSettings = { isOn: false, minutes: DEFAULT_MINUTES }
21
22/** The command that ask-autopick registers; a session that lists it has that mod loaded. */
23const RIVAL_COMMAND = 'ask-autopick'
24
25/**
26 * The words a model writes in parentheses after the option it recommends. The tool tells it to write `(Recommended)`,
27 * and in a question written in another language it writes that word in the language.
28 */
29const RECOMMENDED_WORDS = [
30  'recommended', 'önerilen', 'empfohlen', 'recomendado', 'recomendada', 'recommandé', 'recommandée',
31  'consigliato', 'consigliata', 'aanbevolen', 'zalecane', 'рекомендуется', '推荐', '推薦', '推奨', 'おすすめ', '권장', '추천',
32]
33
34/** A label that ends with one of those words in parentheses, ASCII or full-width. */
35const RECOMMENDED_END = new RegExp(`[((]\\s*(?:${RECOMMENDED_WORDS.join('|')})\\s*[))]\\s*$`, 'iu')
36
37export const isRecommended = (label: string): boolean => RECOMMENDED_END.test(label)
38
39/**
40 * The recommended label of one question: the first option, marked at the end of its label, with no other option
41 * marked. Undefined for a question that takes several answers or has no such option.
42 */
43function pickOf(question: Question): string | undefined {
44  const [first, ...rest] = question.options ?? []
45  if (question.multiSelect === true || first === undefined || !isRecommended(first.label)) return undefined
46
47  return rest.some(option => isRecommended(option.label)) ? undefined : first.label
48}
49
50/** One recommended label per question, or undefined when a question has none: such a call waits for the person. */
51export function picksOf(questions: readonly Question[]): Record<string, string> | undefined {
52  if (questions.length === 0) return undefined
53  const picks: Record<string, string> = {}
54  for (const question of questions) {
55    const label = pickOf(question)
56    if (label === undefined) return undefined
57    picks[question.question] = label
58  }
59
60  return picks
61}
62
63/** The settings as `$.store` holds them; a missing or broken value reads as its default. */
64export function settingsOf(isOn: unknown, minutes: unknown): AutopickSettings {
65  return {
66    isOn: isOn === true,
67    minutes: typeof minutes === 'number' && minutesOf(String(minutes)) !== undefined ? minutes : DEFAULT_MINUTES,
68  }
69}
70
71/** The minutes a `/autopick <word>` argument names, or undefined when it names none in range. */
72export function minutesOf(arg: string): number | undefined {
73  if (!/^\d{1,3}$/.test(arg)) return undefined
74  const n = Number(arg)
75
76  return n >= MIN_MINUTES && n <= MAX_MINUTES ? n : undefined
77}
78
79/** The next wait up or down the steps; a wait between two steps moves to the nearer one in that direction. */
80export function stepMinutes(minutes: number, direction: 1 | -1): number {
81  if (direction > 0) return MINUTE_STEPS.find(step => step > minutes) ?? MAX_MINUTES
82
83  return [...MINUTE_STEPS].reverse().find(step => step < minutes) ?? MIN_MINUTES
84}
85
86/** Whether a command list names ask-autopick's command, which means that mod is loaded. */
87export const hasRival = (commands: readonly { name: string; plugin?: string }[]): boolean =>
88  commands.some(command => command.name === RIVAL_COMMAND || command.plugin === RIVAL_COMMAND)
89
90/** `7:05` for the time left; never below `0:00`. */
91export function countdown(ms: number): string {
92  const seconds = Math.max(0, Math.ceil(ms / 1_000))
93
94  return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`
95}
96
97/** `Color? → Blue (Recommended)`, the questions of one call joined. */
98export const picksText = (picks: Readonly<Record<string, string>>): string =>
99  Object.entries(picks)
100    .map(([question, label]) => `${question} → ${label}`)
101    .join('; ')
102
103/** The picks one per line, `question → label`, for the detail view. */
104export const picksDetail = (picks: Readonly<Record<string, string>>): string =>
105  Object.entries(picks)
106    .map(([question, label]) => `${question} → ${label}`)
107    .join('\n')
108
109/** What a pick was and why it happened, then its picks one per line: the detail view of the Picked line. */
110export const pickDetail = (pick: AutopickPick): string =>
111  `${pick.isByHand ? 'Pick now pressed' : `No answer in ${pick.minutes} min`}\n${picksDetail(pick.picks)}`
112
113/** The header's right side: `on · 10 min` or `off`. */
114export const autopickSummary = (settings: AutopickSettings): string => (settings.isOn ? `on · ${settings.minutes} min` : 'off')
115
116/** The line the transcript keeps for a pick. */
117export function pickedLog(pick: AutopickPick): string {
118  const why = pick.isByHand ? 'Pick now pressed' : `no answer in ${pick.minutes} min`
119
120  return `session-info: ${why}, picked the recommended option: ${picksText(pick.picks)}`
121}
122
123/**
124 * What the model reads after the picked answer. It says who set the rule: the person turned Autopick on and chose the
125 * wait, so the pick applies their standing instruction. A text that called it "not their decision" made the model
126 * refuse to act on it and leave the question open, which defeats the switch the person turned on.
127 */
128export function pickedNote(pick: AutopickPick): string {
129  return pick.isByHand
130    ? 'session-info autopick: the person pressed Pick now, which takes the option you marked (Recommended) without going through the others. Proceed with it as their answer, and name the pick in your next reply so they can change it.'
131    : `session-info autopick: the person turned Autopick on with a ${pick.minutes}-minute wait. They told the session to take the option you marked (Recommended) when they do not answer in that time. This answer applies that standing instruction: proceed with it as their answer, and name the pick in your next reply so they can change it.`
132}
133
134/**
135 * The system prompt section while Autopick is on: the rule, said before the question, so the model marks
136 * (Recommended) only where it may act without the person. A question with no marked option is never picked
137 * (`picksOf`), so this keeps the questions that need the person waiting for them.
138 */
139export function autopickPrompt(minutes: number): string {
140  return [
141    '# Autopick',
142    `The person turned Autopick on: when they leave an AskUserQuestion question unanswered for ${minutes} ${minutes === 1 ? 'minute' : 'minutes'}, the option you marked (Recommended) is picked as their answer, by their standing instruction.`,
143    'Mark an option (Recommended) only when you can carry it out without the person.',
144    "When the step needs the person's own approval (a change that cannot be undone, a push, a deploy, a message to other people, or a gate an instruction reserves for the person), mark no option (Recommended): Autopick then leaves the question for the person.",
145  ].join('\n')
146}
147
148/** The `/autopick` answer. */
149export function statusText(settings: AutopickSettings, isBlocked: boolean): string {
150  if (isBlocked) return 'off · the ask-autopick mod is loaded and answers questions too; disable it to use this one'
151
152  return settings.isOn
153    ? `on · a question unanswered for ${settings.minutes} min gets its recommended option`
154    : `off · questions wait for you; /autopick on picks the recommended option after ${settings.minutes} min`
155}
156
157export const AUTOPICK_USAGE = 'Usage: /autopick [on | off | <minutes from 1 to 120>]'
158
hooks/background.ts 127 lines
1import type { BackgroundStatus, BackgroundTask } from '../types'
2
3import { duration } from './session'
4import type { TaskEnd } from './tasks'
5
6/** The most background commands the section keeps; the oldest finished one drops when a newer starts. */
7export const BACKGROUND_LIMIT = 30
8/** The most background commands the section lists; a longer list shows the first ones and a count. */
9export const BACKGROUND_ROOM = 8
10/** The longest command or description the state keeps; a longer one is cut. */
11export const TEXT_LIMIT = 1_000
12/** The tool that stops a background task; the task it stops sends no notification. */
13export const STOP_TOOL = 'TaskStop'
14
15/** Glyph, word and theme color of each status; the word is what a color-blind reader goes by. */
16export const BACKGROUND_STATUS = {
17  running: { glyph: '⟳', word: 'running', color: 'suggestion' },
18  completed: { glyph: '✓', word: 'done', color: 'success' },
19  failed: { glyph: '✖', word: 'failed', color: 'error' },
20  killed: { glyph: '⊘', word: 'stopped', color: 'warning' },
21  ended: { glyph: '•', word: 'ended', color: 'inactive' },
22} as const satisfies Record<BackgroundStatus, { glyph: string; word: string; color: string }>
23
24/** The first line of a text that has any, trimmed: what a row draws of a command that spans lines. */
25export const firstLine = (text: string): string => (text.split(/\r?\n/).find(line => line.trim() !== '') ?? '').trim()
26
27const kept = (text: string): string => text.trim().slice(0, TEXT_LIMIT)
28
29/**
30 * The background task a finished shell call started: its id comes from `backgroundTaskId` in the call's result, so a
31 * command that ran to its end, failed or was refused gives none. The text kept is the command and the description
32 * the caller wrote, never the output.
33 */
34export function startedTask(input: Record<string, unknown>, ran: Record<string, unknown>, at: number): BackgroundTask | undefined {
35  if (ran.deny !== undefined || ran.isError === true) return undefined
36  const result = typeof ran.result === 'object' && ran.result !== null ? (ran.result as Record<string, unknown>) : {}
37  const id = result.backgroundTaskId
38  if (typeof id !== 'string' || id === '') return undefined
39  const command = typeof input.command === 'string' ? kept(input.command) : ''
40  const description = typeof input.description === 'string' ? kept(firstLine(input.description)) : ''
41
42  return { id, command, ...(description === '' ? {} : { description }), status: 'running', at }
43}
44
45/** The tasks with this one in front, the newest; a task already there under the same id is replaced, and the list is cut to BACKGROUND_LIMIT. */
46export const withTask = (tasks: readonly BackgroundTask[], task: BackgroundTask): BackgroundTask[] =>
47  [task, ...tasks.filter(one => one.id !== task.id)].slice(0, BACKGROUND_LIMIT)
48
49/** A notification's status as a task status; anything but completed or killed counts as failed. */
50export const statusOf = (status: string): BackgroundStatus => (status === 'completed' || status === 'killed' ? status : 'failed')
51
52/** Whether a notification can still set the task's status: it runs, or it ended with no status known. */
53const isOpen = (task: BackgroundTask): boolean => task.status === 'running' || task.status === 'ended'
54
55/**
56 * The tasks with the one the notification names marked as ended; the same array when it names none open. A task the
57 * stop already took as ended gets the notification's status and keeps the time it ended.
58 */
59export function withEnd(tasks: BackgroundTask[], end: TaskEnd, at: number): BackgroundTask[] {
60  if (!tasks.some(task => task.id === end.taskId && isOpen(task))) return tasks
61
62  return tasks.map(task => (task.id === end.taskId && isOpen(task) ? { ...task, status: statusOf(end.status), endedAt: task.endedAt ?? at } : task))
63}
64
65/** The task a `TaskStop` call stopped: the id in its input once the call succeeded; a refused or failed call stops none. */
66export function stoppedTaskId(input: Record<string, unknown>, ran: Record<string, unknown>): string | undefined {
67  if (ran.deny !== undefined || ran.isError === true) return undefined
68  const id = input.task_id
69
70  return typeof id === 'string' && id !== '' ? id : undefined
71}
72
73/** The tasks with the stopped one marked killed; the same array when it names none that runs. */
74export const withStopped = (tasks: BackgroundTask[], taskId: string, at: number): BackgroundTask[] => withEnd(tasks, { taskId, status: 'killed' }, at)
75
76/**
77 * The tasks with each running one that the engine no longer lists in flight marked ended with no status known: a task
78 * that ends with no notification, such as one stopped from the tasks dialog, leaves the list this way. The same array
79 * when every running task is still in flight.
80 */
81export function withInFlight(tasks: BackgroundTask[], inFlight: readonly string[], at: number): BackgroundTask[] {
82  const isGone = (task: BackgroundTask) => task.status === 'running' && !inFlight.includes(task.id)
83  if (!tasks.some(isGone)) return tasks
84
85  return tasks.map(task => (isGone(task) ? { ...task, status: 'ended', endedAt: at } : task))
86}
87
88/** The ids of the tasks a stop lists in flight; undefined when the stop has no such list, so nothing is taken as ended. */
89export function inFlightIds(stop: { background_tasks?: unknown }): string[] | undefined {
90  if (!Array.isArray(stop.background_tasks)) return undefined
91
92  return stop.background_tasks.flatMap(task => {
93    const id = typeof task === 'object' && task !== null ? (task as { id?: unknown }).id : undefined
94
95    return typeof id === 'string' ? [id] : []
96  })
97}
98
99/** Running tasks first, then the ended ones; each group keeps its newest-first order. */
100export const orderedTasks = (tasks: readonly BackgroundTask[]): BackgroundTask[] =>
101  [...tasks.filter(task => task.status === 'running'), ...tasks.filter(task => task.status !== 'running')]
102
103/** What the task is called: the description its caller wrote, else the command. */
104export const taskLabel = (task: BackgroundTask): string => task.description ?? (task.command === '' ? task.id : firstLine(task.command))
105
106/** Whether the row has a second line: the command under a description that names it. */
107export const hasCommandLine = (task: BackgroundTask): boolean => task.description !== undefined && task.command !== ''
108
109/** The rows the listed tasks take: one line each, and a second for the command under a description. */
110export const taskRowCount = (tasks: readonly BackgroundTask[]): number => tasks.reduce((sum, task) => sum + 1 + (hasCommandLine(task) ? 1 : 0), 0)
111
112/** `running · 3m 2s` while it runs, `done · 12s` once it ended: the time it has run or ran for. */
113export function taskState(task: BackgroundTask, now: number): string {
114  const word = BACKGROUND_STATUS[task.status].word
115
116  return `${word} · ${duration((task.endedAt ?? now) - task.at)}`
117}
118
119/** `2 running · 1 done · 1 failed`, or `none`. */
120export function backgroundSummary(tasks: readonly BackgroundTask[]): string {
121  if (tasks.length === 0) return 'none'
122  const count = (status: BackgroundStatus) => tasks.filter(task => task.status === status).length
123  const parts = (Object.keys(BACKGROUND_STATUS) as BackgroundStatus[]).map(status => [count(status), BACKGROUND_STATUS[status].word] as const)
124
125  return parts.filter(([total]) => total > 0).map(([total, word]) => `${total} ${word}`).join(' · ')
126}
127
hooks/cache.ts 283 lines
1import type { CacheHold, CacheState, CacheTtl, KeepWarm } from '../types'
2
3import type { Host } from './host'
4import { tokens } from './session'
5
6const MINUTE_MS = 60_000
7const HOUR_MS = 60 * MINUTE_MS
8
9/** How long each TTL keeps an entry after the last request that read or wrote it. */
10export const TTL_MS = { '5m': 5 * MINUTE_MS, '1h': HOUR_MS } as const satisfies Record<CacheTtl, number>
11
12/** The longest stretch before expiry that the cache counts as cooling; a short TTL cools over its last fifth. */
13const COOLING_MS = 5 * MINUTE_MS
14
15/** A request with less input than this tells nothing about the TTL: a small prefix can sit under the cache's minimum. */
16const JUDGE_MIN_TOKENS = 30_000
17
18/** An idle gap past the short TTL, with a margin for the time a request takes. */
19const SHORT_GAP_MS = 5.5 * MINUTE_MS
20
21/** A request that writes more than this share of its input wrote the context to the cache again. */
22const WRITE_SHARE = 0.5
23
24/** A request that reads more than this share of its input from the cache found it warm. */
25const READ_SHARE = 0.8
26
27/** A keep-warm ping that writes more than this share of what it reads missed the cache. */
28const PING_MISS_SHARE = 0.1
29
30/** The one message a keep-warm ping sends over the conversation; its reply is thrown away. */
31export const KEEP_WARM_PROMPT = 'session-info keep-warm ping. Reply with only: ok'
32
33/** The TTL setting: `auto` follows the plan and the session's requests; `5m` and `1h` fix it. */
34export type TtlSetting = 'auto' | CacheTtl
35
36/** The cache before the first request: the TTL waits for the plan, the first request sets it. */
37export const NO_CACHE: CacheState = { ttl: '1h', ttlSource: 'plan', tokens: 0, restarts: 0, restartTokens: 0, isAfterCompact: false }
38
39/** Token counts of one request, in the API's spelling. */
40export type CacheUsage = { input_tokens: number; cache_read_input_tokens: number; cache_creation_input_tokens: number }
41
42/** One main-thread request: its usage, when it started and ended, and whether the account reports plan limits. */
43export type CacheRequest = { usage: CacheUsage; startedAt: number; endedAt: number; hasPlanLimits: boolean }
44
45export type CacheKind = 'unknown' | 'warm' | 'cooling' | 'cold' | 'kept'
46
47/** The cache now: warm, cooling or kept with `ms` left, cold for `ms`, or unknown before the first request. */
48export type CacheStatus = { kind: 'unknown' } | { kind: Exclude<CacheKind, 'unknown'>; ms: number }
49
50export const CACHE_STATUS = {
51  unknown: { glyph: '·', color: undefined },
52  warm: { glyph: '●', color: 'success' },
53  cooling: { glyph: '◐', color: 'warning' },
54  cold: { glyph: '○', color: 'error' },
55  kept: { glyph: '◆', color: 'suggestion' },
56} as const satisfies Record<CacheKind, { glyph: string; color: string | undefined }>
57
58/** A prompt as `prompt.submit` receives it, as far as the guard reads it. */
59export type Submission = { text: string; origin: { kind: string }; turnId?: string; command?: unknown; isMeta?: true }
60
61/** What decides a hold: the cache now, the context the prompt would write, the guard's minimum, and a compaction since the last request. */
62export type HoldGate = { status: CacheStatus; tokens: number; minTokens: number; isAfterCompact: boolean }
63
64/** What a keep-warm ping did: read the cache, missed it and wrote it, or got no answer. */
65export type PingVerdict = 'hit' | 'miss' | 'none'
66
67export const ttlSetting = (value: unknown): TtlSetting => (value === '5m' || value === '1h' ? value : 'auto')
68
69/** The TTL in use: the setting when it fixes one, else what the session found. */
70export const ttlOf = (state: CacheState, setting: TtlSetting): CacheTtl => (setting === 'auto' ? state.ttl : setting)
71
72export const totalOf = (usage: CacheUsage): number => usage.input_tokens + usage.cache_read_input_tokens + usage.cache_creation_input_tokens
73
74/**
75 * The cache after a main-thread request. A plan account is on the 1-hour TTL and an API account on 5 minutes; then
76 * the requests correct it: a re-cache after an idle gap between the two TTLs shows 5 minutes, and a warm read after a
77 * gap past 5 minutes shows 1 hour. The first request after a compaction writes the shorter context, which is no restart.
78 */
79export function withRequest(state: CacheState, request: CacheRequest): CacheState {
80  const total = totalOf(request.usage)
81  const written = request.usage.cache_creation_input_tokens
82  const gap = state.touchedAt === undefined ? undefined : request.startedAt - state.touchedAt
83  const planTtl: CacheTtl = request.hasPlanLimits ? '1h' : '5m'
84  // The plan limits can still be empty right after the first response; only a later one makes an empty list mean an API key.
85  const isPlanKnown = state.ttlSource === 'plan' && (request.hasPlanLimits || state.touchedAt !== undefined)
86  const touched: CacheState = {
87    ...state,
88    touchedAt: request.endedAt,
89    tokens: total,
90    isAfterCompact: false,
91    isAgeUnknown: false,
92    ...(isPlanKnown ? { ttl: planTtl } : {}),
93  }
94  if (state.isAfterCompact || gap === undefined || total < JUDGE_MIN_TOKENS) return touched
95  const canMeasure = state.ttlSource !== 'switch' && gap > SHORT_GAP_MS
96  if (written / total > WRITE_SHARE) {
97    const restarted = { ...touched, restarts: state.restarts + 1, restartTokens: state.restartTokens + written }
98
99    return canMeasure && gap < HOUR_MS ? { ...restarted, ttl: '5m', ttlSource: 'measured' } : restarted
100  }
101  if (canMeasure && request.usage.cache_read_input_tokens / total > READ_SHARE) return { ...touched, ttl: '1h', ttlSource: 'measured' }
102
103  return touched
104}
105
106/** A model switch names the TTL; a new model has no cache yet, while the same model restored on a resume keeps it. */
107export const withSwitch = (state: CacheState, ttl: CacheTtl, isNewModel: boolean): CacheState =>
108  isNewModel
109    ? { ttl, ttlSource: 'switch', tokens: state.tokens, restarts: state.restarts, restartTokens: state.restartTokens, isAfterCompact: state.isAfterCompact }
110    : { ...state, ttl, ttlSource: 'switch' }
111
112export const withCompact = (state: CacheState): CacheState => ({ ...state, isAfterCompact: true })
113
114/** What the engine says about a session resumed at start: how long ago the last response came, and the context it left. */
115export type Resume = { secondsSince: number; contextTokens?: number }
116
117/** A session resumed at start: the cache dates from the last response, and the context is what that response left. */
118export const withResume = (state: CacheState, resume: Resume, at: number): CacheState => ({
119  ...state,
120  touchedAt: at - resume.secondsSince * 1_000,
121  tokens: resume.contextTokens ?? state.tokens,
122  isAgeUnknown: false,
123})
124
125/** The store key of the last cache touch of each session, which outlives the process and is shared by every window. */
126export const TOUCH_STORE = 'cacheTouches'
127
128/** The most sessions the store keeps a touch for; the least recent go first. */
129const TOUCH_LIMIT = 24
130
131/** How far back a resumed session with no touch on record is taken to have touched the cache: past every TTL. */
132const UNKNOWN_AGE_MS = 24 * HOUR_MS
133
134/** When a session last touched the cache and the context it held then. */
135export type CacheTouch = { at: number; tokens: number }
136
137export type CacheTouches = Record<string, CacheTouch>
138
139const isTouch = (value: unknown): value is CacheTouch =>
140  typeof value === 'object' && value !== null && 'at' in value && typeof value.at === 'number' && 'tokens' in value && typeof value.tokens === 'number'
141
142/** The touches as the store holds them: a record of sessions, with every entry of another shape left out. */
143export function readTouches(value: unknown): CacheTouches {
144  if (typeof value !== 'object' || value === null || Array.isArray(value)) return {}
145
146  return Object.fromEntries(Object.entries(value).filter((entry): entry is [string, CacheTouch] => isTouch(entry[1])))
147}
148
149/** The touches with this session's set, keeping the most recent ones. */
150export function withTouch(touches: CacheTouches, id: string, touch: CacheTouch): CacheTouches {
151  const recent = Object.entries({ ...touches, [id]: touch }).sort((a, b) => b[1].at - a[1].at)
152
153  return Object.fromEntries(recent.slice(0, TOUCH_LIMIT))
154}
155
156/**
157 * A session joined with turns behind it that no request dated, a resume in a new process. The touch the store kept
158 * dates its cache; without one the cache is taken as cold of unknown age, since a resume starts after the process
159 * before it ended. A cache already dated stays as it is.
160 */
161export function withRecovered(state: CacheState, found: CacheTouch | undefined, now: number, context: number): CacheState {
162  if (state.touchedAt !== undefined) return state
163  if (found !== undefined) return { ...state, touchedAt: found.at, tokens: found.tokens, isAgeUnknown: false }
164
165  return { ...state, touchedAt: now - UNKNOWN_AGE_MS, tokens: context, isAgeUnknown: true }
166}
167
168/** The context the next prompt would write: the live reading, which is empty until the first reply of a resumed session, else the last one the cache knew. */
169export const contextOf = (reported: number | undefined, state: CacheState): number => (reported !== undefined && reported > 0 ? reported : state.tokens)
170
171/** The cache with the context its next prompt writes: after a compaction, until its reply, the count of the compacted transcript. */
172export const withCounted = (state: CacheState, counted: number | undefined): CacheState =>
173  state.isAfterCompact && counted !== undefined ? { ...state, tokens: counted } : state
174
175/**
176 * A load that finds turns behind it, after a reload or an install, takes the end of the last turn as the last touch:
177 * its last request ended then. A cache whose requests the mod saw keeps its own touch.
178 */
179export const withSeed = (state: CacheState, endedAt: number, context: number): CacheState =>
180  state.touchedAt === undefined ? { ...state, touchedAt: endedAt, tokens: context } : state
181
182/** A keep-warm ping read the cache, so its entry lives a full TTL again. */
183export const withPing = (state: CacheState, at: number): CacheState => ({ ...state, touchedAt: at, isAgeUnknown: false })
184
185const coolingMs = (ttl: CacheTtl): number => Math.min(COOLING_MS, TTL_MS[ttl] / 5)
186
187export function cacheStatus(state: CacheState, keep: KeepWarm | null, ttl: CacheTtl, at: number): CacheStatus {
188  if (state.touchedAt === undefined) return { kind: 'unknown' }
189  const expiry = state.touchedAt + TTL_MS[ttl]
190  const left = expiry - at
191  if (left <= 0) return { kind: 'cold', ms: at - expiry }
192  if (keep !== null && keep.until > at) return { kind: 'kept', ms: keep.until - at }
193
194  return { kind: left <= coolingMs(ttl) ? 'cooling' : 'warm', ms: left }
195}
196
197/** <1m, 42m, 3h 5m. */
198export function span(ms: number): string {
199  const minutes = Math.floor(ms / MINUTE_MS)
200  if (minutes < 1) return '<1m'
201  if (minutes < 60) return `${minutes}m`
202
203  return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
204}
205
206/** The cache row of the Session section: the state in its color (`warm · 42m left`) and the quiet details (`1h TTL`). */
207export type CacheParts = { state: string; detail: string }
208
209export function cacheParts(status: CacheStatus, state: CacheState, keep: KeepWarm | null, ttl: CacheTtl): CacheParts {
210  const restarts = state.restarts === 0 ? '' : ` · ${state.restarts} re-cache${state.restarts === 1 ? '' : 's'} (${tokens(state.restartTokens)})`
211  if (status.kind === 'unknown') return { state: '', detail: `${ttl} TTL · after the next reply${restarts}` }
212  if (status.kind === 'cold') {
213    const detail = `next prompt re-caches ${tokens(state.tokens)}${restarts}`
214
215    return state.isAgeUnknown === true ? { state: 'probably cold', detail: `resumed · ${detail}` } : { state: `cold for ${span(status.ms)}`, detail }
216  }
217  if (status.kind === 'kept') return { state: `kept warm · ${span(status.ms)} left`, detail: `${keep?.pings ?? 0} ping${keep?.pings === 1 ? '' : 's'}${restarts}` }
218  const left = status.kind === 'cooling' ? `cools in ${span(status.ms)}` : `warm · ${span(status.ms)} left`
219
220  return { state: left, detail: `${ttl} TTL${restarts}` }
221}
222
223/**
224 * Whether the guard holds the prompt: typed at an idle session, not a command, over a cold cache and a big context.
225 * After a compaction the prompt writes only the summary, while the context the guard knows is the one before it.
226 */
227export function shouldHold(submission: Submission, gate: HoldGate): boolean {
228  if (submission.origin.kind !== 'composer' || submission.turnId !== undefined) return false
229  if (submission.command !== undefined || submission.isMeta === true || submission.text.trim() === '') return false
230  if (gate.isAfterCompact) return false
231
232  return gate.status.kind === 'cold' && gate.tokens >= gate.minTokens
233}
234
235/** True when the person sent the held prompt again: the engine puts a held prompt back in the box. */
236export const isSameMessage = (text: string, held: string): boolean => text.trim() === held.trim()
237
238/** What the transcript shows where the held prompt would have entered; the engine puts the prompt back in the box. */
239export const holdText = (hold: CacheHold): string => {
240  const expired = hold.isAgeUnknown === true ? 'The session was resumed, so its prompt cache has probably expired' : `The prompt cache expired ${span(hold.coldMs)} ago`
241
242  return `session-info: held. ${expired}, and this prompt would write ${tokens(hold.tokens)} tokens to it again. Press Enter to send it, or choose Compact or New session.`
243}
244
245/** The band's title: the cache expired, or probably did when the session was resumed with no touch on record. */
246export const holdTitle = (hold: CacheHold): string => (hold.isAgeUnknown === true ? 'the prompt cache has probably expired' : 'the prompt cache expired')
247
248/** The band's right side: how long ago the cache expired, or that the session was resumed. */
249export const holdAge = (hold: CacheHold): string => (hold.isAgeUnknown === true ? 'resumed' : `${span(hold.coldMs)} ago`)
250
251/** Whether keep warm pings now: it runs, the cache is known and cooling, and it is not cold yet. */
252export function isPingDue(state: CacheState, keep: KeepWarm | null, ttl: CacheTtl, at: number): boolean {
253  if (keep === null || keep.until <= at || state.touchedAt === undefined) return false
254  const left = state.touchedAt + TTL_MS[ttl] - at
255
256  return left > 0 && left <= coolingMs(ttl)
257}
258
259/** A ping that wrote more than a tenth of what it read did not find the cache: pinging on would only pay for writes. */
260export function pingVerdict(usage: CacheUsage | undefined): PingVerdict {
261  if (usage === undefined) return 'none'
262
263  return usage.cache_creation_input_tokens > PING_MISS_SHARE * Math.max(1, usage.cache_read_input_tokens) ? 'miss' : 'hit'
264}
265
266/** How often, and for how long at most, the move reads the session id after a /clear. */
267export const SWITCH_POLL_MS = 100
268export const SWITCH_LIMIT_MS = 3_000
269
270/**
271 * Clears the session and leaves the held prompt in the new session's box. The box keeps its draft through a /clear;
272 * the prompt goes back in only when the box is empty after the switch.
273 */
274export async function moveToNewSession(host: Host, text: string): Promise<void> {
275  const before = await host.sessionId()
276  await host.clear()
277  for (let waited = 0; waited < SWITCH_LIMIT_MS; waited += SWITCH_POLL_MS) {
278    if ((await host.sessionId()) !== before) break
279    await host.sleep(SWITCH_POLL_MS)
280  }
281  if ((await host.readBox()).trim() === '') await host.fill(text)
282}
283
hooks/cards.tsx 108 lines
1import type { Color, Elements, RenderChildren } from 'claude-code'
2
3import { ALIGN_GROW } from './title'
4import type { TitleAlign } from './title'
5
6type Widgets = Pick<Elements['terminal'], 'Box' | 'Text'>
7
8/** One headline figure of the tiles row: a bold value, then a dim label. */
9export type Tile = { key: string; value: string; label: string; color?: Color }
10
11/** Below this many columns a frame costs more than it shows, and sections draw bare. */
12const FRAME_MIN_COLUMNS = 44
13/** Rows a frame adds to its section: the top and bottom border. */
14export const FRAME_ROWS = 2
15/** Columns a frame takes from its body: two borders and one cell of padding on each side. */
16export const FRAME_COLUMNS = 4
17const TILE_MIN_COLUMNS = 18
18const TILE_ROWS = 3
19/** Rows the pane's title banner takes: its rule row alone. The blank row below comes from the pane itself. */
20export const BANNER_ROWS = 1
21/** Dashes in each side of the title rule, more than any pane is wide; the box clips them. */
22const RULE_LENGTH = 400
23/** Columns of the side of the rule that does not grow. */
24const RULE_STUB = 2
25
26export const isFramed = (columns: number): boolean => columns >= FRAME_MIN_COLUMNS
27
28/** How wide each tile is and how many rows the tiles take once they wrap to the pane's width. */
29export function tileLayout(count: number, columns: number): { width: number; rows: number } {
30  if (count === 0) return { width: columns, rows: 0 }
31  const perRow = Math.min(count, Math.max(1, Math.floor(columns / TILE_MIN_COLUMNS)))
32
33  return { width: Math.floor(columns / perRow), rows: Math.ceil(count / perRow) * TILE_ROWS }
34}
35
36/** Framed cards and KPI tiles drawn with the surface's own `Box` and `Text`; the frame lights under the pointer. */
37export function widgets({ Box, Text }: Widgets, isTerminal = true) {
38  const card = (key: string, isOpen: boolean, children: RenderChildren) => (
39    <Box
40      key={`card:${key}`}
41      flexDirection="column"
42      borderStyle="round"
43      borderColor="subtle"
44      borderDimColor={!isOpen}
45      paddingX={1}
46      {...(isTerminal ? {} : { marginBottom: 1, paddingY: 1 })}
47      hover={{ borderColor: 'claude', borderDimColor: false }}
48    >
49      {children}
50    </Box>
51  )
52
53  /** Cells mean nothing outside a terminal: there the tiles take half the row each and wrap by share. */
54  const tiles = (data: readonly Tile[], columns: number) => {
55    const { width } = tileLayout(data.length, columns)
56
57    return (
58      <Box
59        flexDirection="row"
60        flexWrap="wrap"
61        justifyContent={isTerminal ? 'flex-start' : 'space-between'}
62        {...(isTerminal ? {} : { marginBottom: 1, rowGap: 1 })}
63      >
64        {data.map(tile => (
65          <Box
66            key={`tile:${tile.key}`}
67            width={isTerminal ? width : '49%'}
68            // bodyColumns is a little narrower than the row: the width sets the wrap and the grow takes up what is left.
69            {...(isTerminal ? { flexGrow: 1 } : {})}
70            flexDirection="row"
71            borderStyle="round"
72            borderColor="subtle"
73            paddingX={1}
74            hover={{ borderColor: 'claude' }}
75          >
76            <Text bold color={tile.color}>{tile.value}</Text>
77            <Text dimColor wrap="truncate-end">{` ${tile.label}`}</Text>
78          </Box>
79        ))}
80      </Box>
81    )
82  }
83
84  /** One side of the title rule: a row of dashes clipped to the width the box gets, which is the rest of the row when it grows and RULE_STUB columns when it does not. */
85  const rule = (key: string, color: string, isGrowing: boolean) => (
86    <Box key={key} height={1} overflow="hidden" {...(isGrowing ? { flexGrow: 1 } : { width: RULE_STUB, flexShrink: 0 })}>
87      <Text color={color || 'subtle'}>{'─'.repeat(RULE_LENGTH)}</Text>
88    </Box>
89  )
90
91  /** The pane's custom title on one row between two rules, no margin, the title bold in the title color; align picks the side that grows. */
92  const banner = (title: string, color: string, align: TitleAlign) => {
93    const [isLeftGrowing, isRightGrowing] = ALIGN_GROW[align]
94
95    return (
96      <Box key="pane-title" flexDirection="row">
97        {rule('pane-title:left', color, isLeftGrowing)}
98        <Box key="pane-title:text" flexShrink={0}>
99          <Text bold {...(color === '' ? {} : { color })}>{` ${title} `}</Text>
100        </Box>
101        {rule('pane-title:right', color, isRightGrowing)}
102      </Box>
103    )
104  }
105
106  return { card, tiles, banner }
107}
108
hooks/client.ts 65 lines
1import type { Host } from './host'
2import { launch, lookupArgv, onPath, platformOf, splitCommand, succeeds } from './viewer'
3import type { Platform } from './viewer'
4
5export { splitCommand }
6
7/** Terminal emulators tried in order on Linux, each with the arguments that come before the command it runs. */
8const TERMINALS: readonly (readonly string[])[] = [
9  ['x-terminal-emulator', '-e'],
10  ['gnome-terminal', '--'],
11  ['konsole', '-e'],
12  ['xfce4-terminal', '-x'],
13  ['kitty'],
14  ['alacritty', '-e'],
15  ['wezterm', 'start', '--'],
16  ['foot'],
17  ['xterm', '-e'],
18]
19
20/** Runs the command from the folder in its first argument, as not every terminal starts in its own working directory. */
21const IN_FOLDER = ['sh', '-c', 'cd "$1" && shift && exec "$@"', 'sh']
22
23const shellQuote = (text: string): string => `'${text.replace(/'/g, `'\\''`)}'`
24
25const appleString = (text: string): string => `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
26
27/**
28 * The argv that opens the client in a new terminal window, in the repository's root.
29 * Windows: `start` opens the default terminal, Windows Terminal on Windows 11; its quoted title comes first.
30 * macOS: Terminal.app through AppleScript. Linux: the first terminal emulator found, given by the caller, with `sh` changing to the root.
31 */
32export function clientArgv(platform: Platform, root: string, command: readonly string[], terminal?: readonly string[]): string[] | undefined {
33  if (platform === 'windows') return ['cmd', '/c', 'start', 'Git client', '/D', root.replace(/\//g, '\\'), ...command]
34  if (platform === 'mac') {
35    const script = `cd ${shellQuote(root)} && ${command.map(shellQuote).join(' ')}`
36
37    return ['osascript', '-e', `tell application "Terminal" to do script ${appleString(script)}`, '-e', 'tell application "Terminal" to activate']
38  }
39
40  return terminal === undefined ? undefined : [...terminal, ...IN_FOLDER, root, ...command]
41}
42
43/** The first terminal emulator of `TERMINALS` on the PATH, with its arguments; undefined when there is none. */
44export async function linuxTerminal(host: Host): Promise<readonly string[] | undefined> {
45  for (const terminal of TERMINALS) if (await succeeds(host, lookupArgv('linux', terminal[0] ?? ''))) return terminal
46
47  return undefined
48}
49
50/** Opens the configured Git client in a new terminal window; a toast says why when it cannot. */
51export async function openClient(host: Host, root: string, line: string): Promise<void> {
52  const command = splitCommand(line)
53  const program = command[0]
54  if (program === undefined) return
55
56  const isFound = /[\\/]/.test(program) ? await host.exists(program) : await onPath(host, program)
57  if (!isFound) return host.toast(`session-info: ${program} is not on the PATH. Set the Git client in /config.`)
58
59  const platform = await platformOf(host)
60  const terminal = platform === 'linux' ? await linuxTerminal(host) : undefined
61  const argv = clientArgv(platform, root, command, terminal)
62  if (argv === undefined) return host.toast('session-info: no terminal emulator found to open the Git client.')
63  launch(host, argv, platform === 'linux' ? root : undefined)
64}
65
hooks/detail.ts 28 lines
1import type { Detail } from '../types'
2
3/** The most characters the detail view keeps of one text; a longer one is cut with a mark. */
4export const DETAIL_LIMIT = 4_000
5
6const CUT = '\n… (cut)'
7
8/** The detail view of a text a row cut short: the title says what it is, the text is whole up to DETAIL_LIMIT. */
9export function detailOf(title: string, text: string): Detail {
10  const whole = text.trim()
11
12  return { title, text: whole.length > DETAIL_LIMIT ? `${whole.slice(0, DETAIL_LIMIT)}${CUT}` : whole }
13}
14
15const ELLIPSIS = '…'
16
17/** The text cut to `room` cells with a trailing `…` when it is longer, else as it is; a row's box clips by itself and leaves no mark. */
18export function clip(text: string, room: number): string {
19  const chars = Array.from(text)
20  if (room < 1 || chars.length <= room) return text
21
22  return `${chars.slice(0, room - 1).join('')}${ELLIPSIS}`
23}
24
25/** Joins the parts of a detail text, one per line, and leaves out an empty part. */
26export const detailLines = (parts: readonly (string | undefined)[]): string =>
27  parts.filter((part): part is string => part !== undefined && part.trim() !== '').join('\n')
28
hooks/context.ts 100 lines
1import type { ContextReading, ContextSlice } from '../types'
2
3import { tokens } from './session'
4
5/** /context gives several rows the same grey, so each used row takes its own color, in order. */
6const PALETTE = ['#7aa2f7', '#7dcfff', '#bb9af7', '#9ece6a', '#e0af68', '#f7768e', '#73daca', '#ff9e64', '#c0caf5']
7/** The row that grows takes the accent color. */
8const MESSAGES = 'claude'
9const EMPTY = 'subtle'
10
11export const GLYPH = { used: '█', free: '─', buffer: '░' } as const
12
13/** Cells between two legend entries; the row Box draws them as its gap. */
14export const LEGEND_GAP = 3
15
16export const SWATCH = { used: '■', free: '─', buffer: '░' } as const
17
18type Category = { name: string; tokens: number; kind: string }
19
20/**
21 * The breakdown `$.session.usage({ breakdown: 'summary' })` answers, as the bar draws it: the used rows in
22 * /context's order, then the free space and the compaction buffer. Deferred tool schemas sit outside the window.
23 */
24export function toReading(breakdown: {
25  categories: readonly Category[]
26  totalTokens: number
27  rawMaxTokens: number
28  autoCompactThreshold?: number
29  isAutoCompactEnabled: boolean
30}): ContextReading | null {
31  if (!(breakdown.rawMaxTokens > 0)) return null
32  const rank = { used: 0, free: 1, buffer: 2 } as const
33  const slices = breakdown.categories
34    .filter((c): c is Category & { kind: ContextSlice['kind'] } => c.tokens > 0 && c.kind in rank)
35    .map(c => ({ name: c.name.toLowerCase(), tokens: c.tokens, kind: c.kind, color: EMPTY }))
36    .sort((a, b) => rank[a.kind] - rank[b.kind])
37  let next = 0
38  for (const slice of slices)
39    if (slice.kind === 'used') slice.color = slice.name === 'messages' ? MESSAGES : (PALETTE[next++ % PALETTE.length] ?? EMPTY)
40
41  return {
42    slices,
43    total: breakdown.totalTokens,
44    window: breakdown.rawMaxTokens,
45    compactsAt: breakdown.isAutoCompactEnabled ? breakdown.autoCompactThreshold : undefined,
46  }
47}
48
49/** Each slice's share of `width` cells; a used slice keeps at least one, and free space absorbs the rounding. */
50export function cellWidths(reading: ContextReading, width: number): number[] {
51  const { slices, window } = reading
52  const sizes = slices.map(s => Math.max(s.kind === 'used' ? 1 : 0, Math.round((s.tokens / window) * width)))
53  let diff = width - sizes.reduce((sum, n) => sum + n, 0)
54  const isUsed = (i: number) => slices[i]?.kind === 'used'
55  const order = slices.map((_, i) => i).sort((a, b) => Number(isUsed(a)) - Number(isUsed(b)) || (sizes[b] ?? 0) - (sizes[a] ?? 0))
56  for (const i of order) {
57    if (diff === 0) break
58    const size = Math.max(isUsed(i) ? 1 : 0, (sizes[i] ?? 0) + diff)
59    diff -= size - (sizes[i] ?? 0)
60    sizes[i] = size
61  }
62
63  return sizes
64}
65
66/** `2.1%`, `23%`, `<0.1%`. */
67export function share(count: number, window: number): string {
68  const percent = (count / window) * 100
69  if (percent > 0 && percent < 0.1) return '<0.1%'
70
71  return `${percent >= 10 ? Math.round(percent) : +percent.toFixed(1)}%`
72}
73
74/** One legend entry's text after its swatch: `skills 9.9k 1%`; free space and the buffer carry no share. */
75export const legendText = (slice: ContextSlice, window: number): string =>
76  `${slice.name} ${tokens(slice.tokens)}${slice.kind === 'used' ? ` ${share(slice.tokens, window)}` : ''}`
77
78/** The legend packed into lines no wider than `width`, each entry its swatch and text. */
79export function legendLines(reading: ContextReading, width: number): ContextSlice[][] {
80  const lines: ContextSlice[][] = []
81  let used = 0
82  for (const slice of reading.slices) {
83    const size = 2 + legendText(slice, reading.window).length
84    const line = lines.at(-1)
85    if (line === undefined || (line.length > 0 && used + LEGEND_GAP + size > width)) {
86      lines.push([slice])
87      used = size
88    } else {
89      line.push(slice)
90      used += LEGEND_GAP + size
91    }
92  }
93
94  return lines
95}
96
97/** `273k / 1.0M · compacts at 967k`: the live count, and where auto-compaction runs when it is on. */
98export const contextText = (used: number, window: number, compactsAt: number | undefined, counts: string): string =>
99  `${tokens(used)} / ${tokens(window)}${compactsAt ? ` · compacts at ${tokens(compactsAt)}` : ''}${counts}`
100
hooks/checks.ts 227 lines
1import type { CheckKind, CheckRun, Checks, CheckStatus } from '../types'
2
3import type { Host } from './host'
4import { buildErrorCount, buildErrors, clean, failedTests, fullOutputPath, tailLines, testCounts, vitestReport, vitestReportPath } from './parse'
5import type { TestCounts } from './parse'
6import { duration } from './session'
7
8export const NO_CHECKS: Checks = { build: null, test: null }
9
10export type Patterns = { build?: RegExp; test?: RegExp }
11
12/** A finished shell call, as `tool.call` resolved it; `taskId` names the background task of a command still running. */
13export type ShellRun = {
14  command: string
15  text: string
16  isError: boolean
17  isAgent: boolean
18  taskId?: string
19  persistedPath?: string
20}
21
22const MAX_ERRORS = 3
23const MAX_FAILURES = 5
24export const MAX_READ = 1_000_000
25
26// Each segment of a shell command is matched against these, so the lists stay anchored and free of nested repeats.
27const TEST = [
28  /^dotnet\s+test(?=\s|$)/,
29  /^dotnet\s+run\s.*\btests?\b/i,
30  /^(?:npm|pnpm|yarn|bun)\s+(?:run(?:-script)?\s+)?test(?::\S+)?(?=\s|$)/,
31  /^npm\s+t(?=\s|$)/,
32  /^(?:jest|vitest|mocha|ava|cypress\s+run|gotestsum|ctest)(?=\s|$)/,
33  /^playwright\s+test(?=\s|$)/,
34  /^node\s+(?:\S+\s+)*--test(?=\s|$)/,
35  /^deno\s+test(?=\s|$)/,
36  /^claude\s+plugin\s+test(?=\s|$)/,
37  /^(?:turbo|nx)\s+(?:run\s+)?test(?::\S+)?(?=\s|$)/,
38  /^cargo\s+(?:test|nextest)(?=\s|$)/,
39  /^go\s+test(?=\s|$)/,
40  /^(?:(?:py|python3?)\s+-m\s+)?(?:pytest|unittest)(?=\s|$)/,
41  /^(?:tox|nox)(?=\s|$)/,
42  /^(?:\.\/)?(?:gradlew?|mvnw?)(?:\.bat|\.cmd)?\s.*\b(?:test|check|verify)\b/,
43  /^(?:rspec|rake\s+(?:test|spec)|(?:bin\/)?rails\s+test)(?=\s|$)/,
44  /^(?:\S*\/)?(?:phpunit|pest)(?=\s|$)/,
45  /^php\s+artisan\s+test(?=\s|$)/,
46  /^(?:mix|swift|flutter|dart|stack|cabal)\s+test(?=\s|$)/,
47  /^zig\s+(?:build\s+)?test(?=\s|$)/,
48  /^make\s+(?:test|check)(?=\s|$)/,
49]
50
51const BUILD = [
52  /^dotnet\s+(?:build|publish|pack|msbuild)(?=\s|$)/,
53  /^msbuild(?:\.exe)?(?=\s|$)/i,
54  /^(?:npm|pnpm|yarn|bun)\s+(?:run(?:-script)?\s+)?(?:build|compile|typecheck|type-check)(?::\S+)?(?=\s|$)/,
55  /^bun\s+build(?=\s|$)/,
56  /^(?:tsc|vue-tsc|tsgo|tsup|esbuild|webpack|rollup)(?=\s|$)/,
57  /^(?:vite|next|nuxt|astro|ng|parcel|turbo|nx|flutter)\s+(?:run\s+)?build(?::\S+)?(?=\s|$)/,
58  /^claude\s+plugin\s+validate(?=\s|$)/,
59  /^cargo\s+(?:build|check|clippy)(?=\s|$)/,
60  /^go\s+(?:build|vet)(?=\s|$)/,
61  /^(?:\.\/)?(?:gradlew?|mvnw?)(?:\.bat|\.cmd)?\s.*\b(?:build|assemble|package|compile|install)\b/,
62  /^(?:swift|zig|stack|cabal)\s+build(?=\s|$)/,
63  /^mix\s+compile(?=\s|$)/,
64  /^xcodebuild(?=\s|$)/,
65  /^(?:cmake\s+--build|ninja)(?=\s|$)/,
66  /^make(?:\s+-[\w-]+)*(?:\s+(?:all|build))?\s*$/,
67]
68
69const IGNORED = /(?:^|\s)(?:--list-tests|--help|--version)(?=\s|$)/
70
71/** Runners in front of the real tool, with the options they take before it: `npx -y -p typescript tsc` runs `tsc`. */
72const PREFIX =
73  /^(?:rtk(?:\s+proxy)?|time|env|&|(?:npx|bunx|uvx|(?:pnpm|yarn)\s+(?:exec|dlx))(?:\s+(?:--package(?:=|\s+)\S+|-p\s+\S+|-[\w-]+))*|(?:uv|poetry|pipenv|hatch)\s+run|bundle\s+exec|[A-Za-z_]\w*=\S*)\s+/
74
75/** A segment without the wrappers that run the real tool: `rtk`, `npx`, env assignments. */
76function unwrap(segment: string): string {
77  let current = segment.trim().replace(/^[({]\s*/, '')
78  for (let next = current.replace(PREFIX, ''); next !== current; next = current.replace(PREFIX, '')) current = next
79
80  return current
81}
82
83/** A user pattern from the settings; an invalid one is ignored. */
84export function toPattern(source: unknown): RegExp | undefined {
85  if (typeof source !== 'string' || source.trim() === '') return undefined
86  try {
87    return new RegExp(source, 'i')
88  } catch {
89    return undefined
90  }
91}
92
93/** A shell command's segments, each without its wrappers: `cd app && rtk git push` gives `cd app` and `git push`. */
94export const segments = (command: string): string[] => command.split(/\s*(?:&&|\|\||[;|\n])\s*/).map(unwrap)
95
96/** Which checks a command runs, segment by segment: `cd app && npm test` is a test run. */
97export function classify(command: string, custom: Patterns = {}): CheckKind[] {
98  const kinds = new Set<CheckKind>()
99  for (const segment of segments(command)) {
100    if (segment === '' || IGNORED.test(segment)) continue
101    if (custom.test?.test(segment) || TEST.some(pattern => pattern.test(segment))) kinds.add('test')
102    else if (custom.build?.test(segment) || BUILD.some(pattern => pattern.test(segment))) kinds.add('build')
103  }
104
105  return [...kinds]
106}
107
108/** The first value each count has across the readings, in order. */
109const mergeCounts = (...readings: (TestCounts | undefined)[]): TestCounts => ({
110  passed: readings.find(r => r?.passed !== undefined)?.passed,
111  failed: readings.find(r => r?.failed !== undefined)?.failed,
112  skipped: readings.find(r => r?.skipped !== undefined)?.skipped,
113  total: readings.find(r => r?.total !== undefined)?.total,
114})
115
116async function readClean(host: Host, path: string | undefined): Promise<string | undefined> {
117  if (path === undefined) return undefined
118  const text = await host.readFile(path).catch(() => undefined)
119
120  return text === undefined ? undefined : clean(text.slice(-MAX_READ))
121}
122
123type Base = Pick<CheckRun, 'command' | 'at' | 'isAgent'>
124
125function buildRun(base: Base, text: string, whole: string | undefined, isError: boolean): CheckRun {
126  const errors = buildErrors(whole ?? text)
127  const found = errors.length > 0 ? errors : buildErrors(text)
128  const errorCount = buildErrorCount(text) ?? (whole === undefined ? undefined : buildErrorCount(whole)) ?? (found.length || undefined)
129  const isFailed = isError || (errorCount ?? 0) > 0
130  const shown = found.length > 0 ? found : tailLines(text, MAX_ERRORS)
131
132  return { ...base, kind: 'build', status: isFailed ? 'failed' : 'passed', errors: isFailed ? shown : [], errorCount, failures: [] }
133}
134
135function testRun(base: Base, text: string, whole: string | undefined, report: ReturnType<typeof vitestReport>, isError: boolean): CheckRun {
136  const counts = mergeCounts(testCounts(text), whole === undefined ? undefined : testCounts(whole), report?.counts)
137  const listed = failedTests(text)
138  const failures = listed.length > 0 ? listed : [whole === undefined ? [] : failedTests(whole), report?.failures ?? []].find(names => names.length > 0) ?? []
139  const isFailed = isError || (counts.failed ?? 0) > 0 || failures.length > 0
140  const isExplained = failures.length > 0 || (counts.failed ?? 0) > 0
141  const reason = buildErrors(whole ?? text)
142  const errors = isFailed && !isExplained ? (reason.length > 0 ? reason : tailLines(text, MAX_ERRORS)) : []
143
144  return { ...base, kind: 'test', status: isFailed ? 'failed' : 'passed', errors, ...counts, failures }
145}
146
147/** One record per check the command ran, read from its output and any whole copy of it on disk. */
148export async function checkRuns(host: Host, kinds: readonly CheckKind[], shell: ShellRun, at: number): Promise<CheckRun[]> {
149  const base: Base = { command: (shell.command.split('\n')[0] ?? '').trim(), at, isAgent: shell.isAgent }
150  if (shell.taskId !== undefined) return kinds.map(kind => ({ ...base, kind, status: 'running', taskId: shell.taskId, errors: [], failures: [] }))
151
152  const text = clean(shell.text)
153  const whole = await readClean(host, shell.persistedPath ?? fullOutputPath(text, (await host.env()).home))
154  const reportPath = kinds.includes('test') ? vitestReportPath(text) : undefined
155  const report = reportPath === undefined ? undefined : vitestReport((await host.readFile(reportPath).catch(() => undefined)) ?? '')
156
157  return kinds.map(kind => (kind === 'build' ? buildRun(base, text, whole, shell.isError) : testRun(base, text, whole, report, shell.isError)))
158}
159
160export const CHECK_STATUS = {
161  passed: { glyph: '✓', color: 'success' },
162  failed: { glyph: '✖', color: 'error' },
163  running: { glyph: '⟳', color: 'suggestion' },
164} as const satisfies Record<CheckStatus, { glyph: string; color: string }>
165
166/** One check as the pane draws it: a head row, then the error lines or failed test names. */
167export type CheckView = { run: CheckRun; label: string; result: string; details: string[] }
168
169const plural = (count: number, word: string): string => `${count} ${word}${count === 1 ? '' : 's'}`
170
171function resultText(run: CheckRun): string {
172  if (run.status === 'running') return 'running in background'
173  if (run.kind === 'build') return run.status === 'failed' && run.errorCount ? plural(run.errorCount, 'error') : run.status
174  if (run.status === 'passed') return run.passed === undefined ? 'passed' : `${run.passed} passed${run.skipped ? ` · ${run.skipped} skipped` : ''}`
175  if (run.failed === undefined) return 'failed'
176  const total = run.total ?? (run.passed === undefined ? undefined : run.failed + run.passed + (run.skipped ?? 0))
177
178  return total === undefined ? `${run.failed} failed` : `${run.failed} failed / ${total}`
179}
180
181function detailLines(run: CheckRun): string[] {
182  const items = run.failures.length > 0 ? run.failures : run.errors
183  const room = run.failures.length > 0 ? MAX_FAILURES : MAX_ERRORS
184  const shown = items.slice(0, room)
185
186  return items.length > room ? [...shown, `… ${items.length - room} more`] : shown
187}
188
189export function checkViews(checks: Checks): CheckView[] {
190  return [checks.build, checks.test]
191    .filter((run): run is CheckRun => run !== null)
192    .map(run => ({ run, label: run.kind === 'build' ? 'Build' : 'Tests', result: resultText(run), details: detailLines(run) }))
193}
194
195/** The head row's right side: `agent · 2m 5s ago`. */
196export const checkWhen = (run: CheckRun, now: number): string =>
197  `${run.isAgent ? 'agent · ' : ''}${duration(now - run.at)} ago`
198
199/** The section header's right side: `✓ build  ✖ tests`. */
200export function checkSummary(checks: Checks): string {
201  return checkViews(checks).map(({ run }) => `${CHECK_STATUS[run.status].glyph} ${run.kind === 'build' ? 'build' : 'tests'}`).join('  ')
202}
203
204/** Failed test names the fix prompt lists before the rest fold into `and N more`. */
205const FIX_ROOM = 3
206
207function testFix(run: CheckRun): string {
208  const count = run.failed ?? run.failures.length
209  if (count === 0) return 'Fix the failed test run'
210  const names = run.failures.slice(0, FIX_ROOM).join(', ')
211  const more = run.failures.length > FIX_ROOM ? ` and ${run.failures.length - FIX_ROOM} more` : ''
212
213  return `Fix the ${plural(count, 'failed test')}${names === '' ? '' : `: ${names}${more}`}`
214}
215
216/** The prompt that asks for a fix of the failed build, else of the failed tests, which a failed build often explains; the key names the run. */
217export function fixSuggestion(checks: Checks): { key: string; text: string } | undefined {
218  const run = [checks.build, checks.test].find(one => one?.status === 'failed')
219  if (!run) return undefined
220  const text = run.kind === 'test' ? testFix(run) : run.errorCount ? `Fix the ${plural(run.errorCount, 'build error')}` : 'Fix the failed build'
221
222  return { key: `${run.kind}@${run.at}`, text }
223}
224
225export const checkRowCount = (views: readonly CheckView[]): number =>
226  views.reduce((rows, view) => rows + 2 + view.details.length, 0)
227