Tells you when a scheduled routine (a scheduled-task run) stops to wait on you: a Mac notification, an optional phone push and a status line once a permission…

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.ts 367 lines1import type { EngineInterface, Register, Timer } from 'claude-code'
2
3import type { RoutineRun, RoutineSession, RoutineSettings } from '../types'
4import {
5 commandArgv,
6 describeCall,
7 describeRun,
8 detectRoutine,
9 finishMessage,
10 firstQuestion,
11 oldestWait,
12 osascriptArgv,
13 statusLine,
14} from './routine'
15
16type Engine = EngineInterface
17
18const SESSION = { plugin: 'routine-watch', key: 'session' } as const
19const UNDECIDED: RoutineSession = { isDecided: false, run: null }
20
21/** The read-only web tools `allowWebReads` lets a routine run without asking; nothing else. */
22const WEB_READS = new Set(['WebFetch', 'WebSearch'])
23/** Prompts that never count as the session's first: machine-injected ones. */
24const NOT_FIRST = new Set(['plugin', 'task-notification', 'observer', 'observer-activity'])
25/** How often the status line's "waiting on you" time is refreshed. */
26const TICK_MS = 15_000
27/** How long a notification command may take. */
28const NOTIFY_TIMEOUT_MS = 15_000
29/** How long a permission ask stands before the person is told, in seconds, when the option is unset or invalid. */
30const WAIT_TOAST_AFTER_S = 20
31
32let config: RoutineSettings = {
33 notifyMac: true,
34 allowWebReads: false,
35 notifyCommand: '',
36 notifyOnFinish: true,
37 waitToastAfterSeconds: WAIT_TOAST_AFTER_S,
38}
39/**
40 * What the session is, kept here and changed synchronously so concurrent hooks
41 * never race; mirrored to `$.state` only so a hot reload can pick it up again.
42 * (A dispatch's `$.state.get` reads one moment, so a hook that waits on a tool
43 * could not see a wait another hook opened meanwhile.)
44 */
45let memory: RoutineSession = UNDECIDED
46let restoring: Promise<void> | null = null
47let ticker: { cancel: () => void } | null = null
48/** The timers that will tell the person of a wait still open when its time comes, by tool_use_id. */
49let pending = new Map<string, Timer>()
50/** The status line last shown, so an unchanged line is not set again. */
51let shownStatus: string | undefined = undefined
52
53async function debug($: Engine, line: string) {
54 try {
55 await $.ui.log(`routine-watch: ${line}`, { to: 'debug' })
56 } catch {
57 // The debug log is best effort.
58 }
59}
60
61async function restore($: Engine) {
62 try {
63 const { value } = await $.state.get(SESSION)
64 if (value && !memory.isDecided) {
65 memory = value
66 if (value.run) {
67 await rearm($, value.run)
68 }
69 }
70 } catch (error) {
71 await debug($, `could not restore the session: ${String(error)}`)
72 }
73}
74
75/** A reload drops a run's timers: arms them again, for the waits not told of yet and for the status line. */
76async function rearm($: Engine, run: RoutineRun) {
77 const now = await $.clock.now()
78 for (const [id, wait] of Object.entries(run.waiting)) {
79 // Strict: a wait kept by an older version, with no flag, was told of at once.
80 if (wait.isTold === false) {
81 tellLater($, id, wait.since + config.waitToastAfterSeconds * 1000 - now)
82 }
83 }
84 if (oldestWait(run)) {
85 ensureTicker($)
86 }
87}
88
89/** The session as known, restored once after a reload. */
90async function load($: Engine): Promise<RoutineSession> {
91 restoring ??= restore($)
92 await restoring
93 return memory
94}
95
96/** Takes the new value at once, then mirrors it for a reload. */
97async function save($: Engine, value: RoutineSession) {
98 memory = value
99 try {
100 await $.state.set(SESSION, value)
101 } catch (error) {
102 await debug($, `could not keep the session: ${String(error)}`)
103 }
104}
105
106async function currentRun($: Engine): Promise<RoutineRun | null> {
107 return (await load($)).run
108}
109
110async function showStatus($: Engine) {
111 const run = await currentRun($)
112 const line = run ? statusLine(run, await $.clock.now()) : undefined
113 if (line !== shownStatus) {
114 shownStatus = line
115 $.ui.status(line)
116 }
117}
118
119function stopTicker() {
120 ticker?.cancel()
121 ticker = null
122}
123
124async function tick($: Engine) {
125 await showStatus($)
126 const run = await currentRun($)
127 if (!run || !oldestWait(run)) {
128 stopTicker()
129 }
130}
131
132function ensureTicker($: Engine) {
133 if (!ticker) {
134 ticker = $.clock.every(TICK_MS, () => void tick($))
135 }
136}
137
138/** Runs one notification command; a failure goes to the debug log, never to the routine. */
139async function runQuietly($: Engine, argv: readonly string[]) {
140 try {
141 const out = await $.process.run(argv, { timeoutMs: NOTIFY_TIMEOUT_MS })
142 if (out.exitCode !== 0) {
143 await debug($, `${argv[0] ?? 'command'} exited ${out.exitCode}: ${out.stderr.trim().slice(0, 200)}`)
144 }
145 } catch (error) {
146 await debug($, `${argv[0] ?? 'command'} failed: ${String(error)}`)
147 }
148}
149
150/** The Mac notification and the person's push command, run side by side. */
151async function sendOut($: Engine, run: RoutineRun, message: string) {
152 const title = `Claude routine: ${run.name}`
153 const jobs: Promise<void>[] = []
154 if (config.notifyMac) {
155 jobs.push(runQuietly($, osascriptArgv(title, message)))
156 }
157 const push = commandArgv(config.notifyCommand, { title, message })
158 if (push) {
159 jobs.push(runQuietly($, push))
160 }
161 await Promise.all(jobs)
162}
163
164/**
165 * Tells the person: a toast now, and the notifications in the background, so
166 * the dialog the routine waits on is never held up by them.
167 */
168function notify($: Engine, run: RoutineRun, message: string) {
169 $.ui.toast(message, { timeoutMs: 10_000 })
170 void sendOut($, run, message)
171}
172
173/** Tells the person of a wait still open, once, and counts it; from then on the status line shows it. */
174async function tell($: Engine, id: string) {
175 pending.delete(id)
176 const { run } = await load($)
177 const wait = run?.waiting[id]
178 if (!run || !wait || wait.isTold) {
179 return
180 }
181 const told: RoutineRun = { ...run, waits: run.waits + 1, waiting: { ...run.waiting, [id]: { ...wait, isTold: true } } }
182 await save($, { ...memory, run: told })
183 ensureTicker($)
184 await showStatus($)
185 notify($, told, wait.message)
186}
187
188/** Tells the person of the wait in `inMs` milliseconds, unless it closes first. */
189function tellLater($: Engine, id: string, inMs: number) {
190 pending.get(id)?.cancel()
191 pending.set(id, $.clock.after(Math.max(0, inMs), () => void tell($, id)))
192}
193
194/** Stops the timers of the waits named (every one when none are named), so a closed wait is never told of. */
195function forget(ids?: readonly string[]) {
196 for (const [id, timer] of pending) {
197 if (!ids || ids.includes(id)) {
198 timer.cancel()
199 pending.delete(id)
200 }
201 }
202}
203
204/**
205 * Opens a wait for one tool call. A question is told of at once; a permission
206 * ask only once it has stood `afterMs`, since in auto mode the engine decides
207 * most asks by itself within seconds, and those are no wait on the person.
208 */
209async function beginWait($: Engine, id: string, label: string, message: string, afterMs: number) {
210 const now = await $.clock.now()
211 const { run } = await load($)
212 if (!run || run.waiting[id] !== undefined) {
213 return
214 }
215 const waiting = { ...run.waiting, [id]: { since: now, label, message, isTold: false } }
216 await save($, { ...memory, run: { ...run, waiting } })
217 if (afterMs > 0) {
218 tellLater($, id, afterMs)
219 } else {
220 await tell($, id)
221 }
222}
223
224/** Closes the waits named (every open one when none are named). */
225async function endWaits($: Engine, ids?: readonly string[]) {
226 const { run } = await load($)
227 forget(ids)
228 const open = run ? Object.keys(run.waiting) : []
229 const closing = ids ? open.filter(id => ids.includes(id)) : open
230 if (!run || closing.length === 0) {
231 return
232 }
233 const waiting = { ...run.waiting }
234 for (const id of closing) {
235 delete waiting[id]
236 }
237 await save($, { ...memory, run: { ...run, waiting } })
238 await showStatus($)
239}
240
241export const register: Register = (on, options) => {
242 const seconds = options.waitToastAfterSeconds
243 config = {
244 notifyMac: options.notifyMac !== false,
245 allowWebReads: options.allowWebReads === true,
246 notifyCommand: typeof options.notifyCommand === 'string' ? options.notifyCommand : '',
247 notifyOnFinish: options.notifyOnFinish !== false,
248 waitToastAfterSeconds: typeof seconds === 'number' && Number.isFinite(seconds) && seconds >= 0 ? seconds : WAIT_TOAST_AFTER_S,
249 }
250 memory = UNDECIDED
251 restoring = null
252 ticker = null
253 pending = new Map()
254 shownStatus = undefined
255
256 on('session.start', async ($, e, next) => {
257 // Not awaited: a run a reload interrupted gets its timers back without holding the start up.
258 void load($)
259 await $.command.register({
260 name: 'routine',
261 description: 'This routine run: its name, when it started, how often it waited on you, the settings',
262 immediate: true,
263 })
264 return next(e)
265 })
266
267 // The session's first prompt decides whether it is a routine run.
268 on('prompt.submit', async ($, e, next) => {
269 try {
270 const known = await load($)
271 if (!known.isDecided && !NOT_FIRST.has(e.origin.kind)) {
272 const name = detectRoutine(e.text, e.origin.kind)
273 const now = await $.clock.now()
274 if (!memory.isDecided) {
275 await save($, { isDecided: true, run: name ? { name, startedAt: now, waits: 0, waiting: {} } : null })
276 if (name) {
277 await showStatus($)
278 }
279 }
280 }
281 } catch (error) {
282 await debug($, `could not read the first prompt: ${String(error)}`)
283 }
284 return next(e)
285 })
286
287 // A permission ask in a routine is a run stopped until the person answers.
288 on('tool.check', async ($, e, next) => {
289 const verdict = await next(e)
290 if (verdict.decision !== 'ask') {
291 return verdict
292 }
293 const run = await currentRun($)
294 if (!run) {
295 return verdict
296 }
297 if (config.allowWebReads && WEB_READS.has(e.tool)) {
298 return { decision: 'allow', reason: 'routine-watch: web reads are allowed in routine runs (allowWebReads)' }
299 }
300 // A query (`$.tool.check`) carries no call id: nothing waits on it.
301 if (e.tool_use_id !== undefined) {
302 const label = describeCall(e.tool, e.input)
303 await beginWait($, e.tool_use_id, label, `Waiting for your OK: ${label}`, config.waitToastAfterSeconds * 1000)
304 }
305 return verdict
306 })
307
308 // A question for the person stops the routine too; every call's end closes its wait.
309 on('tool.call', async ($, e, next) => {
310 const id = e.tool_use_id
311 const run = await currentRun($)
312 if (!run || id === undefined) {
313 return next(e)
314 }
315 if (e.tool === 'AskUserQuestion') {
316 await beginWait($, id, 'AskUserQuestion', `Question for you: ${firstQuestion(e)}`, 0)
317 }
318 try {
319 return await next(e)
320 } finally {
321 await endWaits($, [id])
322 }
323 })
324
325 on('turn.complete', async ($, e, next) => {
326 const done = await next(e)
327 if (e.agentId === undefined) {
328 const run = await currentRun($)
329 if (run) {
330 await endWaits($)
331 if (e.reason === 'error') {
332 notify($, run, 'The run stopped: its turn ended on an error.')
333 }
334 }
335 }
336 return done
337 })
338
339 on('session.end', async ($, e, next) => {
340 const { isDecided, run } = await load($)
341 if (run) {
342 stopTicker()
343 forget()
344 if (config.notifyOnFinish) {
345 const message = finishMessage(run, await $.clock.now())
346 $.ui.toast(message)
347 // Awaited: the session's end allows its hooks a short while, and the notice should land in it.
348 await sendOut($, run, message)
349 }
350 }
351 // A /clear goes on in this process as a fresh conversation, decided again by its first prompt.
352 if (isDecided) {
353 await save($, UNDECIDED)
354 }
355 if (shownStatus !== undefined) {
356 shownStatus = undefined
357 $.ui.status(undefined)
358 }
359 return next(e)
360 })
361
362 on('command.run', { command: 'routine' }, async $ => {
363 const run = await currentRun($)
364 return { text: describeRun(run, config, await $.clock.now()) }
365 })
366}
367hooks/routine.ts 185 lines1import type { RoutineRun, RoutineSettings, RoutineWait } from '../types'
2
3/** The name a routine gets when its prompt carries no name of its own. */
4export const UNNAMED = 'scheduled task'
5
6const TAG = /<scheduled-task\b/
7const NAME = /<scheduled-task\b[^>]*?\bname\s*=\s*(?:"([^"]*)"|'([^']*)')/
8
9const ENTITIES: Record<string, string> = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", '#39': "'" }
10
11/** Control characters (C0, DEL) and the Unicode line and paragraph separators. */
12const isControl = (code: number): boolean => code < 0x20 || code === 0x7f || code === 0x2028 || code === 0x2029
13
14/** Collapses runs of whitespace and control characters to one space. */
15const oneLine = (text: string): string =>
16 Array.from(text, char => (isControl(char.charCodeAt(0)) ? ' ' : char))
17 .join('')
18 .replace(/\s+/g, ' ')
19 .trim()
20
21/** Cuts text to `max` characters, marking the cut with an ellipsis. */
22export const clip = (text: string, max: number): string => (text.length <= max ? text : `${text.slice(0, max - 1)}…`)
23
24/**
25 * The routine's name when `text` is a scheduled task's prompt
26 * (`<scheduled-task name="daily-report" file="…">`), else null. A tag with no
27 * name is still a routine, called "scheduled task".
28 */
29export const routineName = (text: string): string | null => {
30 if (!TAG.test(text)) {
31 return null
32 }
33 const match = NAME.exec(text)
34 const raw = match?.[1] ?? match?.[2] ?? ''
35 const name = oneLine(raw.replace(/&(amp|lt|gt|quot|apos|#39);/g, (_all, entity: string) => ENTITIES[entity] ?? ''))
36 return name ? clip(name, 60) : UNNAMED
37}
38
39/**
40 * Whether the session's first prompt starts a routine, and its name: the
41 * scheduled-task tag in the text, or else a prompt the engine says a schedule
42 * fired (`scheduled-trigger`).
43 */
44export const detectRoutine = (text: string, originKind: string): string | null =>
45 routineName(text) ?? (originKind === 'scheduled-trigger' ? UNNAMED : null)
46
47/**
48 * `text` as an AppleScript string literal: backslashes and double quotes
49 * escaped, control characters and line breaks turned into spaces.
50 */
51export const appleScriptString = (text: string): string =>
52 `"${oneLine(text).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
53
54/** The argv that posts a macOS notification with a sound; argv, so no shell reads it. */
55export const osascriptArgv = (title: string, message: string): string[] => [
56 'osascript',
57 '-e',
58 `display notification ${appleScriptString(clip(message, 240))} with title ${appleScriptString(clip(title, 100))} sound name "Glass"`,
59]
60
61/**
62 * The argv for the person's push command: the template split on whitespace,
63 * then `{title}` and `{message}` filled into the words that name them, so each
64 * value stays inside one argument whatever it holds. Null when no command is set.
65 */
66export const commandArgv = (template: string, values: { title: string; message: string }): string[] | null => {
67 const words = template.trim().split(/\s+/).filter(word => word !== '')
68 if (words.length === 0) {
69 return null
70 }
71 return words.map(word =>
72 word.replace(/\{(title|message)\}/g, (_all, key: string) => (key === 'title' ? values.title : values.message)),
73 )
74}
75
76/** The host a URL names, without `www.`; the URL itself, cut short, when it names none. */
77export const hostOf = (url: string): string => {
78 const match = /^[a-z][a-z0-9+.-]*:\/\/(?:[^@/?#]*@)?(\[[^\]]*\]|[^:/?#]*)/i.exec(url.trim())
79 const host = match?.[1]?.toLowerCase().replace(/^www\./, '') ?? ''
80 return host || clip(oneLine(url), 60)
81}
82
83const fileName = (path: string): string => path.replace(/\/+$/, '').split('/').pop() || path
84
85const field = (input: unknown, key: string): string | null => {
86 if (typeof input !== 'object' || input === null) {
87 return null
88 }
89 const value = (input as Record<string, unknown>)[key]
90 return typeof value === 'string' && value.trim() !== '' ? value : null
91}
92
93/** A short label for a tool call: the tool and what it touches (`WebFetch example.com`). */
94export const describeCall = (tool: string, input: unknown): string => {
95 const url = field(input, 'url')
96 const query = field(input, 'query')
97 const command = field(input, 'command')
98 const path = field(input, 'file_path') ?? field(input, 'notebook_path') ?? field(input, 'path')
99 const detail = url
100 ? hostOf(url)
101 : query
102 ? `"${clip(oneLine(query), 60)}"`
103 : command
104 ? clip(oneLine(command), 60)
105 : path
106 ? fileName(path)
107 : ''
108 return detail ? `${tool} ${detail}` : tool
109}
110
111/** The first question an AskUserQuestion call puts to the person, cut short. */
112export const firstQuestion = (input: unknown): string => {
113 const questions = typeof input === 'object' && input !== null ? (input as { questions?: unknown }).questions : undefined
114 const first: unknown = Array.isArray(questions) ? questions[0] : undefined
115 const text = field(first, 'question')
116 return text ? clip(oneLine(text), 120) : 'a question'
117}
118
119/** A duration as people say it: `45s`, `23m`, `1h05m`. */
120export const formatDuration = (ms: number): string => {
121 const seconds = Math.max(0, Math.floor(ms / 1000))
122 if (seconds < 60) {
123 return `${seconds}s`
124 }
125 const minutes = Math.floor(seconds / 60)
126 if (minutes < 60) {
127 return `${minutes}m`
128 }
129 return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}m`
130}
131
132/** The open wait the person has been told of that began first, or null. */
133export const oldestWait = (run: RoutineRun): RoutineWait | null => {
134 let oldest: RoutineWait | null = null
135 for (const wait of Object.values(run.waiting)) {
136 if (wait.isTold && (!oldest || wait.since < oldest.since)) {
137 oldest = wait
138 }
139 }
140 return oldest
141}
142
143/** `routine: <name>`, or `routine: <name> · waiting on you 3m` while a wait the person has been told of is open. */
144export const statusLine = (run: RoutineRun, now: number): string => {
145 const wait = oldestWait(run)
146 if (!wait) {
147 return `routine: ${run.name}`
148 }
149 const waited = now - wait.since
150 return `routine: ${run.name} · waiting on you ${waited < 60_000 ? '<1m' : formatDuration(waited)}`
151}
152
153const times = (count: number): string => (count === 1 ? '1 time' : `${count} times`)
154
155/** The notification a routine's end sends: how long it ran and how often it waited on the person. */
156export const finishMessage = (run: RoutineRun, now: number): string =>
157 `Routine ${run.name} finished after ${formatDuration(now - run.startedAt)} · ` +
158 (run.waits === 0 ? 'never waited on you' : `waited on you ${times(run.waits)}`)
159
160/** The settings as one line, the push command's text left out (it may carry a private topic). */
161export const describeSettings = (settings: RoutineSettings): string =>
162 [
163 `Mac notifications ${settings.notifyMac ? 'on' : 'off'}`,
164 settings.allowWebReads ? 'web reads allowed (allowWebReads on)' : 'web reads ask (allowWebReads off)',
165 `phone push ${settings.notifyCommand.trim() ? 'on' : 'off'}`,
166 `finish notice ${settings.notifyOnFinish ? 'on' : 'off'}`,
167 settings.waitToastAfterSeconds > 0 ? `waits notify after ${settings.waitToastAfterSeconds}s` : 'waits notify at once',
168 ].join(' · ')
169
170/** What /routine prints. */
171export const describeRun = (run: RoutineRun | null, settings: RoutineSettings, now: number): string => {
172 const settingsLine = `Settings: ${describeSettings(settings)}`
173 if (!run) {
174 return ['Not a routine session: routine-watch acts only in scheduled-task runs.', settingsLine].join('\n')
175 }
176 const wait = oldestWait(run)
177 const waits = run.waits === 0 ? 'Has not waited on you' : `Waited on you ${times(run.waits)}`
178 return [
179 `Routine: ${run.name}`,
180 `Started ${formatDuration(now - run.startedAt)} ago`,
181 wait ? `${waits} · waiting now for ${formatDuration(now - wait.since)}: ${wait.label}` : waits,
182 settingsLine,
183 ].join('\n')
184}
185types/index.d.ts 50 lines1/** One tool call the routine is stopped on: a permission ask or a question for the person. */
2export type RoutineWait = {
3 /** When the wait began, in `$.clock.now()` milliseconds. */
4 since: number
5 /** What it waits on, e.g. `WebFetch example.com`. */
6 label: string
7 /** What the person is told when the wait counts, e.g. `Waiting for your OK: WebFetch example.com`. */
8 message: string
9 /**
10 * Whether the person has been told, and the wait counted: at once for a
11 * question, after `waitToastAfterSeconds` for a permission ask, which the
12 * engine may still decide by itself before then.
13 */
14 isTold: boolean
15}
16
17/** A scheduled-task run in progress in this session. */
18export type RoutineRun = {
19 /** The task's name, from `<scheduled-task name="…">`. */
20 name: string
21 /** When the routine's first prompt arrived. */
22 startedAt: number
23 /** How many times it has stopped to wait on the person: the waits told of. */
24 waits: number
25 /** The waits still open, by tool_use_id, told of or not yet. */
26 waiting: Record<string, RoutineWait>
27}
28
29/** What the session is: undecided until its first prompt, then a routine run or not. */
30export type RoutineSession = {
31 isDecided: boolean
32 run: RoutineRun | null
33}
34
35/** The plugin's settings, as /routine describes them. */
36export type RoutineSettings = {
37 notifyMac: boolean
38 allowWebReads: boolean
39 notifyCommand: string
40 notifyOnFinish: boolean
41 /** How long a permission ask stands before the person is told, in seconds; 0 tells at once. */
42 waitToastAfterSeconds: number
43}
44
45declare module 'claude-code' {
46 interface PluginState {
47 'routine-watch': { session: RoutineSession }
48 }
49}
50