Senses Claude Code idle time, running work, user return, and still-waiting permission prompts for Meridian through `meridian idle`.

A Claude Code mod that tells Meridian when a session goes idle, what work the turn left running, and when the user comes back. Meridian decides what to do about it: a push notification, and a warning that the prompt cache is about to expire. The mod only senses and runs the timers Meridian places.
Every meridian idle command below carries --interactive; the table omits that common flag for readability.
| Claude hook | Meridian call | Why | |
|---|---|---|---|
session.start (TUI only) | meridian idle config --harness claude | Stays inert unless the role gate and the config say enabled. Under claude -p (isInteractive === false, no surface) it never calls Meridian. | |
session.start, after a reload or resume | meridian idle status --json | Rebuilds timers from the stored schedule of this session's open stretch, skipping stages already done. | |
turn.complete without agentId | meridian idle arm --harness claude --session <id> [--background-tasks=<json>] [--user-text=...] [--assistant-text=...] | A main-loop turn ended. Core resolves the recorded native transcript store through the inherited MERIDIAN_CHAT_ID; the mod never derives it from the session's mutable cwd. The mod sends the last composer prompt and the event's answer as notification excerpts; injected origins and system reminders are excluded. --background-tasks forwards a bounded prefix of the background_tasks from the classic.Stop that precedes the turn's end, each as {kind, command?}: subagents and workflows are agent, monitors watcher, and shells are shell when their full command fits the bound or other otherwise. Core alone decides what they mean: it holds the push while work that wakes the session runs (that turn arms again), delays it for other tasks, and drops the warning when a spawn wait yields before the cache goes cold. A new or re-anchored schedule returns absolute push_at / warn_at (and push_held with the reason, for the log); an absorbed arm keeps matching timers or recovers them from status. | |
classic.Notification with notification_type = "permission_prompt" | meridian idle needs-permission --harness claude --message <text> | Claude reports that a main-loop or background-subagent permission prompt is still unanswered. Meridian forwards one stateless notify.needs_permission notice; other notification types are ignored. | |
prompt.submit or command.run with origin composer (or bridge, the user's phone) | meridian idle return --harness claude --session <id> --user-prompt | The user is back. Timers are cancelled first, synchronously. | |
| timer: push, warn | `meridian idle fire push\ | warn …` | Core sends the notification itself. The mod only reports that the timer fired. |
Injected prompts (task-notification, peer, plugin, sdk, scheduled triggers, Stop-hook continuations) are not returns.
The mod never sends a notification, reads Meridian config files or MERIDIAN_* variables, writes under ~/.meridian, or prints to the terminal. Its own diagnostics live in the plugin's $.store under the key log (last 100 lines).
/meridian-idlePrints the current stretch, anchor, time left on each timer and the last log lines. It does not count as a return.
meridian claude adds --plugin-dir for interactive launches by itself, and sets MERIDIAN_SESSION_ROLE. To use the mod in a Claude session started outside Meridian, with meridian on PATH:
CLAUDE_CODE_PLUGIN_DIRS=$(meridian idle mod-path) claude
Outside Meridian the role is unset and the mod asserts --interactive itself, so only a TUI session ever arms.
claude plugin validate src/meridian/claude_runtime/meridian-idle
claude plugin test src/meridian/claude_runtime/meridian-idle
The module is plain TypeScript the host runs directly: no build step, no dependencies. hooks/register.test.ts covers each hook path against a fake meridian idle and a fake host.
Claude Code lays build-specific type files into any plugin directory it loads with --plugin-dir or CLAUDE_CODE_PLUGIN_DIRS: .claude-plugin/types/** (about 800 KB, different per Claude version, with its own .gitignore) and a 56-byte tsconfig.json that extends it. The repo ignores .claude-plugin/types/ and the wheel excludes it; tsconfig.json is committed because it is tiny and never changes. Claude also loads the mod fine from a read-only directory (an installed wheel it cannot write to), so the launcher does not copy the mod.
hooks/register.ts 476 lines1import type { ClassicHookInputs, EngineInterface, Register, Timer } from 'claude-code'
2
3// Meridian's Claude idle sensor.
4//
5// This module senses three things and hands every decision to `meridian idle`:
6// idle a main-loop turn finished -> `idle arm` with the work still running, then one timer per stage
7// return the user typed or sent something -> `idle return`, timers cancelled
8// permission Claude still awaits approval -> `idle needs-permission`, with no state change
9// Notifications belong to core; this file never sends one, reads
10// meridian config or env, or writes under `~/.meridian`. Nothing here writes to the terminal: diagnostics go to the
11// plugin's own `$.store` key `log`, and `/meridian-idle` prints them on request.
12
13type Stage = 'push' | 'warn'
14
15const STAGES: readonly Stage[] = ['push', 'warn']
16const HARNESS = 'claude'
17const COMMAND = 'meridian-idle'
18const CLI_TIMEOUT_MS = 20_000
19const LOG_LIMIT = 100
20const EXCERPT_CHAR_CAP = 4_000
21// One JSON argv entry stays below ~50 KiB even if every command code unit needs
22// JSON's longest escape, well clear of Linux's 128 KiB per-argument limit.
23const BACKGROUND_TASK_LIMIT = 16
24const BACKGROUND_COMMAND_CHAR_CAP = 512
25
26type Json = Record<string, unknown>
27type BackgroundTask = NonNullable<ClassicHookInputs['Stop']['background_tasks']>[number]
28
29/** One open stretch as the mod knows it: the ids `fire` needs, and the absolute stage times. */
30type Armed = {
31 session: string
32 stretch: number
33 anchor: number
34 at: Partial<Record<Stage, number>>
35 /** What core answered when each stage's timer fired, for `/meridian-idle`. */
36 fired: Partial<Record<Stage, string>>
37}
38
39type State = {
40 /** Print mode or no surface: the whole session is ignored. */
41 inert: boolean
42 /** Memoised `idle config --interactive` verdict. */
43 gate: Promise<boolean> | undefined
44 armed: Armed | undefined
45 timers: Timer[]
46 /** Bumped by every user return. Async work compares it to detect that the user came back meanwhile. */
47 epoch: number
48 /** An `arm` reached core since the last `return`, so a `return` call has something to close. */
49 mayBeOpen: boolean
50 /** Serialises the short `meridian idle` calls so arm/return/fire reach core in hook order. */
51 queue: Promise<unknown>
52 log: string[]
53 /** Last prompt typed by the human; tool results and injected hook turns never enter here. */
54 lastUserText: string | undefined
55 /** The main loop's in-flight background work, from the `Stop` that precedes its `turn.complete`. */
56 stopTasks: BackgroundTask[] | undefined
57}
58
59function newState(): State {
60 return {
61 inert: false,
62 gate: undefined,
63 armed: undefined,
64 timers: [],
65 epoch: 0,
66 mayBeOpen: false,
67 queue: Promise.resolve(),
68 log: [],
69 lastUserText: undefined,
70 stopTasks: undefined,
71 }
72}
73
74// -- small helpers ---------------------------------------------------------
75
76function describeError(err: unknown): string {
77 if (err instanceof Error) return err.message
78 return String(err)
79}
80
81function isRecord(value: unknown): value is Json {
82 return typeof value === 'object' && value !== null && !Array.isArray(value)
83}
84
85function asNumber(value: unknown): number | undefined {
86 return typeof value === 'number' && Number.isFinite(value) ? value : undefined
87}
88
89function capExcerpt(value: string | undefined): string | undefined {
90 return value?.slice(0, EXCERPT_CHAR_CAP)
91}
92
93/** A prompt or command the user themselves sent. Injected origins (task-notification, peer, plugin, sdk, ...) are not returns. */
94function isUserOrigin(origin: { kind: string } | undefined): boolean {
95 return origin?.kind === 'composer' || origin?.kind === 'bridge'
96}
97
98function note($: EngineInterface, s: State, line: string): void {
99 s.log.push(`${new Date().toISOString()} ${line}`)
100 if (s.log.length > LOG_LIMIT) s.log.splice(0, s.log.length - LOG_LIMIT)
101 $.store.set('log', s.log).catch(() => undefined)
102}
103
104function cancelTimers(s: State): void {
105 for (const timer of s.timers) timer.cancel()
106 s.timers = []
107}
108
109function enqueue(s: State, task: () => Promise<unknown>): Promise<unknown> {
110 const run = s.queue.then(task).catch(() => undefined)
111 s.queue = run
112 return run
113}
114
115/** Runs `meridian idle <args>` in the session's environment and returns the parsed stdout (a JSON object or array). Never throws. */
116async function cli($: EngineInterface, s: State, args: string[]): Promise<unknown> {
117 try {
118 const out = await $.process.run(['meridian', 'idle', ...args, '--interactive'], { timeoutMs: CLI_TIMEOUT_MS })
119 const text = out.stdout.trim()
120 if (text === '') return { error: `no output (exit ${out.exitCode}): ${out.stderr.trim().slice(0, 200)}` }
121 try {
122 return JSON.parse(text)
123 } catch {
124 return { error: `unparseable output (exit ${out.exitCode}): ${text.slice(0, 200)}` }
125 }
126 } catch (err) {
127 return { error: describeError(err) }
128 }
129}
130
131/** The error text of a `cli` result, or undefined when it succeeded. */
132function failure(reply: unknown): string | undefined {
133 if (!isRecord(reply)) return Array.isArray(reply) ? undefined : 'unexpected reply'
134 return typeof reply.error === 'string' ? reply.error : undefined
135}
136
137function who(armed: Armed): string[] {
138 return ['--harness', HARNESS, '--session', armed.session, '--stretch', String(armed.stretch)]
139}
140
141// -- gate: is this a primary TUI session with idle enabled? ----------------
142
143async function checkGate($: EngineInterface, s: State): Promise<boolean> {
144 const reply = await cli($, s, ['config', '--harness', HARNESS])
145 const problem = failure(reply)
146 if (problem !== undefined || !isRecord(reply)) {
147 // Not memoised: a transient failure (meridian not on PATH yet) should not disable idle for the whole session.
148 note($, s, `config failed: ${problem ?? 'unexpected reply'}`)
149 s.gate = undefined
150 return false
151 }
152 if (reply.enabled !== true) {
153 s.inert = true
154 note($, s, `inert: idle disabled (${typeof reply.reason === 'string' ? reply.reason : 'no reason given'})`)
155 return false
156 }
157 note($, s, 'active: idle enabled')
158 return true
159}
160
161function gate($: EngineInterface, s: State): Promise<boolean> {
162 if (s.inert) return Promise.resolve(false)
163 s.gate ??= checkGate($, s)
164 return s.gate
165}
166
167// -- arm / adopt timers ----------------------------------------------------
168
169function readSchedule(row: unknown): Armed['at'] {
170 const at: Armed['at'] = {}
171 if (!isRecord(row)) return at
172 for (const stage of STAGES) {
173 const when = asNumber(row[`${stage}_at`])
174 if (when !== undefined) at[stage] = when
175 }
176 return at
177}
178
179/** Replaces the pending timers with one per stage in `armed.at`, at its absolute epoch-ms time. */
180async function adopt($: EngineInterface, s: State, armed: Armed, epoch: number): Promise<void> {
181 const now = await $.clock.now()
182 if (s.epoch !== epoch) return // the user came back while we were waiting
183 cancelTimers(s)
184 s.armed = armed
185 for (const stage of STAGES) {
186 const when = armed.at[stage]
187 if (when === undefined) continue
188 s.timers.push(
189 $.clock.after(Math.max(0, when - now), () => {
190 void onTimer($, s, stage, armed, epoch)
191 }),
192 )
193 }
194 const plan = STAGES.filter(stage => armed.at[stage] !== undefined)
195 .map(stage => `${stage}+${Math.round(((armed.at[stage] ?? now) - now) / 1000)}s`)
196 .join(' ')
197 note($, s, `armed stretch ${armed.stretch} anchor ${armed.anchor}: ${plan || 'no stages left'}`)
198}
199
200/** Rebuilds timers from the stored schedule of this session's open stretch (reload or resume), never from memory. */
201async function recover($: EngineInterface, s: State, session: string, epoch: number): Promise<void> {
202 const rows = await cli($, s, ['status', '--json'])
203 if (!Array.isArray(rows)) {
204 const problem = failure(rows)
205 if (problem !== undefined) note($, s, `status failed: ${problem}`)
206 return
207 }
208 const row = rows.find(
209 candidate =>
210 isRecord(candidate) &&
211 candidate.harness === HARNESS &&
212 candidate.session === session &&
213 candidate.stretch_open === true,
214 )
215 if (!isRecord(row)) return
216 const stretch = asNumber(row.stretch)
217 const anchor = asNumber(row.anchor)
218 if (stretch === undefined || anchor === undefined) return
219 const done = isRecord(row.done) ? row.done : {}
220 const at = readSchedule(row.schedule)
221 for (const stage of STAGES) {
222 if (done[stage] !== undefined) delete at[stage] // the stage already ran in this stretch
223 }
224 s.mayBeOpen = true
225 await adopt($, s, { session, stretch, anchor, at, fired: {} }, epoch)
226}
227
228/** Core's name for each kind of host background task. Core decides what each means for the push and the warning. */
229const TASK_KINDS: Record<string, string> = { subagent: 'agent', workflow: 'agent', shell: 'shell', monitor: 'watcher' }
230
231/** The work the main loop left running, as `idle arm --background-tasks` JSON. */
232function backgroundTasks(tasks: BackgroundTask[]): string {
233 return JSON.stringify(
234 tasks.slice(0, BACKGROUND_TASK_LIMIT).map(task => {
235 const shellCommand = task.type === 'shell' ? task.command : undefined
236 const overCap = shellCommand !== undefined && shellCommand.length > BACKGROUND_COMMAND_CHAR_CAP
237 return {
238 kind: overCap ? 'other' : (TASK_KINDS[task.type] ?? 'other'),
239 ...(shellCommand !== undefined && !overCap ? { command: shellCommand } : {}),
240 }
241 }),
242 )
243}
244
245async function armTask(
246 $: EngineInterface,
247 s: State,
248 epoch: number,
249 assistantText: string | undefined,
250 tasks: BackgroundTask[] | undefined,
251): Promise<void> {
252 if (!(await gate($, s))) return
253 try {
254 // Work still running does not stop the arm: core reads it and holds or delays the push.
255 const session = await $.session.id()
256 const args = ['arm', '--harness', HARNESS, '--session', session]
257 if (tasks !== undefined && tasks.length > 0) args.push(`--background-tasks=${backgroundTasks(tasks)}`)
258 const userExcerpt = capExcerpt(s.lastUserText)
259 const assistantExcerpt = capExcerpt(assistantText)
260 if (userExcerpt !== undefined) args.push(`--user-text=${userExcerpt}`)
261 if (assistantExcerpt !== undefined) args.push(`--assistant-text=${assistantExcerpt}`)
262 const reply = await cli($, s, args)
263 const problem = failure(reply)
264 if (problem !== undefined || !isRecord(reply)) {
265 note($, s, `arm failed: ${problem ?? 'unexpected reply'}`)
266 return
267 }
268 const stretch = asNumber(reply.stretch)
269 const anchor = asNumber(reply.anchor)
270 if (stretch === undefined || anchor === undefined) {
271 // Core declined (role or idle gate): nothing is open, nothing to time.
272 cancelTimers(s)
273 s.armed = undefined
274 note($, s, `arm declined${typeof reply.reason === 'string' ? ` (${reply.reason})` : ''}`)
275 return
276 }
277 s.mayBeOpen = true
278 if (s.epoch !== epoch) return // a return queued behind this arm closes the stretch; arm no timers for it
279 const current = s.armed
280 if (current !== undefined && current.session === session && current.stretch === stretch && current.anchor === anchor) {
281 return // same stretch and anchor: core absorbed this arm (a duplicate turn); keep our timers
282 }
283 if (typeof reply.push_held === 'string') note($, s, `push held: ${reply.push_held}`)
284 const at = readSchedule(reply)
285 if (Object.keys(at).length === 0 && typeof reply.reason === 'string') {
286 // An absorbed arm for a stretch we do not know yet carries no deadlines: take them from the store.
287 await recover($, s, session, epoch)
288 return
289 }
290 await adopt($, s, { session, stretch, anchor, at, fired: {} }, epoch)
291 } catch (err) {
292 note($, s, `arm error: ${describeError(err)}`)
293 }
294}
295
296// -- return ----------------------------------------------------------------
297
298async function returnTask($: EngineInterface, s: State, sessionId: Promise<string | undefined>): Promise<void> {
299 if (!s.mayBeOpen) return // no arm reached core since the last return: nothing to close, skip the ~1 s call
300 const session = await sessionId
301 if (session === undefined) return
302 s.mayBeOpen = false
303 const reply = await cli($, s, ['return', '--harness', HARNESS, '--session', session, '--user-prompt'])
304 const problem = failure(reply)
305 if (problem !== undefined) {
306 s.mayBeOpen = true
307 note($, s, `return failed: ${problem}`)
308 } else if (isRecord(reply) && reply.stretch_closed === true) {
309 note($, s, 'return: stretch closed')
310 }
311}
312
313// -- permission prompt -----------------------------------------------------
314
315async function needsPermissionTask($: EngineInterface, s: State, message: string): Promise<void> {
316 try {
317 const reply = await cli($, s, [
318 'needs-permission', '--harness', HARNESS, `--message=${message}`,
319 ])
320 const problem = failure(reply)
321 if (problem !== undefined) note($, s, `needs-permission failed: ${problem}`)
322 } catch (err) {
323 note($, s, `needs-permission error: ${describeError(err)}`)
324 }
325}
326
327/** The user is back. Cancels timers at once (synchronously), then closes the stretch in core. */
328function userReturned($: EngineInterface, s: State): void {
329 s.epoch += 1
330 cancelTimers(s)
331 s.armed = undefined
332 // Read the id now, not when the queued call runs: `/clear` changes it in between.
333 const sessionId = $.session.id().catch(() => undefined)
334 void enqueue(s, () => returnTask($, s, sessionId))
335}
336
337// -- timers -----------------------------------------------------------------
338
339async function onTimer($: EngineInterface, s: State, stage: Stage, armed: Armed, epoch: number): Promise<void> {
340 try {
341 if (s.armed !== armed || s.epoch !== epoch) return
342 const args = ['fire', stage, ...who(armed), '--anchor', String(armed.anchor)]
343 const reply = await enqueue(s, () => cli($, s, args))
344 const problem = failure(reply)
345 if (problem !== undefined || !isRecord(reply)) {
346 note($, s, `fire ${stage} failed: ${problem ?? 'unexpected reply'}`)
347 return
348 }
349 note($, s, `fire ${stage}: ${String(reply.decision)} (${String(reply.reason)})`)
350 armed.fired[stage] = reply.decision === 'act' ? 'act' : `skip: ${String(reply.reason)}`
351 } catch (err) {
352 note($, s, `timer ${stage} error: ${describeError(err)}`)
353 }
354}
355
356// -- session start ---------------------------------------------------------
357
358async function startTask($: EngineInterface, s: State, epoch: number): Promise<void> {
359 if (!(await gate($, s))) return
360 try {
361 await $.command.register({ name: COMMAND, description: 'Show Meridian idle stretch and timers' })
362 } catch (err) {
363 note($, s, `command registration failed: ${describeError(err)}`)
364 }
365 try {
366 await recover($, s, await $.session.id(), epoch)
367 } catch (err) {
368 note($, s, `recover error: ${describeError(err)}`)
369 }
370}
371
372// -- /meridian-idle --------------------------------------------------------
373
374async function statusText($: EngineInterface, s: State): Promise<string> {
375 // The host already prefixes a plugin command's output with the plugin's name.
376 if (s.inert) return 'inactive for this session'
377 const now = await $.clock.now()
378 const lines: string[] = []
379 const armed = s.armed
380 if (armed === undefined) {
381 lines.push('no stretch armed')
382 } else {
383 lines.push(`stretch ${armed.stretch}, anchor ${armed.anchor}`)
384 for (const stage of STAGES) {
385 const when = armed.at[stage]
386 if (when === undefined) continue
387 const fired = armed.fired[stage]
388 const timing = fired !== undefined ? `fired (${fired})` : when <= now ? 'due' : `in ${Math.round((when - now) / 1000)}s`
389 lines.push(` ${stage.padEnd(7)} ${timing}`)
390 }
391 }
392 if (s.log.length > 0) {
393 lines.push('log:')
394 for (const line of s.log.slice(-8)) lines.push(` ${line}`)
395 }
396 return lines.join('\n')
397}
398
399// -- registration ----------------------------------------------------------
400
401export const register: Register = on => {
402 const s = newState()
403
404 on('session.start', async ($, e, next) => {
405 if (e.isInteractive === false || e.surface === null) {
406 s.inert = true
407 } else {
408 // Off the startup path: `meridian` takes about a second.
409 const epoch = s.epoch
410 void enqueue(s, () => startTask($, s, epoch))
411 }
412 return next(e)
413 })
414
415 // Subagent, teammate and compaction-fork turns raise turn.start too, with agentId set. Only the main loop's
416 // start retires the Stop list that its own turn.complete will use.
417 on('turn.start', async ($, e, next) => {
418 if (e.agentId === undefined) s.stopTasks = undefined
419 return next(e)
420 })
421
422 // The main loop's Stop fires just before its turn.complete and is the only place the host lists background work.
423 on('classic.Stop', async ($, e, next) => {
424 s.stopTasks = e.background_tasks
425 return next(e)
426 })
427
428 on('turn.complete', async ($, e, next) => {
429 // A subagent's turn carries agentId; only the main loop's end is the user-visible idle.
430 if (e.agentId === undefined && !s.inert) {
431 const epoch = s.epoch
432 const tasks = s.stopTasks
433 s.stopTasks = undefined
434 void enqueue(s, () => armTask($, s, epoch, e.answer, tasks))
435 }
436 return next(e)
437 })
438
439 on('classic.Notification', async ($, e, next) => {
440 if (!s.inert && e.notification_type === 'permission_prompt') {
441 // This signal is independent of the idle timeline: do not queue it behind state calls.
442 void needsPermissionTask($, s, e.message)
443 }
444 return next(e)
445 })
446
447 on('prompt.submit', async ($, e, next) => {
448 if (!s.inert && isUserOrigin(e.origin)) {
449 s.lastUserText = e.text
450 userReturned($, s)
451 }
452 return next(e)
453 })
454
455 // Typed slash commands never reach prompt.submit. `/meridian-idle` itself is a read-only look at the timers and does not count as a return.
456 on('command.run', { command: COMMAND }, async ($, e, next) => {
457 void next
458 return { text: await statusText($, s) }
459 })
460
461 on('command.run', async ($, e, next) => {
462 if (!s.inert && e.command !== COMMAND && isUserOrigin(e.origin)) {
463 s.lastUserText = `/${e.command}${e.args ? ` ${e.args}` : ''}`
464 userReturned($, s)
465 }
466 return next(e)
467 })
468
469 on('session.end', async ($, e, next) => {
470 s.epoch += 1
471 cancelTimers(s)
472 s.armed = undefined
473 return next(e)
474 })
475}
476