Keeps Claude Code's long Monitor watches running past the 30-minute cap, so their expiry no longer wakes Claude or spends a turn

Claude Code stops every Monitor watch after at most 30 minutes and wakes Claude with a notice telling it to re-arm the watch. Claude then spends a turn, rereading the whole conversation, only to call Monitor again with the same input. Over an afternoon of watching a pull request or a log that adds up to a lot of turns that do nothing.
This plugin keeps the watch going itself. A minute before the watch would expire it stops it and starts the same watch again, with the same input, so the expiry notice is never sent. Claude is not woken, no tokens are spent, and nothing shows in the transcript. Events from the new watch reach Claude as before.
If a watch expires anyway (see below), the plugin re-arms it then and drops the notice, which leaves one dim line in the transcript:
⏺ ↻ re-armed PR checks (b5vptfscx)
Claude Code counts that as the session going idle again, so a minute later it sends its "Claude is waiting for your input" notification, which a terminal may show as an unread badge. The swap before expiry avoids both.
Only watches Claude asked for at the maximum, timeout_ms of 1800000 or more. Claude Code's own instructions tell Claude to use the maximum for a long watch and re-arm it on every expiry, which is what this does. Shorter watches expire as usual.
A watch re-armed for a whole day expires as usual too, so Claude gets to look at a watch that has been running, maybe quietly, for that long.
Watches started by subagents are left alone.
tail -f without -n 0, a script that reports status on its first pass) repeats that every 30 minutes, as it would when Claude re-arms it./tmp/monitor-rearm/<session id>, which the session watches; the file-change event runs the swap. Claude Code registers watched files when a session starts, so a session that was already running when you installed or updated the plugin falls back to re-arming on expiry until it is restarted. So does a watch whose swap was missed, for example while the machine slept.TaskStop with either id, the first one Claude saw or the one in the latest event, stops it.PostToolUse hooks in settings don't run for a re-arm or the TaskStop of a swapped watch. It is no work of Claude's, and a hook that shows the session as busy (a terminal status dot) would mark an idle session busy with no Stop to clear it.The re-arm is the plugin's call, not Claude's, whether it is a swap or a re-arm on expiry. In auto mode the classifier judges a call against the request Claude made it in, so for the plugin's call it has nothing to judge and gives no verdict, and a prompt in the other modes would ask you again about a command you already let run.
So the plugin approves its re-arm itself, and nothing else: only its own Monitor call, only while it re-arms a watch, and only with the exact command Claude's approved call started that watch with. Every other call, Claude's or another plugin's, gets the usual check. The plugin turns only a pending ask into an approval, so a deny rule still stops the re-arm.
A watch runs its command again on each re-arm, for up to a day. If the command is a script that changes on disk in that time, the new version runs without a fresh check.
Claude Code 2.1.289 or later, with function-hook mods available to your account.
/plugin marketplace add nnemirovsky/cc-monitor-rearm
/plugin install monitor-rearm@monitor-rearm
There is nothing to configure.
claude plugin validate .
claude plugin test .
claude --plugin-dir .
MIT
hooks/register.ts 227 lines1import type { EngineInterface, Register } from 'claude-code'
2
3// Claude Code stops every Monitor after at most 30 minutes and wakes Claude
4// with an expiry notice, which it answers by calling Monitor again: a turn
5// and a full context read just to keep a watch going. A watch asked for at
6// that maximum is meant to run on, so this mod keeps it going itself: a minute
7// before the watch would expire it stops it and starts the same watch again,
8// so no notice is sent and nothing shows in the session. Shorter watches
9// expire as usual, and so does a long one after a day, so Claude gets to look
10// at a watch that has stayed quiet for that long. A watch whose command
11// exited, or that Claude stopped, is not kept going.
12//
13// The swap runs on a timer, but a plugin's calls from a timer pass none of its
14// own hooks, so it could not approve its own Monitor call. So the timer only
15// writes a file the session watches (registered at SessionStart), and the swap
16// runs in the hook for the engine's FileChanged event.
17//
18// When the swap did not happen (a session started before the plugin was
19// installed, a machine asleep past the expiry), the expiry notice arrives: the
20// watch is re-armed then and the notice dropped, which leaves one row in the
21// transcript and counts as the session going idle again.
22//
23// Either way the re-arm is this plugin's call, not Claude's, so auto mode's
24// classifier has no request to judge it by and gives no verdict. The command
25// was approved when Claude started the watch, so the plugin approves its own
26// re-arm of it: only the exact command it recorded, only while it is
27// re-arming that watch.
28
29const LONG_MS = 1800000
30const DAY_MS = 86400000
31// How long before a watch would expire it is swapped for a fresh one.
32const LEAD_MS = 60000
33const PLUGIN = 'monitor-rearm'
34const REARMED = `${PLUGIN}: re-armed `
35
36// One <task-notification> carrying a Monitor's expiry notice; group 1 its task id.
37const EXPIRY = /<task-notification>\s*<task-id>([^<]+)<\/task-id>(?:(?!<\/task-notification>)[\s\S])*?\[Monitor expired after [^\]]*\](?:(?!<\/task-notification>)[\s\S])*<\/task-notification>\s*/g
38// One <task-notification> saying its task ended (only those carry a status:
39// the command exited, or the task was stopped); group 1 its task id.
40const ENDED = /<task-notification>\s*<task-id>([^<]+)<\/task-id>(?:(?!<\/task-notification>)[\s\S])*?<status>/g
41
42type Watch = { input: Record<string, unknown>; first: string; since: number; due: number }
43
44// Long watches by their current task id, and the current id of each watch by
45// the id Claude knows it by (its first).
46const watches = new Map<string, Watch>()
47const current = new Map<string, string>()
48
49// The command of the watch being re-armed right now, while its Monitor call runs.
50let rearming: string | undefined
51// The old task of a swapped watch, while the TaskStop call for it runs.
52let stopping: string | undefined
53// The file this session watches for the swap, once SessionStart registered it.
54let bell: string | undefined
55
56function taskId(res: { result?: unknown }): string | undefined {
57 const r = res.result as { taskId?: unknown; persistent?: boolean } | undefined
58 return typeof r?.taskId === 'string' && !r.persistent ? r.taskId : undefined
59}
60
61// Stops keeping the watch whose current task id this is.
62function forget(id: string) {
63 const watch = watches.get(id)
64 if (!watch) return
65 watches.delete(id)
66 current.delete(watch.first)
67}
68
69// Asks for the swap once a watch is due: the write fires FileChanged.
70function ring($: EngineInterface, ms: number) {
71 if (!bell) return
72 const path = bell
73 $.clock.after(ms, () => {
74 void $.clock
75 .now()
76 .then(now => $.fs.write(path, String(now)))
77 .catch(() => undefined)
78 })
79}
80
81// Starts the watch again with the same input; resolves its new task id, or
82// undefined once it is no longer kept (a day old, or the call failed).
83async function restart($: EngineInterface, id: string): Promise<string | undefined> {
84 const watch = watches.get(id)
85 if (!watch) return undefined
86 watches.delete(id)
87 const now = await $.clock.now()
88 if (now - watch.since >= DAY_MS) {
89 current.delete(watch.first)
90 return undefined
91 }
92 rearming = String(watch.input.command)
93 const res = await $.tool.call({ tool: 'Monitor', ...watch.input } as never).finally(() => {
94 rearming = undefined
95 })
96 const next = taskId(res)
97 if (!next) {
98 current.delete(watch.first)
99 return undefined
100 }
101 const timeout = Number(watch.input.timeout_ms)
102 watches.set(next, { ...watch, due: now + timeout - LEAD_MS })
103 current.set(watch.first, next)
104 ring($, timeout - LEAD_MS)
105 return next
106}
107
108// Stops every watch that is due and starts it again: the old one never
109// expires, so no notice is sent. A watch whose command already exited (a PR
110// merged, a build done) cannot be stopped and is not started again, or it
111// would report its last state anew.
112async function swap($: EngineInterface) {
113 const now = await $.clock.now()
114 for (const [id, watch] of [...watches]) {
115 if (watch.due > now + 1000 || now - watch.since >= DAY_MS) continue
116 stopping = id
117 const res = await $.tool.call({ tool: 'TaskStop', task_id: id } as never).finally(() => {
118 stopping = undefined
119 })
120 if (res.deny !== undefined || res.isError) {
121 forget(id)
122 continue
123 }
124 if (await restart($, id)) continue
125 // A FileChanged hook may not submit a prompt (it could wait on the turn the
126 // hook holds), so it is sent once the hook is done.
127 const text = `${PLUGIN} stopped the watch "${String(watch.input.description ?? 'Monitor')}" (${watch.first}) to restart it before it expired, but could not start it again. Start it again if it is still needed.`
128 $.clock.after(0, () => {
129 void $.prompt.submit({ text }).catch(() => undefined)
130 })
131 }
132}
133
134export const register: Register = on => {
135 // Have the session watch this plugin's file, so its timer can reach a hook.
136 on('classic.SessionStart', async ($, e, next) => {
137 const res = await next(e)
138 const path = `/tmp/${PLUGIN}/${e.session_id}`
139 try {
140 await $.fs.write(path, '')
141 } catch {
142 return res
143 }
144 bell = path
145 return { ...res, watchPaths: [...(res.watchPaths ?? []), path] }
146 })
147
148 on('classic.FileChanged', async ($, e, next) => {
149 if (!bell || e.file_path !== bell) return next(e)
150 await swap($).catch(() => undefined)
151 return {}
152 })
153
154 // Remember each long watch the main conversation starts.
155 on('tool.call', { tool: 'Monitor' }, async ($, e, next) => {
156 const res = await next(e)
157 const { tool, tool_use_id, consent, agentId, ...input } = e as unknown as Record<string, unknown>
158 const id = taskId(res)
159 const timeout = Number(input.timeout_ms)
160 if (id && !agentId && rearming === undefined && timeout >= LONG_MS) {
161 const now = await $.clock.now()
162 watches.set(id, { input, first: id, since: now, due: now + timeout - LEAD_MS })
163 ring($, timeout - LEAD_MS)
164 }
165 return res
166 })
167
168 // Approve this plugin's own re-arm: its call, the command it is re-arming.
169 // Only an ask turns into an allow, so a deny rule still stops it.
170 on('tool.check', { tool: 'Monitor' }, async ($, e, next) => {
171 const verdict = await next(e)
172 const command = (e.input as { command?: unknown } | undefined)?.command
173 const ours = rearming !== undefined && e.tool_use_id && next.origin.plugin === PLUGIN && command === rearming
174 if (!ours || verdict.decision !== 'ask') return verdict
175 return { decision: 'allow', reason: `${PLUGIN} re-arms a watch Claude started` }
176 })
177
178 // A re-arm is no work of Claude's, so the settings PostToolUse hooks don't hear
179 // of it: a status hook would mark the idle session busy, with no Stop to follow.
180 function ours(e: { tool_name: string; tool_input: unknown }): boolean {
181 const input = e.tool_input as { command?: unknown; task_id?: unknown } | undefined
182 if (rearming !== undefined && e.tool_name === 'Monitor' && input?.command === rearming) return true
183 return stopping !== undefined && e.tool_name === 'TaskStop' && input?.task_id === stopping
184 }
185 on('classic.PostToolUse', async ($, e, next) => (ours(e) ? {} : next(e)))
186 on('classic.PostToolUseFailure', async ($, e, next) => (ours(e) ? {} : next(e)))
187
188 // Claude still knows a re-armed watch by its first task id, and its events
189 // name the current one: either stops it.
190 on('tool.call', { tool: 'TaskStop' }, async ($, e, next) => {
191 if (stopping !== undefined) return next(e)
192 const asked = (e as unknown as { task_id?: string }).task_id
193 if (!asked) return next(e)
194 const now = current.get(asked) ?? asked
195 forget(now)
196 return now === asked ? next(e) : next({ ...e, task_id: now } as typeof e)
197 })
198
199 // The expiry notice of a watch that was not swapped in time: re-arm it and
200 // take the notice out, so no turn starts for it. A watch that ended on its
201 // own is not kept any longer.
202 on('prompt.submit', { origin: { kind: 'task-notification' } }, async ($, e, next) => {
203 for (const m of e.text.matchAll(ENDED)) forget(m[1]!)
204 if (!e.text.includes('[Monitor expired after')) return next(e)
205 const names: string[] = []
206 let kept = e.text
207 for (const m of e.text.matchAll(EXPIRY)) {
208 const watch = watches.get(m[1]!)
209 if (!(await restart($, m[1]!)) || !watch) continue
210 names.push(`${String(watch.input.description ?? 'Monitor')} (${watch.first})`)
211 kept = kept.replace(m[0], '')
212 }
213 if (names.length === 0) return next(e)
214 if (kept.trim()) return next({ ...e, text: kept })
215 return { drop: REARMED + names.join(', ') }
216 })
217
218 // The engine notes the dropped notice in the transcript; say what happened instead.
219 on('session.append', { door: 'notice' }, async ($, e, next) => {
220 const content = e.message.content
221 const text = typeof content === 'string' ? content : content.map(b => ('text' in b ? b.text : '')).join('')
222 const at = text.indexOf(REARMED)
223 if (at < 0) return next(e)
224 const line = `↻ re-armed ${text.slice(at + REARMED.length)}`
225 return next({ ...e, message: { ...e.message, content: [{ type: 'text', text: line }] } } as typeof e)
226 })
227}