Watches your Modal apps from the CLI, in projects that use Modal: running apps and containers on the status line, a toast when one has been up too long…

Claude Code mods (function-hook plugins) I find helpful. Each folder is one plugin.
Requires a Claude Code build with function-hook plugins (2.1.289 or newer). machine-guard reads macOS tools (sysctl, vm_stat, ioreg, ps).
git clone https://github.com/joeldg/claude-mods ~/Projects/claude-mods
A pane of your project's running dev servers, so you don't have to ask Claude to restart them — and a tool so Claude doesn't have to run lsof to find out what's listening.
/servers opens the Servers pane:package.json dev/start/serve/preview scripts (run with your lockfile's package manager), .claude/launch.json and Procfileclaude CLI, which also listen on localhost from the project's folder) are never listed as servers nor counted as other listeners.~/.claude/dev-servers/<project>/.dev_servers tool: this project's running servers (name, port, pid, uptime, and the log when it was started from the pane), the start commands that aren't running, and with all: true every other listener on the machine (port, process), ending with how many Claude Code sessions it left out, e.g. (7 Claude Code sessions not listed), so nothing is hidden silently. Its description tells Claude to use it instead of lsof/netstat/ps. It never starts or stops anything.Port 4000 is held by node (pid 123, up 2h, in /Users/me/other).servers: :4000 :5173.netstat -anv -p tcp (macOS) or ss -ltnp (Linux), never a bare lsof; ps and lsof -d cwd run once per new pid, one pid at a time. One open session scans per interval (15s by default) and writes ~/.claude/dev-servers/scan-cache.json for the others; a slow scan doubles the interval, up to 5 minutes.Puts files you just downloaded into your prompt with one click.
~/Downloads (top level). When a new file arrives (PDF, Markdown, images, 3MF/STL/OBJ, zip, video…), a band appears above the prompt: New in Downloads: paper.pdf, model-b.3mf · 2m ago [Attach] [Dismiss].@"/Users/you/Downloads/paper.pdf" mentions in your prompt. Dismiss hides those files./downloads lists the 10 newest files, numbered. /downloads attach 1 3 (or 2-4) adds those, and /downloads clear dismisses everything new.Settings: folder (~/Downloads), extensions, pollSeconds (5), maxAgeMinutes (120).
Sets effort per message, so you don't have to switch it by hand.
~/.claude/usage-meter/summary.json, at most every 30 s) and, once pct reaches budgetCapAt (80%), caps every turn at budgetCapEffort (high), deep asks included, so you stop hitting the 5-hour wall. A turn already at or below the cap is left alone; lowering over a warm cache waits like any other lowering and never happens mid-turn. A missing or stale summary (over 10 minutes old), or one with no percentage yet (no fresh API reading and no limit learned), is no budget information. The debug log gets one line when the cap engages and one when it releases. budgetCapAt: 0 turns it off.subagentEffort (empty by default) to run every subagent request at that effort; the budget cap applies to them too (the lower of the two). Each subagent turn's effort is decided at its first request and kept for the turn.avoidModel (a regex such as fable) to send those requests to fallbackModel instead, subagents included./route shows the last decision, the session's counts, the budget state (percent used, the cap, whether it is engaged) and the subagent effort. /route off and /route on toggle it all; /route deep and /route routine force the next turn.effort: low (routine); while the budget cap lowers it: effort: high (budget 84%).Settings: routineEffort (low), deepEffort (max), routinePattern, deepPattern, avoidModel, fallbackModel (opus), stickyTurns (2), freeSwitchTokens (30000), cacheTtlMinutes (60), budgetCapAt (80; 0 = off), budgetCapEffort (high), subagentEffort (empty = the session's own).
A Jobs pane for long-running work: training runs, downloads, extractions — and three tools so Claude follows them instead of polling.
nohup … > log & launches by itself./watch <log> [label] adds any other log file./ and /Volumes/* (the NAS).jobs: 2 running · 1 stalled. A timer Claude sets for itself — sleep 600 && echo done, a loop of sleeps, or a task described as a wait, timer, pause or delay that only polls and reports with read-only programs (rg, tail, pgrep…) — is still listed by jobs_list and shown as a dim timer row, but never toasts, never counts in the status line, does not open the pane, is judged by its exit marker alone (no ps), and leaves a minute after it ends. Anything that runs a real program is a job, however it is described./jobs opens the pane, /unwatch <label|id|done|all> removes jobs.jobs_list (every watched job's state, pid, progress, ETA, last-output age, exit code and log path), jobs_watch ({ pid?, log?, name?, quietMinutes? }: follow a process or log started elsewhere; it never starts commands) and jobs_unwatch ({ name }). The first message of each conversation says jobs are watched and names them, so Claude stops writing until … sleep loops and running ps. They need no permission prompt: they only read the mod's own list.tail, checks processes with ps (one listing, or a per-pid lookup when only pids are watched), and runs df. A probe that times out or takes over 2 s is retried at a doubling interval, up to 5 minutes, until it is fast again. The debug log names a probe's pace only once it has held for two probes in a row, and at most once per five minutes per probe, so a pace that flips with the Mac's load leaves no trail.Settings (in /config): stall minutes (10), refresh seconds (10), how long finished jobs stay (120 min; a timer leaves after a minute), auto-open (on), which disks to show.
Memory, swap and GPU on the status line, a machine_status tool for Claude, and a guard that refuses heavy local jobs when the Mac can't take them.
RAM tight 12% free · swap 7.9/8G · top python 31G · GPU 87%, and CPU 4/16 cores whenever macOS has parked the performance cores. "Free" is unused memory (vm_stat's free + inactive + speculative pages): what a new job can take without pushing anyone out. macOS's own "memory free percentage" counts active pages too, which is how a Mac can be "55% free" with the swap nearly full.sysctl calls and vm_stat), every 15 s by default; the GPU (ioreg) on every third sample, never right after a slow one. One session samples and writes ~/.claude/machine-guard/sample.json (with a lock.json while it probes); every other session shows the same numbers instead of probing too. When probes are slow or time out (10–40 s while the Mac swaps) on two samples in a row, the interval doubles, and doubles again with each further slow sample, up to 2 min; a single slow sample is a blip and changes nothing. The configured pace returns once two samples in a row are fast again. The other sessions follow the sampler's pace, so a blip stays quiet in every session.kern.sched_recommended_cores, the bitmask of CPUs the scheduler may use. When macOS's performance controller parks the performance cores (after a thermal event, or stuck until a sleep/wake or reboot), the status line shows CPU 4/16 cores, machine_status and /guard report it with the parked count, you get one toast once at least half the cores have been parked for a minute, or any parking has lasted five minutes (masks blip for seconds under GPU load), and one when they come back, and Claude gets a note when it starts heavy work so it keeps worker counts small. The guard never blocks on it.ps, the slowest probe) is taken only on demand (/guard, machine_status) or when a sample shows pressure, at most once a minute; "biggest" means the apps from a table taken in the last 5 minutes./busy.When memory is only tight (under 20% free, or kernel level 2), the job runs and Claude gets a note to start one heavy job at a time.
machine_status is a tool Claude can call (no input, allowed without asking): the sample's age, RAM free, swap, GPU, the pressure level, the biggest apps (or how to get a table), the guard's verdict and its rules. Claude is told to use it instead of ps, top, vm_stat, memory_pressure or project scripts before launching heavy work./busy 3h training a vision model reserves the Mac in every Claude session. /busy off lifts it. The reservation lives in ~/.claude/machine-guard.json, so a training script can write it too: ``bash echo '{"reason":"overnight training","until":'$(( ($(date +%s) + 8*3600) * 1000 ))'}' > ~/.claude/machine-guard.json ``/guard shows what it sees (and takes a process table when one is due). /guard pause 15m lets heavy jobs through in this session; /guard on resumes the guard.modal run, ssh), tests (pytest) and installs are never treated as heavy.overnight_|nightly_run\.sh.Watches how the other mods behave in real use, without changing them. It is listed first in CLAUDE_CODE_PLUGIN_DIRS, so the other mods' hooks run beneath it.
next.trace), with the mod's name, the event and how long it ran. Slow hooks (over 1.5 s) are recorded too. The first failure of each mod in a session raises a toast.rg, grep, pgrep or pkill exiting 1 with nothing on stderr (no match, no such process), are logged as expected (proc-expected, with why), not as failures; an exit of 2 or more, or anything on stderr, still counts. It also records model calls (the only usage the mods cost: /second-opinion, /recall ask) and file writes (folders only, never contents)./mods: a pane with one row per mod: ✓ active, ⚠ failing, ✗ not seen this session, · seen but idle. Each row shows today's counts and last activity, with Details for its recent events. It also says which mods it can't see, if any of them run above it./mods report [24h|7d|30d]: a per-mod report across all sessions, also written to ~/.claude/mods/monitor/report-latest.md for a scheduled review or Claude to read./mods failures [7d]: failures and failed subprocesses only.~/.claude/mods/monitor/<date>/<session>.jsonl, flushed every minute and at session end, with secrets masked and old days removed after 30 days.$.ui.log with wording like "failed" or "could not"): shown in Details and in /mods failures. Three in an hour mark the mod ⚠ and raise one toast. That is how effort-router's per-request hook, which runs inside the response stream where no monitor should sit, reports a failure. It also always sends the request on unchanged./secrets records there) are watched for failures and slow runs, but not counted per run.Settings: alerts (on), slowMs (1500), watchRender (on), watchCommands (on; off stops "mod-monitor" appearing beside other mods' command output), watchAppend (on), retentionDays (30), flushSeconds (60).
Keeps an eye on Modal so idle GPU containers don't burn credits — in the projects that use Modal, with one CLI run per minute for the whole machine.
.py file with import modal / from modal import … (one rg run, 5 s at most), or modal named in pyproject.toml, requirements*.txt, uv.lock or poetry.lock. The answer is remembered per project for a day. Running /modal, or any modal … command in Bash, switches it on for the session; alwaysPoll (off) watches every project.~/.claude/modal-meter/lock.json runs modal app list --json every pollSeconds (60) and writes cache.json; the other open sessions read the cache and refresh their own status line and pane from it. Once one session learns the CLI has no billing report, none tries it again for a day.app list over 2 s or a timeout doubles the interval (up to 10 minutes); a fast answer brings it back.Modal: 1 running (2 containers). Deployed apps with no containers cost nothing, so they stay off it.alertMinutes (30), repeated at most every 30 minutes./modal opens a pane of apps with state, containers and uptime. Stop asks for Confirm, then runs modal app stop. Nothing is stopped any other way.budgetToday where the Modal CLI supports billing report (1.3.3+, Team/Enterprise workspaces). Otherwise /modal says why spend isn't shown.modal or python3 -m modal. It checks PATH first rather than running a command that can only fail, never retries one that isn't there, and stays silent when Modal isn't set up.Does the "merged #219, clean up branches and start #214" round trip for you, and surfaces CI failures with their logs.
gh pr create Claude runs. It polls gh pr view every 60s.PRs: #219 ✓ · #220 CI… · #221 ✗, for every watched PR.gh pr create) or you added with /prs watch, and for any PR whose branch this worktree has checked out. PRs adopted from the repository at start stay on the status line, in /prs and in prs_status, and still get the merge ritual, but their CI results don't toast — so with seven worktree sessions of one repo a result toasts once, where it matters, not seven times. toastAdoptedCi (off) brings back toasts for every watched PR.git fetch --prune, switch to the default branch (only from the PR's own branch) and git pull --ff-only.--force, never other branches.git worktree add, such as Claude Code's .claude/worktrees/<name> sessions) it only fetches: it never switches or pulls there, because the default branch is checked out in the primary worktree and the switch could only fail ('main' is already used by worktree …). When the merged branch is the one the worktree has checked out, the toast says #N merged → this worktree's branch; remove the worktree when you're done (git worktree remove <path>) and the Tab suggestion tells Claude the branch and worktree stay until you remove them. In the primary worktree the ritual is unchanged.gh pr checks and the tail of the failed log attached, so you don't paste it.prs_status (number, title, state, branch, CI, URL, and how old the data is), instead of running gh pr view or gh pr checks itself: no API call, and it refreshes first when the data is older than a poll.Resource not accessible by personal access token), it tells you once with the fix (gh auth login --web, or grant the token "Checks: read"), keeps polling the PRs without their checks so merges are still handled, shows them as #219 CI?, and tries the checks again after 30 minutes or when you run /prs. If gh can't read PRs at all (not logged in), the status line says PRs: gh can't read them and nothing is polled until then. A GitHub rate limit pauses polling for 5 minutes; any other failure doubles the wait up to 10 minutes, back to normal on the next success. Nothing retries every minute forever; the debug log gets one line per change./prs lists watched PRs and asks gh again at once. /prs watch <n|url> and /prs forget <n|all> add and remove them.gh and git, at about one GitHub API call per open PR per minute.Settings:
pollSeconds (60)authRetryMinutes (30): how long before the checks are tried again after gh refused them over auth.attachCiLogs (on)logLines (120)deleteRemoteBranch (off): deletes the branch on GitHub too, only while it still points at the merged commit. GitHub's own "Automatically delete head branches" setting does the same job.toastAdoptedCi (off): toast the CI results of PRs adopted from the repository too, as every PR's used to; with several worktree sessions of one repo, each would toast.It never closes issues; put "Closes #N" in PR bodies for that.
Search everything you've done with coding agents, from Claude or from /recall. It replaces the broken agent-memory plugin.
/remember notes. Routine (scheduled) runs are left out unless you add routines:include to a query.grep and cat are kept but ranked low.search, expand, recap and list, which run without permission prompts. It checks them when you say "like last time" or "what did we decide", and before asking you something you already settled./goal (or the Stop hook's condition), open tasks with a count of the done ones, the questions you asked with the first line of each answer, the files touched, the commits made and PRs opened. After a compaction it goes back into Claude's context as Ledger (this session, before compaction) (about 40 lines at most), so you don't have to say "don't lose track of where we were". /recall ledger prints it any time; /clear starts a fresh one. It is written to ~/.claude/recall/ledger/<session>.json (readable only by you, secrets masked) so a reload keeps it./recall <query> opens a pane of hits grouped by session. Open shows the conversation around a hit, Attach sends it with your next message, and Copy resume command copies claude --resume <id>./recall last [n] recaps your last session in this repo: last asks, last answer, PRs, commits, open tasks and decisions. Send to Claude attaches it./recall ledger prints this session's ledger (above)./recall timeline [7d|30d|90d] [all]/recall decisions|commands|files|prs|commits|issues|urls|tasks|notes [query]/recall ask <question> answers from your history with Haiku 4.5, citing sessions. It costs a little usage and sends the matching excerpts to the model./recall stats, /recall reindex, /recall forget session <id>|project <name>|before <date> (asks you to confirm), /recall help./remember <fact>, /remember list, /remember forget <ref>.Last session here (2d ago): "…" · PR #99 · 3 open tasks [Recap].#214, ABC-12, a file name or a quoted phrase seen in past sessions, a band offers what happened then. Nothing is sent unless you click.OR gives alternatives, "quotes" an exact phrase, and -word excludes. Filters: project:name, kind:decision, since:7d, until:2026-09-30, source:codex, routines:include.~/.claude/recall/index.db, readable only by you, and never goes in a repo. The ledgers beside it are kept the same way.~/.zshrc, ~/.zprofile, ~/.bashrc and `~/.bash_profilehooks/register.tsx 645 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { ModalCache, ModalMeter, ModalProject, ModalShared } from '../types'
5import {
6 activeApps,
7 alertText,
8 cliCandidates,
9 dueAlerts,
10 firstLine,
11 formatDuration,
12 isAuthProblem,
13 isCacheEntry,
14 isDependencyFile,
15 isEnoent,
16 isLock,
17 isMissingModule,
18 isModalCommand,
19 isProjectRecord,
20 isTimeout,
21 kindOf,
22 lacksBilling,
23 namesModal,
24 nextInterval,
25 paneNotice,
26 parseAppList,
27 parseSpend,
28 rowText,
29 statusText,
30 summaryText,
31 trackApps,
32 usd,
33 utcDay,
34 wantsYes,
35} from './meter'
36
37type Engine = EngineInterface
38
39const PANE = 'modal-meter'
40const TITLE = 'Modal'
41const PROBE_TIMEOUT_MS = 30_000
42const LIST_TIMEOUT_MS = 60_000
43const STOP_TIMEOUT_MS = 120_000
44/** The look at the project's Python files (`rg`) gets this long; then its dependency files decide. */
45const DETECT_TIMEOUT_MS = 5_000
46/** A project's answer (uses Modal or not) is kept in the store this long before it is looked at again. */
47const PROJECT_RECHECK_MS = 24 * 60 * 60_000
48/** Spend is asked this often at most (a poll is every minute; spend moves slower). */
49const SPEND_EVERY_MS = 5 * 60_000
50/** After `billing report` failed for a reason other than not existing, wait this long to ask again. */
51const SPEND_RETRY_MS = 60 * 60_000
52/** Once a CLI is known to lack `billing report`, no session tries it again for this long. */
53const BILLING_RECHECK_MS = 24 * 60 * 60_000
54/** Another session's lock is stale once its poll interval and this much (one probe timeout) have passed since it was taken. */
55const LOCK_STALE_MS = LIST_TIMEOUT_MS
56/** Plain output: no ANSI styling from rich (FORCE_COLOR still adds bold, which the parser strips). */
57const PLAIN_ENV = { NO_COLOR: '1', TERM: 'dumb' }
58/** `rg -l` over the project's Python files for a line importing modal, the usual vendored folders skipped. */
59const RG_ARGS = ['-l', '-m1', '--glob', '*.py', '--glob', '!.venv/**', '--glob', '!node_modules/**', '--glob', '!.git/**', '-e', '^\\s*(import|from)\\s+modal\\b']
60/** The dependency files read when `rg` cannot list the project's own. */
61const DEPENDENCY_FILES = ['pyproject.toml', 'requirements.txt', 'uv.lock', 'poetry.lock']
62
63const EMPTY: ModalMeter = { cli: null, problem: null, apps: [], polledAt: null, spendToday: null, spendNote: null }
64/** What is known before any session has polled: nothing, and `billing report` untried. */
65const UNKNOWN: ModalShared = {
66 cli: null,
67 problem: null,
68 apps: [],
69 spendToday: null,
70 spendNote: null,
71 spendAskedAt: null,
72 spendWaitMs: SPEND_EVERY_MS,
73 billingUnsupportedAt: null,
74}
75
76const meter = atom({ plugin: 'modal-meter', key: 'meter' } as const, EMPTY)
77const tracked = atom({ plugin: 'modal-meter', key: 'tracked' } as const, {})
78const confirming = atom({ plugin: 'modal-meter', key: 'confirming' } as const, null)
79const stopping = atom({ plugin: 'modal-meter', key: 'stopping' } as const, null)
80const budgetDay = atom({ plugin: 'modal-meter', key: 'budgetDay' } as const, null)
81const watching = atom({ plugin: 'modal-meter', key: 'watching' } as const, false)
82
83type Config = { command: string; pollMs: number; alertMs: number; budget: number; alwaysPoll: boolean }
84
85/**
86 * Why a poll runs: the timer (`tick`: another session's fresh answer will do, and its live lock
87 * is respected), the person's /modal (`asked`: a fresh answer will do, else poll whoever holds
88 * the lock), or a stop this session made (`changed`: always poll).
89 */
90type Poll = 'tick' | 'asked' | 'changed'
91
92let config: Config = { command: '', pollMs: 60_000, alertMs: 30 * 60_000, budget: 0, alwaysPoll: false }
93let timer: { cancel: () => void } | null = null
94/** The poll interval in force: the option, doubled while Modal answers slowly. */
95let intervalMs = 60_000
96/** The Modal CLI argv that answered `--version` (or another session's, adopted): undefined until tried, null when none did. */
97let cli: string[] | null | undefined
98let inflight: Promise<void> | null = null
99/** The home directory, read once; null when there is none to keep the shared cache under. */
100let home: string | null | undefined
101let sessionId: string | null = null
102/** The cache entry this session last read or wrote: the cache itself when there is no home directory. */
103let memo: ModalCache | null = null
104
105type Ran = { started: boolean; code: number; stdout: string; stderr: string }
106
107async function run($: Engine, argv: readonly string[], timeoutMs: number): Promise<Ran> {
108 try {
109 const out = await $.process.run(argv, { timeoutMs, env: PLAIN_ENV })
110 return { started: true, code: out.exitCode, stdout: out.stdout, stderr: out.stderr }
111 } catch (error) {
112 return { started: false, code: -1, stdout: '', stderr: String(error) }
113 }
114}
115
116/**
117 * Whether `exe` can start: a path is checked as given, a bare name against each `PATH` folder. With no
118 * `PATH` to read it is assumed present, so the probe still runs. Checking first spares a process that
119 * can only fail (`modal` is often not on `PATH` when Modal runs as `python3 -m modal`).
120 */
121async function canStart($: Engine, exe: string): Promise<boolean> {
122 try {
123 if (exe.includes('/')) {
124 return await $.fs.exists(exe)
125 }
126 const folders = ((await $.env.get('PATH')) ?? '').split(':').filter(Boolean)
127 if (folders.length === 0) {
128 return true
129 }
130 for (const folder of folders) {
131 if (await $.fs.exists(`${folder.replace(/\/+$/, '')}/${exe}`)) {
132 return true
133 }
134 }
135 return false
136 } catch {
137 return true
138 }
139}
140
141/** The first candidate that answers `--version`: the option as given, else `modal`, then `python3 -m modal`. */
142async function resolveCli($: Engine): Promise<string[] | null> {
143 for (const argv of cliCandidates(config.command)) {
144 if (!(await canStart($, argv[0] ?? ''))) {
145 continue
146 }
147 const out = await run($, [...argv, '--version'], PROBE_TIMEOUT_MS)
148 if (out.started && out.code === 0 && !isMissingModule(`${out.stderr}\n${out.stdout}`)) {
149 return argv
150 }
151 }
152 return null
153}
154
155/** The CLI another session found, when it can start here too; else this session's own search. */
156async function adoptCli($: Engine, shared: readonly string[] | null): Promise<string[] | null> {
157 if (shared !== null && shared.length > 0 && (await canStart($, shared[0] ?? ''))) {
158 return [...shared]
159 }
160 return resolveCli($)
161}
162
163function notFound(): string {
164 const own = config.command.trim()
165 return own
166 ? `the Modal CLI did not run as \`${own}\` (the modalCommand option)`
167 : 'no Modal CLI found (tried `modal` and `python3 -m modal`); set the modalCommand option to the command you run Modal with'
168}
169
170/** Nothing to show: no status line, no rows, the reason kept for /modal and the pane. */
171async function silence($: Engine, problem: string, label: string | null) {
172 await update($, meter, () => ({ ...EMPTY, cli: label, problem }))
173 $.ui.status(undefined)
174}
175
176async function checkBudget($: Engine, spent: number, now: number) {
177 if (config.budget <= 0 || spent < config.budget) {
178 return
179 }
180 const day = utcDay(now)
181 if ((await read($, budgetDay)) === day) {
182 return
183 }
184 await update($, budgetDay, () => day)
185 $.ui.toast(
186 `Modal spend today is ${usd(spent)}, past your ${usd(config.budget)} daily budget — /modal to see what is running`,
187 { timeoutMs: 15_000 },
188 )
189}
190
191type SpendPart = Pick<ModalShared, 'spendToday' | 'spendNote' | 'spendAskedAt' | 'spendWaitMs' | 'billingUnsupportedAt'>
192
193/** The spend fields of an answer, and nothing else (what `readSpend` keeps or replaces). */
194const spendOf = (shared: ModalShared): SpendPart => ({
195 spendToday: shared.spendToday,
196 spendNote: shared.spendNote,
197 spendAskedAt: shared.spendAskedAt,
198 spendWaitMs: shared.spendWaitMs,
199 billingUnsupportedAt: shared.billingUnsupportedAt,
200})
201
202/**
203 * Today's spend from `modal billing report --for today --json`, where this CLI has it and a read
204 * is due; else `kept` as the last session left it. A CLI without the command is remembered for a
205 * day, for every session.
206 */
207async function readSpend($: Engine, argv: readonly string[], now: number, isForced: boolean, kept: SpendPart): Promise<SpendPart> {
208 if (kept.billingUnsupportedAt !== null && now - kept.billingUnsupportedAt < BILLING_RECHECK_MS) {
209 return kept
210 }
211 if (!isForced && kept.spendAskedAt !== null && now - kept.spendAskedAt < kept.spendWaitMs) {
212 return kept
213 }
214 const out = await run($, [...argv, 'billing', 'report', '--for', 'today', '--json'], LIST_TIMEOUT_MS)
215 const text = `${out.stderr}\n${out.stdout}`
216 const spent = out.started && out.code === 0 ? parseSpend(out.stdout) : null
217 if (spent !== null) {
218 return { spendToday: spent, spendNote: null, spendAskedAt: now, spendWaitMs: SPEND_EVERY_MS, billingUnsupportedAt: null }
219 }
220 if (lacksBilling(text)) {
221 return {
222 spendToday: null,
223 spendNote: 'this Modal CLI has no `billing report` command; Modal 1.3.3 and later have one',
224 spendAskedAt: now,
225 spendWaitMs: SPEND_EVERY_MS,
226 billingUnsupportedAt: now,
227 }
228 }
229 return {
230 spendToday: null,
231 spendNote: `\`billing report\` failed: ${firstLine(text)}`,
232 spendAskedAt: now,
233 spendWaitMs: SPEND_RETRY_MS,
234 billingUnsupportedAt: null,
235 }
236}
237
238/**
239 * One run of the CLI: the app list, then spend where due. `shared` is the last answer any session
240 * gave, whose spend timing and billing knowledge carry on; `now` is when the poll started.
241 */
242async function probe($: Engine, argv: readonly string[], shared: ModalShared, now: number, isForced: boolean): Promise<ModalShared> {
243 const label = argv.join(' ')
244 const kept: ModalShared = { ...shared, cli: [...argv], problem: null, apps: [] }
245 const listed = await run($, [...argv, 'app', 'list', '--json'], LIST_TIMEOUT_MS)
246 const text = `${listed.stderr}\n${listed.stdout}`
247 const apps = listed.started && listed.code === 0 ? parseAppList(listed.stdout) : null
248 adapt($, (await $.clock.now()) - now, isTimeout(listed.stderr), apps !== null)
249 if (!listed.started) {
250 if (isEnoent(listed.stderr)) {
251 // The executable is not on this session's PATH: no retry until /modal asks to look again.
252 cli = null
253 }
254 return { ...kept, problem: `\`${label} app list\` could not run: ${firstLine(listed.stderr)}` }
255 }
256 if (listed.code !== 0) {
257 return {
258 ...kept,
259 problem: isAuthProblem(text)
260 ? `Modal has no profile or token set up on this machine (run \`${label} setup\`)`
261 : `\`${label} app list\` failed: ${firstLine(text)}`,
262 }
263 }
264 if (apps === null) {
265 return { ...kept, problem: `\`${label} app list --json\` printed no JSON list` }
266 }
267 return { ...kept, ...(await readSpend($, argv, now, isForced, spendOf(kept))), apps }
268}
269
270/** Shows an answer, this session's or another's: the status line, the pane's rows, the long-run toasts and the budget toast. */
271async function apply($: Engine, data: ModalShared, polledAt: number, now: number) {
272 const label = data.cli?.join(' ') ?? null
273 if (data.problem !== null) {
274 await silence($, data.problem, label)
275 return
276 }
277 let next = trackApps(await read($, tracked), data.apps, now)
278 for (const app of dueAlerts(data.apps, next, now, config.alertMs)) {
279 const since = next[app.id]?.busySince ?? now
280 $.ui.toast(alertText(app, now - since), { timeoutMs: 15_000 })
281 next = { ...next, [app.id]: { busySince: since, alertedAt: now } }
282 }
283 await update($, tracked, () => next)
284 if (data.spendToday !== null) {
285 await checkBudget($, data.spendToday, now)
286 }
287 await update($, meter, () => ({
288 cli: label,
289 problem: null,
290 apps: data.apps,
291 polledAt,
292 spendToday: data.spendToday,
293 spendNote: data.spendNote,
294 }))
295 $.ui.status(statusText(data.apps, false))
296}
297
298/** `~/.claude/modal-meter`, where every session shares what it read; null with no home directory to keep it under. */
299async function sharedDir($: Engine): Promise<string | null> {
300 if (home === undefined) {
301 const found = (await $.env.get('HOME').catch(() => undefined)) || (await $.env.get('USERPROFILE').catch(() => undefined))
302 home = found ? found.replace(/\/+$/, '') : null
303 }
304 return home === null ? null : `${home}/.claude/modal-meter`
305}
306
307/** This session's id: the name on the lock and the cache it writes. */
308async function whoAmI($: Engine): Promise<string> {
309 sessionId ??= (await $.session.id().catch(() => null)) || `s-${Math.random().toString(36).slice(2, 10)}`
310 return sessionId
311}
312
313/** A JSON file's value; null when it is missing or not JSON. */
314async function readJson($: Engine, path: string): Promise<unknown> {
315 const text = await $.fs.read(path).catch(() => null)
316 if (typeof text !== 'string') {
317 return null
318 }
319 try {
320 return JSON.parse(text)
321 } catch {
322 return null
323 }
324}
325
326/** The shared cache; with no home directory, what this session last wrote itself. */
327async function readCache($: Engine, dir: string | null): Promise<ModalCache | null> {
328 if (dir === null) {
329 return memo
330 }
331 const value = await readJson($, `${dir}/cache.json`)
332 return isCacheEntry(value) ? value : null
333}
334
335async function writeCache($: Engine, dir: string | null, entry: ModalCache) {
336 memo = entry
337 if (dir !== null) {
338 await $.fs.write(`${dir}/cache.json`, JSON.stringify(entry)).catch(() => undefined)
339 }
340}
341
342/**
343 * Whether this session may run the CLI now, taking the lock when it may. A tick yields to another
344 * session's lock while it is live: the holder's poll interval plus one probe timeout since it was
345 * taken. The holder keeps the lock between polls, so one session polls for all until it goes away;
346 * the person's own /modal and a stop this session made poll whoever holds it.
347 */
348async function takeLock($: Engine, dir: string, now: number, holderIntervalMs: number, isTick: boolean): Promise<boolean> {
349 const me = await whoAmI($)
350 const lock = await readJson($, `${dir}/lock.json`)
351 if (isTick && isLock(lock) && lock.by !== me && now - lock.ts < holderIntervalMs + LOCK_STALE_MS) {
352 return false
353 }
354 await $.fs.write(`${dir}/lock.json`, JSON.stringify({ ts: now, by: me })).catch(() => undefined)
355 return true
356}
357
358/** The poll interval after a probe: doubled after a slow or timed-out one, the option again after a fast success; one log line per change. */
359function adapt($: Engine, elapsedMs: number, isTimedOut: boolean, isOk: boolean) {
360 const next = nextInterval(intervalMs, config.pollMs, elapsedMs, isTimedOut, isOk)
361 if (next === intervalMs) {
362 return
363 }
364 intervalMs = next
365 $.ui.log(`modal-meter: polling every ${formatDuration(next)} (app list ${isTimedOut ? 'timed out' : `took ${formatDuration(elapsedMs)}`})`, {
366 to: 'debug',
367 })
368 setTimer($)
369}
370
371/** (Re)starts the timer at the interval in force. */
372function setTimer($: Engine) {
373 timer?.cancel()
374 timer = $.clock.every(intervalMs, () => void poll($, 'tick'))
375}
376
377function ensureTimer($: Engine) {
378 if (!timer) {
379 setTimer($)
380 }
381}
382
383async function pollOnce($: Engine, mode: Poll) {
384 const now = await $.clock.now()
385 const dir = await sharedDir($)
386 const cached = await readCache($, dir)
387 if (mode !== 'changed' && cached !== null && now - cached.ts < cached.intervalMs) {
388 await apply($, cached.data, cached.ts, now)
389 return
390 }
391 if (cli === undefined) {
392 cli = await adoptCli($, cached?.data.cli ?? null)
393 }
394 if (cli === null) {
395 // Nothing to run here; another session's answer, even an old one, is still worth showing.
396 if (cached !== null) {
397 await apply($, cached.data, cached.ts, now)
398 } else {
399 await silence($, notFound(), null)
400 }
401 return
402 }
403 if (dir !== null && !(await takeLock($, dir, now, cached?.intervalMs ?? intervalMs, mode === 'tick'))) {
404 if (cached !== null) {
405 await apply($, cached.data, cached.ts, now)
406 }
407 return
408 }
409 const data = await probe($, cli, cached?.data ?? UNKNOWN, now, mode === 'asked')
410 await writeCache($, dir, { ts: now, by: await whoAmI($), intervalMs, data })
411 await apply($, data, now, now)
412}
413
414/** One poll at a time: a call while one runs shares it. */
415function poll($: Engine, mode: Poll): Promise<void> {
416 if (!inflight) {
417 inflight = pollOnce($, mode)
418 .catch(error => $.ui.log(`modal-meter: poll failed: ${String(error)}`, { to: 'debug' }))
419 .finally(() => {
420 inflight = null
421 })
422 }
423 return inflight
424}
425
426/** A poll that starts after any running one, so it sees what happened since. */
427async function refresh($: Engine, mode: Poll) {
428 if (inflight) {
429 await inflight
430 }
431 await poll($, mode)
432}
433
434/** The project's dependency files worth reading, by name; the usual four when the folder cannot be listed. */
435async function dependencyFiles($: Engine, cwd: string): Promise<string[]> {
436 try {
437 return (await $.fs.list(cwd)).filter(entry => entry.kind === 'file' && isDependencyFile(entry.name)).map(entry => entry.name)
438 } catch {
439 return DEPENDENCY_FILES
440 }
441}
442
443/** Whether the project imports modal in a `.py` file (asked of `rg`), or names it in a dependency file. */
444async function detectModal($: Engine, cwd: string): Promise<boolean> {
445 const found = await run($, ['rg', ...RG_ARGS, cwd], DETECT_TIMEOUT_MS)
446 if (found.started && found.code === 0 && found.stdout.trim() !== '') {
447 return true
448 }
449 for (const name of await dependencyFiles($, cwd)) {
450 const text = await $.fs.read(`${cwd}/${name}`).catch(() => null)
451 if (typeof text === 'string' && namesModal(name, text)) {
452 return true
453 }
454 }
455 return false
456}
457
458/** Whether the project at `cwd` uses Modal, remembered in the store for a day. */
459async function usesModal($: Engine, cwd: string): Promise<boolean> {
460 const key = `project:${cwd}`
461 const now = await $.clock.now()
462 const known = await $.store.get(key).catch(() => undefined)
463 if (isProjectRecord(known) && now - known.checkedAt < PROJECT_RECHECK_MS) {
464 return known.usesModal
465 }
466 const record: ModalProject = { usesModal: await detectModal($, cwd), checkedAt: now }
467 await $.store.set(key, record).catch(() => undefined)
468 return record.usesModal
469}
470
471/** Turns the meter on for this session, once: the state the pane reads, and the timer. */
472async function startWatching($: Engine, why: string) {
473 if (!(await read($, watching))) {
474 await update($, watching, () => true)
475 $.ui.log(`modal-meter: watching Modal: ${why}`, { to: 'debug' })
476 }
477 ensureTimer($)
478}
479
480/** The session's start, off the hook's own time: whether this project is watched, then the first poll. */
481async function begin($: Engine, cwd: string) {
482 try {
483 await update($, stopping, () => null)
484 const why = config.alwaysPoll
485 ? 'the alwaysPoll option'
486 : (await read($, watching))
487 ? 'asked earlier this session'
488 : (await usesModal($, cwd))
489 ? 'this project uses Modal'
490 : null
491 if (why === null) {
492 $.ui.log('modal-meter: not watching Modal: this project does not use it (/modal or a modal command starts it)', { to: 'debug' })
493 return
494 }
495 await startWatching($, why)
496 await poll($, 'tick')
497 } catch (error) {
498 $.ui.log(`modal-meter: start failed: ${String(error)}`, { to: 'debug' })
499 }
500}
501
502/** The confirmed Stop: `modal app stop <id>` (again with `--yes` where the CLI asks for it), a fresh poll, a toast. */
503async function stopApp($: Engine, id: string) {
504 if ((await read($, stopping)) !== null) {
505 return
506 }
507 const name = (await read($, meter)).apps.find(app => app.id === id)?.name ?? id
508 await update($, confirming, () => null)
509 await update($, stopping, () => id)
510 let out: Ran = { started: false, code: -1, stdout: '', stderr: 'no Modal CLI' }
511 try {
512 if (cli === undefined) {
513 cli = await adoptCli($, memo?.data.cli ?? null)
514 }
515 if (cli) {
516 out = await run($, [...cli, 'app', 'stop', id], STOP_TIMEOUT_MS)
517 if (out.started && out.code !== 0 && wantsYes(`${out.stderr}\n${out.stdout}`)) {
518 out = await run($, [...cli, 'app', 'stop', '--yes', id], STOP_TIMEOUT_MS)
519 }
520 }
521 } finally {
522 await update($, stopping, () => null)
523 }
524 await refresh($, 'changed')
525 $.ui.toast(
526 out.started && out.code === 0
527 ? `Stopped Modal app ${name}`
528 : `Could not stop Modal app ${name}: ${firstLine(`${out.stderr}\n${out.stdout}`)}`,
529 { timeoutMs: 10_000 },
530 )
531}
532
533const positive = (value: unknown, fallback: number): number => {
534 const n = Number(value)
535 return Number.isFinite(n) && n > 0 ? n : fallback
536}
537
538export const register: Register = (on, options) => {
539 config = {
540 command: String(options.modalCommand ?? '').trim(),
541 pollMs: Math.max(10, positive(options.pollSeconds, 60)) * 1000,
542 alertMs: positive(options.alertMinutes, 30) * 60_000,
543 budget: Math.max(0, Number(options.budgetToday ?? 0) || 0),
544 alwaysPoll: options.alwaysPoll === true,
545 }
546 timer = null
547 intervalMs = config.pollMs
548 cli = undefined
549 inflight = null
550 home = undefined
551 sessionId = null
552 memo = null
553
554 on('session.start', async ($, e, next) => {
555 await $.command.register({
556 name: 'modal',
557 description: 'Open the Modal pane: running apps, containers, spend; stop an app',
558 })
559 void begin($, e.cwd)
560 return next(e)
561 })
562
563 on('command.run', { command: 'modal' }, async $ => {
564 await startWatching($, 'the person ran /modal')
565 if (cli === null) {
566 // Not found before: look again, in case Modal was installed since.
567 cli = undefined
568 }
569 await refresh($, 'asked')
570 await $.ui.open({ id: PANE, title: TITLE })
571 return { text: summaryText(await read($, meter), await read($, tracked), await $.clock.now(), config.budget) }
572 })
573
574 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
575 if (isModalCommand(e.command) && !(await read($, watching))) {
576 await startWatching($, 'a modal command ran')
577 void poll($, 'tick')
578 }
579 return next(e)
580 })
581
582 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
583 const { Box, Text, Button } = $.ui.resolve(e)
584 const shown = await read($, meter)
585 const tracking = await read($, tracked)
586 const asked = await read($, confirming)
587 const busyId = await read($, stopping)
588 const isWatching = await read($, watching)
589 const now = await $.clock.now()
590 const apps = activeApps(shown.apps)
591 const notice = paneNotice(shown, isWatching)
592 // An answer older than two polls: another session holds the lock and is slow, or this one has no CLI.
593 const age = shown.polledAt !== null && now - shown.polledAt >= 2 * intervalMs ? now - shown.polledAt : null
594 const spend =
595 shown.spendToday === null
596 ? null
597 : `Spend today (UTC): ${usd(shown.spendToday)}${config.budget > 0 ? ` of ${usd(config.budget)}` : ''}`
598
599 return (
600 <Box flexDirection="column" gap={1}>
601 {notice !== null && <Text dimColor>{notice}</Text>}
602 {apps.map(app => {
603 const isIdle = kindOf(app) === 'idle'
604 if (busyId === app.id) {
605 return (
606 <Box key={`row-${app.id}`} flexDirection="row">
607 <Text color="yellow">{`Stopping ${app.name}…`}</Text>
608 </Box>
609 )
610 }
611 if (asked === app.id) {
612 return (
613 <Box key={`row-${app.id}`} flexDirection="row" gap={1}>
614 <Text bold>{`Stop ${app.name}?`}</Text>
615 <Button
616 key={`confirm-${app.id}`}
617 label="Confirm"
618 variant="primary"
619 onPress={() => stopApp($, app.id)}
620 />
621 <Button key={`cancel-${app.id}`} label="Cancel" onPress={() => update($, confirming, () => null)} />
622 </Box>
623 )
624 }
625 return (
626 <Box key={`row-${app.id}`} flexDirection="row" justifyContent="space-between" gap={1}>
627 <Text dimColor={isIdle} wrap="truncate-end">
628 {rowText(app, tracking[app.id], now)}
629 </Text>
630 <Button
631 key={`stop-${app.id}`}
632 label="Stop"
633 dimColor={isIdle}
634 onPress={() => update($, confirming, () => app.id)}
635 />
636 </Box>
637 )
638 })}
639 {age !== null && <Text dimColor>{`Last read ${formatDuration(age)} ago.`}</Text>}
640 {spend !== null && <Text dimColor>{spend}</Text>}
641 </Box>
642 )
643 })
644}
645hooks/meter.ts 445 lines1import type { ModalApp, ModalAppKind, ModalCache, ModalLock, ModalMeter, ModalProject, ModalTracked } from '../types'
2
3const ANSI = /\u001b\[[0-9;?]*[A-Za-z]/g
4
5/** The command candidates to try, in order: the option split into argv, else `modal` then `python3 -m modal`. */
6export const cliCandidates = (option: string): string[][] => {
7 const own = splitCommand(option)
8 return own.length > 0 ? [own] : [['modal'], ['python3', '-m', 'modal']]
9}
10
11/** Splits a command line on spaces, keeping "quoted words" whole. */
12export const splitCommand = (text: string): string[] =>
13 text.match(/"[^"]*"|'[^']*'|\S+/g)?.map(word => word.replace(/^(["'])(.*)\1$/, '$2')) ?? []
14
15/** A Modal CLI JSON key in one spelling: `App ID` (CLI before 1.5) and `app_id` (1.5 on) both read `app_id`. */
16export const jsonKey = (key: string): string =>
17 key
18 .replace(/[^a-zA-Z0-9]+/g, '_')
19 .toLowerCase()
20 .replace(/^_+|_+$/g, '')
21
22/** The first JSON array in `text`, ANSI styling stripped (rich adds it when FORCE_COLOR is set); null when there is none. */
23const jsonArray = (text: string): unknown[] | null => {
24 const plain = text.replace(ANSI, '')
25 const start = plain.indexOf('[')
26 const end = plain.lastIndexOf(']')
27 if (start < 0 || end < start) {
28 return null
29 }
30 try {
31 const parsed: unknown = JSON.parse(plain.slice(start, end + 1))
32 return Array.isArray(parsed) ? parsed : null
33 } catch {
34 return null
35 }
36}
37
38const normalized = (row: unknown): Record<string, unknown> | null => {
39 if (!row || typeof row !== 'object' || Array.isArray(row)) {
40 return null
41 }
42 const out: Record<string, unknown> = {}
43 for (const [key, value] of Object.entries(row)) {
44 out[jsonKey(key)] = value
45 }
46 return out
47}
48
49const pick = (row: Record<string, unknown>, keys: readonly string[]): unknown =>
50 keys.map(key => row[key]).find(value => value !== undefined && value !== null && value !== '')
51
52/**
53 * A Modal timestamp in epoch ms: `2026-10-07 07:50:00-07:00` (the CLI's JSON), any ISO
54 * string, or epoch seconds or ms. Null when absent or unreadable.
55 */
56export const parseTimestamp = (value: unknown): number | null => {
57 if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
58 return value < 1e12 ? value * 1000 : value
59 }
60 if (typeof value !== 'string' || !value.trim()) {
61 return null
62 }
63 const text = value.trim()
64 if (/^\d+(\.\d+)?$/.test(text)) {
65 return parseTimestamp(Number(text))
66 }
67 const ms = Date.parse(text.replace(/^(\d{4}-\d{2}-\d{2}) (\d)/, '$1T$2'))
68 return Number.isFinite(ms) ? ms : null
69}
70
71/** Modal's state label in one short word: `ephemeral (detached)` → `detached`, `initializing...` → `initializing`. */
72export const normalizeState = (value: unknown): string => {
73 const text = String(value ?? '')
74 .toLowerCase()
75 .replace(/\.+$|…$/g, '')
76 .trim()
77 if (!text) {
78 return 'unknown'
79 }
80 return /detached/.test(text) ? 'detached' : text
81}
82
83const count = (value: unknown): number => {
84 const n = typeof value === 'number' ? value : Number.parseInt(String(value ?? ''), 10)
85 return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0
86}
87
88/**
89 * The apps in `modal app list --json`, whatever the CLI's key spelling (`App ID`,
90 * `Description`, `State`, `Tasks`, `Created at`, `Stopped at`; snake_case from 1.5 on).
91 * Rows with no id are dropped. Null when the text holds no JSON array.
92 */
93export const parseAppList = (text: string): ModalApp[] | null => {
94 const rows = jsonArray(text)
95 if (rows === null) {
96 return null
97 }
98 const apps: ModalApp[] = []
99 for (const raw of rows) {
100 const row = normalized(raw)
101 if (!row) {
102 continue
103 }
104 const id = pick(row, ['app_id', 'id', 'appid'])
105 if (typeof id !== 'string' || !id.trim()) {
106 continue
107 }
108 const name = pick(row, ['description', 'name', 'app_name'])
109 apps.push({
110 id: id.trim(),
111 name: typeof name === 'string' && name.trim() ? name.trim() : id.trim(),
112 state: normalizeState(pick(row, ['state', 'status'])),
113 containers: count(pick(row, ['tasks', 'n_running_tasks', 'running_tasks', 'containers'])),
114 createdAt: parseTimestamp(pick(row, ['created_at', 'created'])),
115 stoppedAt: parseTimestamp(pick(row, ['stopped_at', 'stopped'])),
116 })
117 }
118 return apps
119}
120
121/** States a `modal run` is in while its local process lives: worth counting even before containers start. */
122const LIVE_STATES = new Set(['ephemeral', 'detached', 'initializing', 'running'])
123const GONE_STATES = new Set(['stopped', 'disabled'])
124
125export const kindOf = (app: ModalApp): ModalAppKind => {
126 if (app.containers > 0) {
127 return 'running'
128 }
129 if (GONE_STATES.has(app.state) || app.state === 'stopping' || app.stoppedAt !== null) {
130 return 'stopped'
131 }
132 return LIVE_STATES.has(app.state) ? 'running' : 'idle'
133}
134
135/** The apps worth a row: everything not stopped, running ones first, most containers first, then by name. */
136export const activeApps = (apps: readonly ModalApp[]): ModalApp[] =>
137 apps
138 .filter(app => kindOf(app) !== 'stopped')
139 .sort(
140 (a, b) =>
141 Number(kindOf(b) === 'running') - Number(kindOf(a) === 'running') ||
142 b.containers - a.containers ||
143 a.name.localeCompare(b.name),
144 )
145
146const plural = (n: number, word: string): string => `${n} ${word}${n === 1 ? '' : 's'}`
147
148export const containersText = (n: number): string => plural(n, 'container')
149
150/** `Modal: 1 running (2 containers) · 1 deployed`; undefined when nothing is active. */
151/**
152 * `Modal: 1 running (2 containers) · 1 deployed`; with `includeIdle` false (the status line),
153 * deployed apps with no containers are left out, since they cost nothing.
154 */
155export const statusText = (apps: readonly ModalApp[], includeIdle = true): string | undefined => {
156 const active = activeApps(apps)
157 const running = active.filter(app => kindOf(app) === 'running')
158 const idle = active.length - running.length
159 const containers = running.reduce((sum, app) => sum + app.containers, 0)
160 const parts: string[] = []
161 if (running.length > 0) {
162 parts.push(`${running.length} running${containers > 0 ? ` (${containersText(containers)})` : ''}`)
163 }
164 if (idle > 0 && (includeIdle || running.length > 0)) {
165 parts.push(`${idle} deployed`)
166 }
167 return parts.length > 0 ? `Modal: ${parts.join(' · ')}` : undefined
168}
169
170/**
171 * Since when an app with containers counts as up: a `modal run` app from its creation;
172 * a deployed app from when the meter first saw it with containers (its creation is the
173 * deploy, which can be weeks old).
174 */
175const busyStart = (app: ModalApp, now: number): number =>
176 LIVE_STATES.has(app.state) && app.createdAt !== null && app.createdAt <= now ? app.createdAt : now
177
178/**
179 * The tracking carried to this poll: every listed app that is not stopped keeps its
180 * last alert time; `busySince` starts when containers appear and clears when they go.
181 */
182export const trackApps = (
183 previous: Readonly<Record<string, ModalTracked>>,
184 apps: readonly ModalApp[],
185 now: number,
186): Record<string, ModalTracked> => {
187 const next: Record<string, ModalTracked> = {}
188 for (const app of apps) {
189 if (kindOf(app) === 'stopped') {
190 continue
191 }
192 const before = previous[app.id]
193 next[app.id] = {
194 busySince: app.containers > 0 ? (before?.busySince ?? busyStart(app, now)) : null,
195 alertedAt: before?.alertedAt ?? null,
196 }
197 }
198 return next
199}
200
201/**
202 * The apps due a long-running toast: containers up for longer than `alertMs`, and no
203 * toast for them in the last `alertMs`.
204 */
205export const dueAlerts = (
206 apps: readonly ModalApp[],
207 tracked: Readonly<Record<string, ModalTracked>>,
208 now: number,
209 alertMs: number,
210): ModalApp[] =>
211 apps.filter(app => {
212 const one = tracked[app.id]
213 if (!one || one.busySince === null || app.containers === 0) {
214 return false
215 }
216 return now - one.busySince > alertMs && (one.alertedAt === null || now - one.alertedAt >= alertMs)
217 })
218
219/** `45s`, `45m`, `2h 5m`, `3d 4h`. */
220export const formatDuration = (ms: number): string => {
221 const seconds = Math.max(0, Math.floor(ms / 1000))
222 if (seconds < 60) {
223 return `${seconds}s`
224 }
225 const minutes = Math.floor(seconds / 60)
226 if (minutes < 60) {
227 return `${minutes}m`
228 }
229 const hours = Math.floor(minutes / 60)
230 if (hours < 24) {
231 return `${hours}h${minutes % 60 ? ` ${minutes % 60}m` : ''}`
232 }
233 const days = Math.floor(hours / 24)
234 return `${days}d${hours % 24 ? ` ${hours % 24}h` : ''}`
235}
236
237export const alertText = (app: ModalApp, upMs: number): string =>
238 `Modal app ${app.name} has run ${formatDuration(upMs)} with ${containersText(app.containers)} — /modal to stop it`
239
240/** How long an app has been up: since its containers started, else since it was created. */
241export const upFor = (app: ModalApp, tracked: ModalTracked | undefined, now: number): number | null => {
242 const since = tracked?.busySince ?? app.createdAt
243 return since === null ? null : Math.max(0, now - since)
244}
245
246/** `image-worker · ephemeral · 2 containers · up 45m`. */
247export const rowText = (app: ModalApp, tracked: ModalTracked | undefined, now: number): string => {
248 const up = upFor(app, tracked, now)
249 return [app.name, app.state, containersText(app.containers), up === null ? null : `up ${formatDuration(up)}`]
250 .filter(Boolean)
251 .join(' · ')
252}
253
254/** `$1.23`. */
255export const usd = (amount: number): string => `$${amount.toFixed(2)}`
256
257/**
258 * Today's spend from `modal billing report --for today --json`: the sum of its rows'
259 * `cost` (a decimal string). Null when the text holds no JSON array.
260 */
261export const parseSpend = (text: string): number | null => {
262 const rows = jsonArray(text)
263 if (rows === null) {
264 return null
265 }
266 let total = 0
267 for (const raw of rows) {
268 const row = normalized(raw)
269 const cost = row ? Number(pick(row, ['cost', 'total_cost', 'amount'])) : Number.NaN
270 if (Number.isFinite(cost)) {
271 total += cost
272 }
273 }
274 return Math.round(total * 1e6) / 1e6
275}
276
277/**
278 * The CLI said it has no `billing` command (Modal before 1.3.3): the "No such command" line of
279 * its error box, or the root command's usage line (`Usage: modal [OPTIONS] COMMAND [ARGS]...`),
280 * which a usage error of `billing report` itself never prints.
281 */
282export const lacksBilling = (output: string): boolean => {
283 const plain = output.replace(ANSI, '')
284 return /no such command\W+billing/i.test(plain) || /^\s*usage:(?!.*\bbilling\b).*\[OPTIONS\] COMMAND \[ARGS\]/im.test(plain)
285}
286
287/** `$.process.run` gave the command up: "aborted: still running after Nms". */
288export const isTimeout = (output: string): boolean => /still running after/i.test(output)
289
290/** The command could not start: the executable is not there. */
291export const isEnoent = (output: string): boolean => /\bENOENT\b|not found in \$?PATH/i.test(output)
292
293/** The CLI could not authenticate: no profile or token set up on this machine. */
294export const isAuthProblem = (output: string): boolean =>
295 /token|authenticat|credential|not logged in|modal setup|no modal profile|profile.*not found/i.test(output)
296
297/** A Modal that runs at all but has no `modal` package behind `python3 -m modal`. */
298export const isMissingModule = (output: string): boolean => /no module named '?modal/i.test(output)
299
300/** `modal app stop` refused to run without a terminal and asked for `--yes` (Modal 1.4.2 on). */
301export const wantsYes = (output: string): boolean => /--yes\b/.test(output)
302
303/** The first line worth showing from a failed command's output. */
304export const firstLine = (output: string): string =>
305 output
306 .replace(ANSI, '')
307 .split('\n')
308 .map(line => line.replace(/^[\s│╭╰─┃|]+|[\s│╮╯─┃|]+$/g, '').trim())
309 .find(line => line && !/^(error|usage:.*|try '.*)$/i.test(line))
310 ?.slice(0, 160) ?? 'no output'
311
312/** The UTC day of `ms`, `2026-10-07`: the day Modal's `--for today` reports. */
313export const utcDay = (ms: number): string => new Date(ms).toISOString().slice(0, 10)
314
315export const NOT_WATCHING =
316 'Not watching Modal: this project does not use it. /modal starts watching for this session; the alwaysPoll option watches every project.'
317
318/** The pane's one-line notice: why there are no rows, or that they are on their way; null when there are rows to show. */
319export const paneNotice = (meter: ModalMeter, isWatching: boolean): string | null => {
320 if (meter.problem !== null) {
321 return `modal-meter is silent: ${meter.problem}.`
322 }
323 if (meter.polledAt === null) {
324 return isWatching ? 'Reading Modal…' : NOT_WATCHING
325 }
326 return activeApps(meter.apps).length === 0 ? 'No Modal apps running or deployed.' : null
327}
328
329/** The meter's state in words: what `/modal` answers. */
330export const summaryText = (
331 meter: ModalMeter,
332 tracked: Readonly<Record<string, ModalTracked>>,
333 now: number,
334 budget: number,
335): string => {
336 if (meter.problem !== null) {
337 return `modal-meter is silent: ${meter.problem}.`
338 }
339 if (meter.polledAt === null) {
340 return 'modal-meter has not read Modal yet.'
341 }
342 const apps = activeApps(meter.apps)
343 const lines = [`${statusText(meter.apps) ?? 'Modal: nothing running or deployed'} (read with \`${meter.cli ?? 'modal'}\`)`]
344 for (const app of apps) {
345 lines.push(` ${rowText(app, tracked[app.id], now)}${kindOf(app) === 'idle' ? ' (idle)' : ''}`)
346 }
347 lines.push(
348 meter.spendToday !== null
349 ? `Spend today (UTC): ${usd(meter.spendToday)}${budget > 0 ? ` of a ${usd(budget)} daily budget` : ''}`
350 : `Spend: not shown (${meter.spendNote ?? 'not read yet'})`,
351 )
352 return lines.join('\n')
353}
354
355/** A probe slower than this doubles the poll interval. */
356export const SLOW_MS = 2_000
357/** The poll interval backs off no further than this. */
358export const MAX_INTERVAL_MS = 10 * 60_000
359
360/**
361 * The next poll interval: doubled (never past `MAX_INTERVAL_MS`, never below the option) after a
362 * probe that timed out or took longer than `SLOW_MS`; the option again after a fast success; else
363 * as it was (a fast failure says nothing about Modal's speed).
364 */
365export const nextInterval = (current: number, configured: number, elapsedMs: number, isTimedOut: boolean, isOk: boolean): number => {
366 if (isTimedOut || elapsedMs > SLOW_MS) {
367 return Math.max(configured, Math.min(current * 2, MAX_INTERVAL_MS))
368 }
369 return isOk ? configured : current
370}
371
372/** Words that run the word after them, so `python3 -m modal`, `uv run modal` and `sudo modal` count as modal. */
373const RUNNERS = new Set([
374 'sudo', 'env', 'time', 'nohup', 'exec', 'command', 'nice', 'caffeinate', 'watch',
375 'uv', 'uvx', 'poetry', 'pipx', 'pdm', 'hatch', 'run', 'python', 'python3', 'py',
376])
377
378/**
379 * Whether a shell command runs the Modal CLI: `modal …` (or `…/modal …`) as the command of any
380 * simple command in it, after any `VAR=value` prefix and runners (`uv run`, `python3 -m`, `sudo`).
381 * Mentions as an argument (`grep modal`, `pip install modal`) do not count.
382 */
383export const isModalCommand = (command: string): boolean =>
384 command.split(/\n|;|&&|\|\||\||\$\(|`|[(){}]/).some(part => {
385 const words = part.trim().split(/\s+/)
386 let i = 0
387 while (i < words.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(words[i] ?? '')) {
388 i++
389 }
390 while (i < words.length && (RUNNERS.has(words[i] ?? '') || (words[i] ?? '').startsWith('-'))) {
391 i++
392 }
393 return /(^|\/)modal$/.test(words[i] ?? '')
394 })
395
396/** A dependency file worth reading for a `modal` requirement: `pyproject.toml`, `requirements*.txt`, `uv.lock`, `poetry.lock`. */
397export const isDependencyFile = (name: string): boolean => /^(pyproject\.toml|requirements[^/]*\.txt|uv\.lock|poetry\.lock)$/.test(name)
398
399/**
400 * Whether a dependency file names the `modal` package: a requirement line in `requirements*.txt`;
401 * a `"modal…"` requirement string or a `modal = …` key in `pyproject.toml`; a `name = "modal"`
402 * package in `uv.lock` or `poetry.lock`.
403 */
404export const namesModal = (file: string, text: string): boolean => {
405 const name = file.slice(file.lastIndexOf('/') + 1)
406 if (/^requirements[^/]*\.txt$/.test(name)) {
407 return /^\s*modal\b/im.test(text)
408 }
409 if (name === 'pyproject.toml') {
410 return /["']modal(?=\s*["'[<>=!~;@])/i.test(text) || /^\s*modal\s*=/m.test(text)
411 }
412 if (name === 'uv.lock' || name === 'poetry.lock') {
413 return /^\s*name\s*=\s*"modal"\s*$/m.test(text)
414 }
415 return false
416}
417
418const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
419
420const isNumberOrNull = (value: unknown): boolean => value === null || typeof value === 'number'
421const isStringOrNull = (value: unknown): boolean => value === null || typeof value === 'string'
422
423/** The shared cache file read back: `{ ts, by, intervalMs, data }` in the shapes the meter writes. */
424export const isCacheEntry = (value: unknown): value is ModalCache =>
425 isRecord(value) &&
426 typeof value.ts === 'number' &&
427 typeof value.by === 'string' &&
428 typeof value.intervalMs === 'number' &&
429 isRecord(value.data) &&
430 (value.data.cli === null || Array.isArray(value.data.cli)) &&
431 isStringOrNull(value.data.problem) &&
432 Array.isArray(value.data.apps) &&
433 isNumberOrNull(value.data.spendToday) &&
434 isStringOrNull(value.data.spendNote) &&
435 isNumberOrNull(value.data.spendAskedAt) &&
436 typeof value.data.spendWaitMs === 'number' &&
437 isNumberOrNull(value.data.billingUnsupportedAt)
438
439/** The shared lock file read back: `{ ts, by }`. */
440export const isLock = (value: unknown): value is ModalLock => isRecord(value) && typeof value.ts === 'number' && typeof value.by === 'string'
441
442/** A project's record in the store: `{ usesModal, checkedAt }`. */
443export const isProjectRecord = (value: unknown): value is ModalProject =>
444 isRecord(value) && typeof value.usesModal === 'boolean' && typeof value.checkedAt === 'number'
445types/index.d.ts 104 lines1/** One row of `modal app list --json`, read defensively. */
2export type ModalApp = {
3 /** The app id (`ap-…`), what `modal app stop` takes. */
4 id: string
5 /** The app's description: its name, or the id when Modal gave none. */
6 name: string
7 /**
8 * Modal's state, lowercased and shortened: `deployed`, `ephemeral`, `detached`
9 * (ephemeral, detached), `initializing`, `stopping`, `stopped`, `disabled`, or
10 * whatever word a newer CLI prints.
11 */
12 state: string
13 /** Running tasks (containers). */
14 containers: number
15 /** When the app was created, in epoch ms; null when the CLI did not say. */
16 createdAt: number | null
17 /** When the app stopped, in epoch ms; null while it has not. */
18 stoppedAt: number | null
19}
20
21/** `running`: containers up or a live `modal run`; `idle`: deployed with no containers; `stopped`: gone. */
22export type ModalAppKind = 'running' | 'idle' | 'stopped'
23
24/** What the meter remembers about one listed app between polls. */
25export type ModalTracked = {
26 /** Since when it has had containers (null while it has none). */
27 busySince: number | null
28 /** When it last raised the long-running toast. */
29 alertedAt: number | null
30}
31
32export type ModalMeter = {
33 /** The CLI in use, as typed (`python3 -m modal`); null when none ran. */
34 cli: string | null
35 /** Why the meter is silent; null while it is reading Modal. */
36 problem: string | null
37 apps: ModalApp[]
38 polledAt: number | null
39 /** Today's spend in USD (Modal's UTC day); null when not known. */
40 spendToday: number | null
41 /** Why spend is not shown; null while it is (or before it was asked). */
42 spendNote: string | null
43}
44
45/**
46 * What one session's poll learned, written to `~/.claude/modal-meter/cache.json` for every
47 * session on the machine: the one holding the lock runs the CLI, the others show this.
48 */
49export type ModalShared = {
50 /** The CLI argv that answered (`['python3', '-m', 'modal']`); null when none did. */
51 cli: string[] | null
52 /** Why there are no apps to show; null when `apps` is the answer. */
53 problem: string | null
54 apps: ModalApp[]
55 /** Today's spend in USD (Modal's UTC day); null when not known. */
56 spendToday: number | null
57 /** Why spend is not shown; null while it is (or before it was asked). */
58 spendNote: string | null
59 /** When `billing report` was last run, by any session; null when never. */
60 spendAskedAt: number | null
61 /** How long after `spendAskedAt` to ask again: five minutes, or an hour after a failure. */
62 spendWaitMs: number
63 /** When a session learned this CLI has no `billing report`; null while it has one, or none has tried. */
64 billingUnsupportedAt: number | null
65}
66
67/** The shared cache file: who wrote it when, and how long it is good for (the writer's poll interval). */
68export type ModalCache = {
69 ts: number
70 /** The session that wrote it. */
71 by: string
72 intervalMs: number
73 data: ModalShared
74}
75
76/** The shared lock file: the session polling Modal for everyone, and when it last started a poll. */
77export type ModalLock = {
78 ts: number
79 by: string
80}
81
82/** What `$.store` remembers under `project:<cwd>`: whether the project uses Modal, and when that was checked. */
83export type ModalProject = {
84 usesModal: boolean
85 checkedAt: number
86}
87
88declare module 'claude-code' {
89 interface PluginState {
90 'modal-meter': {
91 meter: ModalMeter
92 tracked: Record<string, ModalTracked>
93 /** The app whose Stop was pressed and now waits for Confirm. */
94 confirming: string | null
95 /** The app a confirmed stop is running for. */
96 stopping: string | null
97 /** The UTC day the budget toast was shown for. */
98 budgetDay: string | null
99 /** Whether this session reads Modal: the project uses it, the person asked, or alwaysPoll. */
100 watching: boolean
101 }
102 }
103}
104