/relay: update stale docs, save a handoff note to a temp file, draft a continuation prompt, compact, and put the prompt in the box.

A Claude Code mod (function-hook plugin) that turns the checkpoint-compact-continue routine into one command, /relay.
When a session's context is getting full, /relay:
saveInstructions), then ends the turn with a handoff note inside <handoff-note> tags. The note covers what's done, what's in progress, decisions, lessons, gotchas, workarounds, next steps and the files touched. The plugin writes the note to a temp file, $TMPDIR/claude-relay/<project>-<UTC time>.md (/tmp when TMPDIR is unset), so nothing new lands in the repo. The model doesn't write that file itself, so there's no permission prompt for a path outside the project.macOS clears $TMPDIR on reboot and removes files left unused for about 3 days. That's fine for the next session; set noteDir if you want notes kept longer.
$.model.fork, the cache-served, tool-less side question /btw asks. The fork replays the last request, which ends before the save turn's final message, so the note is quoted into the question. The answer is a copy/paste-ready prompt: one line on what to continue, then "Come up to speed:" and the files to read (@path, the temp note first), plus only what those files don't say. It doesn't tell the agent to read the @ files or instruction files such as AGENTS.md and CLAUDE.md, since the harness attaches and loads those itself. The fork doesn't add the question or the answer to the conversation. The prompt is saved to the plugin's store, written beside the note as <note>.prompt.md (so you can compare it with what you sent), and, by default, copied to the clipboard./compact does, with your instructions (default: keep what's helpful and not written to a durable location).@ mentions; a plugin's submitted prompt doesn't. Set fillDuringCompaction to false to fill only after compaction.From the start of the save turn until your next prompt's turn starts, relay holds background deliveries that would start a turn on their own: a background shell or agent finishing, another session's or a coordinating session's message, a scheduled prompt. Each is dropped with a note saying relay is holding it. Your next prompt carries them as context, in the order they arrived, and anything dequeued after you press Enter but before your turn starts follows that turn as a message from relay. So nothing runs between the checkpoint and the continuation prompt, and a notification right after the save turn no longer stops the run. A delivery into a running turn isn't held. A prompt you type into the running save turn doesn't end the hold. Two kinds of message aren't held: a channel message (Slack or Telegram through an MCP server), since that may be you driving the session remotely, and a teammate's message, which the engine gives no origin, the same as a command queued with no stamp, which could be yours. If the run fails before the prompt reaches the box, a failure hands them back as a message from relay; if the box can't be filled, they stay held for the prompt you paste. If a prompt that took them is refused further down, they go back on hold. If a hand-back is itself refused, the log shows the messages in full, so nothing is lost silently. /relay status shows how many are held, and /relay cancel releases them at any time.
If any step fails, the run stops before the next one and logs why:
fillDuringCompaction off, saved for /relay paste), and the log says to /compact before sending it.fillDuringCompaction off, nothing is filled and the prompt stays saved for /relay paste). The log says to run /compact before sending it; a prompt you already queued runs on the uncompacted conversation. A rejected compaction is retried twice, 2 s apart, in case the save turn is still winding down; meanwhile the status says not to send the prompt yet, and a prompt sent then runs on the uncompacted conversation (the log says so).Headless sessions (-p, SDK) can't compact from a plugin on Claude Code 2.1.294, so there /relay saves and drafts the prompt, then stops with the prompt saved.
Tested end to end in an interactive session on Claude Code 2.1.294: save turn, note written to $TMPDIR, fork, compaction (35k → 3k tokens) and fill. Pressing Enter on the filled prompt attached the temp note through its @ path with no permission prompt. 0.4.0's fill during compaction and the hold are covered by claude plugin test; whether Enter during a compaction queues the prompt is the engine's behavior and is still to be checked live.
/relay [focus] run it; optional focus is appended to the save prompt
/relay status idle, or which phase and for how long
/relay cancel stop a run (anything already written or compacted stays)
/relay paste fill the prompt box with the last continuation prompt, from any session
status, cancel and paste are matched whole and ignore case. Any other text is the focus.
Use /relay mid-session to free up context and keep going: the save turn only records where things stand, and the work continues after you press Enter on the filled prompt. The save prompt tells the model not to start new work, since anything started then would be compacted half-done. So use the focus to say what the note should cover, including what you'll do next, not to give the model a task:
/relay next I'm wiring the retry logic into the uploader; make sure the note covers what that needs
To give the next session an instruction, type it under the filled prompt before pressing Enter; the prompt is placed ahead of anything you'd already typed.
Set in /config, or in settings under pluginConfigs["relay@relay"].options (the key is the plugin id, <plugin>@<marketplace>):
| Option | Default | |
|---|---|---|
deliver | fill | fill puts the prompt in the box. submit sends it at once and tells the model to read the @ files, since a plugin's prompt doesn't attach them. |
compactInstructions | Keep any information that's helpful to the agent and not written to a durable location. | What the compaction summary keeps. |
noteDir | empty | Directory for handoff notes. Empty: $TMPDIR/claude-relay (else /tmp/claude-relay). |
copyToClipboard | true | Also copy the continuation prompt to the clipboard. |
saveInstructions | empty | Replaces the save turn's first step (update stale docs and notes in place). See below. |
fillDuringCompaction | true | With deliver: fill, fill the box as compaction starts, so you can queue the prompt. false: fill once compaction has finished. |
The save and continuation prompts live in hooks/prompts.ts.
saveInstructions replaces only the save turn's first step. relay still asks for the handoff note inside <handoff-note> tags, tells the model not to write the note file, and says not to start new work, since it needs the tagged note for the continuation prompt. Use it to run your own closeout routine, for example a skill:
Follow the saving-session-state skill.
A skill named there must be one the model can invoke (no disable-model-invocation), because the save turn asks the model to load it. Whatever it runs shouldn't stop to ask questions: relay continues only once the save turn ends with the tagged note.
This repo is its own marketplace. Install from GitHub:
claude plugin marketplace add chrisvaillancourt/claude-relay
claude plugin install relay@relay --scope user
The install may say the userConfig options aren't set yet; until you set them, the defaults below apply. A GitHub install runs a copy. It updates only when version in plugin.json changes: claude plugin marketplace update relay, then claude plugin update relay@relay.
Or from a local clone:
claude plugin marketplace add /path/to/claude-relay
claude plugin install relay@relay --scope user
A folder marketplace is read from the clone itself. After an edit, run /reload-plugins; no version bump or reinstall is needed. claude plugin list shows Read from: <clone>.
claude plugin validate .
claude plugin test .
To try it without installing: claude --plugin-dir ..
MIT.
hooks/register.ts 483 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, PluginOptions, Register, Timer } from 'claude-code'
3
4import {
5 cleanContinuation,
6 continuationPrompt,
7 extractNote,
8 forSubmit,
9 heldNotice,
10 holdAppend,
11 restoreHold,
12 isCanceled,
13 isHeldOrigin,
14 isPersonOrigin,
15 notePathFor,
16 parseArgs,
17 promptPathFor,
18 SAVE_MARKER,
19 savePrompt,
20} from './prompts'
21import type { Config, Hold, Run, SavedPrompt } from '../types'
22
23/** A compaction right after the save turn may still see it running; retry briefly, then give up. */
24const COMPACT_RETRY_MS = 2000
25const COMPACT_ATTEMPTS = 3
26/** How long after the save prompt's turn started to expect its turn.start to have been matched. */
27const SAVE_TURN_WATCHDOG_MS = 5000
28const DEFAULT_COMPACT_INSTRUCTIONS =
29 "Keep any information that's helpful to the agent and not written to a durable location."
30
31const IDLE: Run = { phase: 'idle', runId: 0, saveTurnId: null, startedAt: null, notePath: null }
32
33const runAtom = atom({ plugin: 'relay', key: 'run' } as const, IDLE)
34
35const RELEASED: Hold = { isHolding: false, items: [], endsAtTurn: false, gen: 0 }
36const holdAtom = atom({ plugin: 'relay', key: 'hold' } as const, RELEASED)
37
38// Module variables reset on a hot reload; `$.state` survives one. A run left
39// `continuing` by a reload has lost its timer, so session.start resets it.
40let config: Config = configFrom({})
41let timer: Timer | null = null
42/** The run whose continuation prompt went into the box as compaction started. */
43let filledEarlyRunId: number | null = null
44/** The run a main-loop turn started in after its save turn, even one that has ended since. */
45let interruptedRunId: number | null = null
46let isInteractive = true
47/** Whether a main-loop turn is running; subagents raise no turn.start. */
48let isTurnRunning = false
49
50function configFrom(options: PluginOptions): Config {
51 const instructions = typeof options.compactInstructions === 'string' ? options.compactInstructions.trim() : ''
52 return {
53 deliver: options.deliver === 'submit' ? 'submit' : 'fill',
54 compactInstructions: instructions || DEFAULT_COMPACT_INSTRUCTIONS,
55 copyToClipboard: options.copyToClipboard !== false,
56 noteDir: typeof options.noteDir === 'string' ? options.noteDir.trim() : '',
57 saveInstructions: typeof options.saveInstructions === 'string' ? options.saveInstructions.trim() : '',
58 fillDuringCompaction: options.fillDuringCompaction !== false,
59 }
60}
61
62/** Ends the hold and returns what it held. */
63async function release($: EngineInterface): Promise<string[]> {
64 let items: string[] = []
65 await update($, holdAtom, cur => {
66 items = cur.items
67 return { ...RELEASED, gen: (cur.gen ?? 0) + 1 }
68 })
69 return items
70}
71
72/** Puts held messages that couldn't be handed back in the transcript, so they aren't lost. */
73function logHeld($: EngineInterface, items: readonly string[], why: string) {
74 if (!items.length) return
75 try {
76 $.ui.log(`relay: couldn't hand back ${items.length} held message${items.length === 1 ? '' : 's'} (${why}). Here they are:\n\n${heldNotice(items)}`)
77 } catch {
78 // Best effort.
79 }
80}
81
82/**
83 * Ends the hold and hands what it held back to the session as relay's own
84 * message, which runs once the session is idle. From a timer, since a hook
85 * that submits would wait on itself.
86 */
87async function releaseToSession($: EngineInterface): Promise<number> {
88 const held = await release($)
89 if (held.length) {
90 $.clock.after(0, () => {
91 $.prompt
92 .submit({ text: heldNotice(held) })
93 .then(r => {
94 if (r.drop !== undefined) logHeld($, held, r.drop)
95 })
96 .catch(err => logHeld($, held, errorText(err)))
97 })
98 }
99 return held.length
100}
101
102function cancelTimer() {
103 timer?.cancel()
104 timer = null
105}
106
107function errorText(err: unknown) {
108 return err instanceof Error ? err.message : String(err)
109}
110
111function toast($: EngineInterface, text: string) {
112 try {
113 $.ui.toast(text)
114 } catch {
115 // Best effort.
116 }
117}
118
119/** Ends run `runId` if it is still the live one, and says why; never throws. */
120async function finish($: EngineInterface, runId: number, message: string | null, keepHold = false) {
121 try {
122 const run = await read($, runAtom)
123 if (run.runId !== runId || run.phase === 'idle') return
124 await update($, runAtom, cur => (cur.runId === runId ? { ...IDLE, runId } : cur))
125 $.ui.status(undefined)
126 if (message) $.ui.log(`relay: ${message}`)
127 // A failure leaves no continuation prompt to wait for, unless it's already in the box.
128 if (message && !keepHold && filledEarlyRunId !== runId) await releaseToSession($)
129 } catch {
130 // Reporting must never throw out of a hook or timer.
131 }
132}
133
134async function isCurrent($: EngineInterface, runId: number) {
135 const run = await read($, runAtom)
136 return run.runId === runId && run.phase === 'continuing'
137}
138
139/** Puts `text` in the prompt box ahead of any draft the person has typed. */
140async function fill($: EngineInterface, text: string): Promise<boolean> {
141 const draft = (await $.prompt.read()).text.trim()
142 const filled = await $.prompt.fill({ text: draft ? `${text}\n\n${draft}` : text })
143 return filled.isFilled
144}
145
146/** Compacts, retrying briefly if the save turn hasn't finished tearing down. */
147async function compact($: EngineInterface, runId: number, attempt = 1): Promise<void> {
148 if (!(await isCurrent($, runId))) return
149 if (isTurnRunning || interruptedRunId === runId) {
150 await finish(
151 $,
152 runId,
153 filledEarlyRunId === runId
154 ? 'stopped: a turn started while compaction was retrying. If it was the continuation prompt, it ran on the uncompacted conversation; /compact, then /relay paste, to start over.'
155 : 'stopped: a new turn started before compaction. The continuation prompt is saved: /compact, then /relay paste.',
156 )
157 return
158 }
159 let result
160 try {
161 const compacting = $.session.compact({ instructions: config.compactInstructions })
162 if (attempt === 1 && config.deliver === 'fill' && config.fillDuringCompaction) {
163 // The prompt goes in as compaction starts, so the person can queue it
164 // before a background task finishes. Its rejection is awaited below.
165 compacting.catch(() => undefined)
166 if (await fillSaved($, runId)) {
167 filledEarlyRunId = runId
168 $.ui.status('compacting… the continuation prompt is in the box; Enter queues it')
169 }
170 }
171 result = await compacting
172 } catch (err) {
173 $.ui.log(`relay: compaction attempt ${attempt} rejected: ${errorText(err)}`, { to: 'debug' })
174 // The person pressing Esc or Ctrl+C cancels compaction; that's a decision, not a hiccup.
175 if (isCanceled(errorText(err))) {
176 await finish($, runId, `compaction was canceled. ${savedHint(runId, '/relay paste')}`)
177 return
178 }
179 if (isInteractive && attempt < COMPACT_ATTEMPTS && (await isCurrent($, runId))) {
180 if (filledEarlyRunId === runId) $.ui.status("compaction is retrying; don't send the prompt yet…")
181 timer = $.clock.after(COMPACT_RETRY_MS, () => {
182 compact($, runId, attempt + 1).catch(e => finish($, runId, `stopped: ${errorText(e)}`))
183 })
184 return
185 }
186 await finish($, runId, `couldn't compact (${errorText(err)}). ${savedHint(runId, 'run /compact yourself, then /relay paste')}`)
187 return
188 }
189 if (result.skip !== undefined) {
190 await finish($, runId, `compaction was skipped (${result.skip}). ${savedHint(runId, '/relay paste')}`)
191 return
192 }
193 await deliver($, runId)
194}
195
196/** Where the continuation prompt is after a failed compaction, and what to do with it. */
197function savedHint(runId: number, recovery: string): string {
198 return filledEarlyRunId === runId
199 ? "The continuation prompt is already in the prompt box: run /compact before you send it, or it runs on the uncompacted conversation."
200 : `The continuation prompt is saved: ${recovery}.`
201}
202
203/** Fills the box with the run's saved prompt; false when it can't. */
204async function fillSaved($: EngineInterface, runId: number): Promise<boolean> {
205 if (!(await isCurrent($, runId))) return false
206 const saved = (await $.store.get('lastPrompt')) as SavedPrompt | undefined
207 return saved?.text ? fill($, saved.text).catch(() => false) : false
208}
209
210async function deliver($: EngineInterface, runId: number) {
211 if (!(await isCurrent($, runId))) return
212 const saved = (await $.store.get('lastPrompt')) as SavedPrompt | undefined
213 const text = saved?.text ?? ''
214 if (config.deliver === 'submit') {
215 await finish($, runId, null)
216 // A plugin's submit carries no context, so what was held goes in its text.
217 const held = await release($)
218 const body = held.length ? `${forSubmit(text)}\n\n${heldNotice(held)}` : forSubmit(text)
219 void $.prompt
220 .submit({ text: body, asUser: true })
221 .then(async r => {
222 if (r.drop === undefined) return
223 $.ui.log(`relay: the continuation prompt was dropped (${r.drop}); /relay paste to retry.`)
224 logHeld($, held, r.drop)
225 })
226 .catch(err => {
227 $.ui.log(`relay: couldn't submit the continuation prompt (${errorText(err)}); /relay paste to retry.`)
228 logHeld($, held, errorText(err))
229 })
230 toast($, 'compacted; sending the continuation prompt')
231 return
232 }
233 if (filledEarlyRunId === runId) {
234 await finish($, runId, null)
235 // Enter during compaction queues the prompt and empties the box.
236 const box = (await $.prompt.read().catch(() => ({ text: '' }))).text
237 toast($, box.includes(text) ? 'compacted; review the prompt and press Enter' : 'compacted')
238 return
239 }
240 const isFilled = await fill($, text).catch(() => false)
241 // A prompt that couldn't be filled is still to be sent, so the hold stays for it.
242 await finish($, runId, isFilled ? null : `couldn't fill the prompt box. Continuation prompt:\n\n${text}`, true)
243 if (isFilled) toast($, 'compacted; review the prompt and press Enter')
244}
245
246/** After the save turn: write its note, fork the continuation prompt, keep it, then compact and deliver. */
247async function continueRun($: EngineInterface, runId: number, answer: string, notePath: string) {
248 const note = extractNote(answer)
249 try {
250 if (!(await isCurrent($, runId))) return
251 if (!note) {
252 await finish($, runId, 'stopped: the save turn ended with no handoff note. Nothing was compacted.')
253 return
254 }
255 try {
256 await $.fs.write(notePath, `${note}\n`)
257 } catch (err) {
258 await finish($, runId, `stopped: couldn't write the handoff note to ${notePath} (${errorText(err)}). Nothing was compacted.`)
259 return
260 }
261 $.ui.status('writing the continuation prompt…')
262 // The fork replays the last request, which ends before the note, so the note rides along.
263 const reply = await $.model.fork({ prompt: continuationPrompt(note, notePath) })
264 if (!(await isCurrent($, runId))) return
265 if (!reply.isAnswered) {
266 await finish($, runId, `stopped: the continuation prompt failed (${reply.reason}). Nothing was compacted.`)
267 return
268 }
269 const text = cleanContinuation(reply.text)
270 if (!text) {
271 await finish($, runId, 'stopped: the continuation prompt came back empty. Nothing was compacted.')
272 return
273 }
274 const saved: SavedPrompt = { text, at: await $.clock.now(), sessionId: await $.session.id() }
275 await $.store.set('lastPrompt', saved)
276 // Kept beside the note, to compare with what the person sends; best effort.
277 await $.fs.write(promptPathFor(notePath), `${text}\n`).catch(() => undefined)
278 if (config.copyToClipboard) await $.ui.copy({ text }).catch(() => undefined)
279 if (!(await isCurrent($, runId))) return
280 $.ui.status('compacting…')
281 await compact($, runId)
282 } catch (err) {
283 await finish($, runId, `stopped: ${errorText(err)}`)
284 }
285}
286
287/** Submits the save prompt; called from a timer, since command.run can't submit. */
288async function submitSave($: EngineInterface, runId: number, save: string) {
289 const run = await read($, runAtom)
290 if (run.runId !== runId || run.phase !== 'saving') return
291 // Anything still held from an earlier run goes to this save turn. Taken only
292 // now, so a cancel before this timer runs releases it with the rest.
293 const carried = await release($)
294 const text = carried.length ? `${save}\n\n${heldNotice(carried)}` : save
295 let r
296 try {
297 r = await $.prompt.submit({ text, asUser: true })
298 } catch (err) {
299 logHeld($, carried, errorText(err))
300 throw err
301 }
302 if (r.drop !== undefined) {
303 await finish($, runId, `stopped: the save prompt was dropped (${r.drop}).`)
304 logHeld($, carried, 'the save prompt carrying them was dropped')
305 return
306 }
307 // The submit resolves as the save turn starts. If turn.start didn't match the
308 // marker (another plugin rewrote the prompt), don't wait in `saving` forever.
309 $.clock.after(SAVE_TURN_WATCHDOG_MS, () => {
310 void read($, runAtom)
311 .then(cur => {
312 if (cur.runId === runId && cur.phase === 'saving' && cur.saveTurnId === null) {
313 return finish($, runId, "stopped: couldn't find the save turn. Nothing was compacted; /relay to retry.")
314 }
315 })
316 .catch(() => undefined)
317 })
318}
319
320export const register: Register = (on, options) => {
321 config = configFrom(options)
322 timer = null
323 isTurnRunning = false
324
325 on('session.start', async ($, e, next) => {
326 const result = await next(e)
327 isInteractive = e.isInteractive
328 await $.command.register({
329 name: 'relay',
330 description: 'Save state to durable notes, draft a continuation prompt, compact, and queue the prompt',
331 argumentHint: '[focus | status | cancel | paste]',
332 })
333 // A `saving` run holds no timer, so its turn.complete can still continue it.
334 const run = await read($, runAtom)
335 if (run.phase === 'continuing') {
336 await update($, runAtom, cur => ({ ...IDLE, runId: cur.runId + 1 }))
337 $.ui.log(
338 'relay: a reload interrupted the run after the save turn. If a continuation prompt was drafted, /relay paste has it; run /compact yourself first.',
339 )
340 }
341 return result
342 })
343
344 on('turn.start', async ($, e, next) => {
345 isTurnRunning = true
346 // The person's prompt took what was held at Enter; anything since follows its turn.
347 if ((await read($, holdAtom)).endsAtTurn) await releaseToSession($)
348 const run = await read($, runAtom)
349 // Latched: a turn that ends before a compaction retry still counts.
350 if (run.phase === 'continuing') interruptedRunId = run.runId
351 if (run.phase === 'saving' && run.saveTurnId === null && e.text.includes(SAVE_MARKER)) {
352 await update($, runAtom, cur => (cur.runId === run.runId ? { ...cur, saveTurnId: e.turnId } : cur))
353 // From the save turn on, a delivery that would start a turn of its own waits
354 // for the continuation prompt; one into this turn carries its turnId and passes.
355 await update($, holdAtom, cur => ({ ...cur, isHolding: true, endsAtTurn: false, gen: (cur.gen ?? 0) + 1 }))
356 }
357 return next(e)
358 })
359
360 on('turn.complete', async ($, e, next) => {
361 const result = await next(e)
362 if (e.agentId !== undefined) return result
363 isTurnRunning = false
364 const run = await read($, runAtom)
365 if (run.phase !== 'saving' || run.saveTurnId !== e.turnId) return result
366 if (e.reason !== 'answer') {
367 await finish($, run.runId, `stopped: the save turn ended (${e.reason}). Nothing was compacted.`)
368 return result
369 }
370 const now = await update($, runAtom, cur =>
371 cur.runId === run.runId && cur.phase === 'saving' ? { ...cur, phase: 'continuing' as const } : cur,
372 )
373 if (now.runId !== run.runId || now.phase !== 'continuing' || now.notePath === null) return result
374 const notePath = now.notePath
375 // Compaction rejects while a turn runs, so continue once this one has ended.
376 cancelTimer()
377 timer = $.clock.after(0, () => void continueRun($, run.runId, e.answer, notePath))
378 return result
379 })
380
381 on('prompt.submit', async ($, e, next) => {
382 if (!(await read($, holdAtom)).isHolding) return next(e)
383 // One delivered into a running turn starts no turn of its own.
384 if (isHeldOrigin(e.origin.kind) && e.turnId === undefined) {
385 let isCaptured = false
386 await update($, holdAtom, cur => {
387 const held = holdAppend(cur, e.text)
388 isCaptured = held !== null
389 return held ?? cur
390 })
391 if (isCaptured) return { drop: 'relay is holding this until you send the continuation prompt; it goes along with that prompt.' }
392 return next(e)
393 }
394 if (!isPersonOrigin(e.origin.kind)) return next(e)
395 // Typed into the save turn: not the continuation prompt, so the hold goes on.
396 if (e.turnId !== undefined && e.turnId === (await read($, runAtom)).saveTurnId) return next(e)
397 let taken: string[] = []
398 let gen = 0
399 let didEnd = false
400 await update($, holdAtom, cur => {
401 gen = cur.gen ?? 0
402 didEnd = !cur.endsAtTurn
403 taken = didEnd ? cur.items : []
404 return didEnd ? { ...cur, items: [], endsAtTurn: true } : cur
405 })
406 const result = await next(taken.length ? { ...e, context: [...(e.context ?? []), heldNotice(taken)] } : e)
407 if (result.drop !== undefined) {
408 // Refused further down: give back what it took, unless the hold has ended since.
409 let isRestored = false
410 await update($, holdAtom, cur => {
411 const back = restoreHold(cur, taken, gen, didEnd)
412 isRestored = back !== null
413 return back ?? cur
414 })
415 if (!isRestored) logHeld($, taken, 'the prompt carrying them was refused after the hold ended')
416 }
417 return result
418 }).catch(($, e, next) => next(e)) // a failure lets the prompt through; holding is best effort
419
420 on('command.run', { command: 'relay' }, async ($, e) => {
421 const cmd = parseArgs(e.args)
422 const run = await read($, runAtom)
423
424 switch (cmd.kind) {
425 case 'status': {
426 const hold = await read($, holdAtom)
427 const holding = hold.isHolding
428 ? ` Holding ${hold.items.length} background message${hold.items.length === 1 ? '' : 's'} until your next prompt; /relay cancel releases them.`
429 : ''
430 if (run.phase === 'idle') return { text: `Idle.${holding}` }
431 const minutes = run.startedAt === null ? 0 : Math.round(((await $.clock.now()) - run.startedAt) / 60_000)
432 return { text: `${run.phase === 'saving' ? 'Saving' : 'Continuing'}, started ${minutes} min ago. /relay cancel to stop.${holding}` }
433 }
434
435 case 'cancel': {
436 const hold = await read($, holdAtom)
437 if (run.phase === 'idle' && !hold.isHolding) return { text: 'Nothing to cancel.' }
438 if (run.phase !== 'idle') {
439 cancelTimer()
440 await update($, runAtom, cur => ({ ...IDLE, runId: cur.runId + 1 }))
441 $.ui.status(undefined)
442 }
443 const released = await releaseToSession($)
444 const note = released ? ` Released ${released} held message${released === 1 ? '' : 's'}.` : ''
445 return { text: `Cancelled. Anything already saved or compacted stays.${note}` }
446 }
447
448 case 'paste': {
449 const saved = (await $.store.get('lastPrompt')) as SavedPrompt | undefined
450 if (!saved?.text) return { text: 'No saved continuation prompt.' }
451 const isFilled = await fill($, saved.text).catch(() => false)
452 const when = new Date(saved.at).toISOString()
453 return {
454 text: isFilled
455 ? `Filled the continuation prompt saved ${when} (session ${saved.sessionId}).`
456 : `Couldn't fill the prompt box. Saved ${when} (session ${saved.sessionId}):\n\n${saved.text}`,
457 }
458 }
459
460 case 'start': {
461 if (run.phase !== 'idle') return { text: `Already ${run.phase}. /relay status, or /relay cancel to reset.` }
462 if ((await $.session.turns()) === 0) return { text: 'Nothing to hand off yet.' }
463 const runId = run.runId + 1
464 const startedAt = await $.clock.now()
465 const noteDir = config.noteDir || `${(await $.env.get('TMPDIR')) || '/tmp'}`.replace(/\/+$/, '') + '/claude-relay'
466 const notePath = notePathFor(noteDir, await $.session.root(), startedAt)
467 await update($, runAtom, () => ({ phase: 'saving' as const, runId, saveTurnId: null, startedAt, notePath }))
468 $.ui.status('saving state…')
469 // The host refuses a submit from inside command.run (it would wait on
470 // the turn this hook holds), so submit once the command has returned.
471 const save = savePrompt(cmd.focus, notePath, config.saveInstructions)
472 cancelTimer()
473 timer = $.clock.after(0, () => {
474 submitSave($, runId, save).catch(err =>
475 finish($, runId, `stopped: couldn't submit the save prompt (${errorText(err)}).`),
476 )
477 })
478 return { text: 'Saving state, then drafting a continuation prompt and compacting.' }
479 }
480 }
481 })
482}
483hooks/prompts.ts 199 lines1import type { Command, Hold } from '../types'
2
3/** Leads the save prompt, so the save turn can be told apart by its text. */
4export const SAVE_MARKER = '[relay] Checkpoint before compaction.'
5
6/**
7 * Where the handoff note goes: `dir` (default: the system temp directory's
8 * claude-relay/), named for the project and the UTC time the run started.
9 */
10export function notePathFor(dir: string, projectRoot: string, nowMs: number): string {
11 const project = (projectRoot.replace(/\/+$/, '').split('/').pop() || 'session').replace(/[^A-Za-z0-9._-]/g, '-')
12 const stamp = new Date(nowMs).toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z')
13 return `${dir.replace(/\/+$/, '')}/${project}-${stamp}.md`
14}
15
16/** The save turn's default first step, which the `saveInstructions` option replaces. */
17export const DEFAULT_SAVE_STEP =
18 "Update the project's docs and notes that this session's work made stale, in place, following CLAUDE.md / AGENTS.md. Don't create a handoff note in the project."
19
20/**
21 * The save turn's prompt: update stale docs (or follow `saveInstructions`),
22 * then end with the handoff note, which the plugin saves.
23 */
24export function savePrompt(focus: string, notePath: string, saveInstructions = ''): string {
25 const lines = [
26 `${SAVE_MARKER} The conversation will be compacted after this turn, and the next session starts from what you leave now.`,
27 '',
28 `1. ${saveInstructions.trim() || DEFAULT_SAVE_STEP}`,
29 `2. Then, after your last tool call, end with the handoff note inside <handoff-note> and </handoff-note> tags, each on its own line. What's inside the tags is saved to ${notePath} for the next session; don't write that file yourself.`,
30 '3. In the note, record what is done; what is in progress, exactly where it stands (branches, uncommitted changes, running jobs, open PRs); decisions and why; what you learned; issues, gotchas and workarounds; next steps, each with a disposition (do / skip / defer); and the files you wrote or updated this session.',
31 "4. Link to what's already durable instead of repeating it.",
32 '',
33 "Don't start new work.",
34 ]
35 if (focus) lines.push('', `Focus: ${focus}`)
36 return lines.join('\n')
37}
38
39/** The side question asked over the transcript once the save turn ends (what `/btw` would be asked). */
40export const CONTINUATION_PROMPT =
41 'Give me a concise, copy/paste-ready prompt to continue in the next session. ' +
42 'Open with one line saying what to continue, then a line reading "Come up to speed:" and the files the next agent should read first, one per line, each path prefixed with `@`. ' +
43 "The harness attaches the @ files and loads AGENTS.md, CLAUDE.md and other instruction files by itself, so don't tell the agent to read them, and don't list instruction files. " +
44 "Add anything else they need to know that those files don't say, without repeating what they do. " +
45 'Output only the prompt: no preamble, no wrapper formatting, no code fence.'
46
47const OPEN_TAG = /^\s*<handoff-note>\s*$/
48const CLOSE_TAG = /^\s*<\/handoff-note>\s*$/
49const FENCE = /^\s*(`{3,}|~{3,})/
50const INLINE_NOTE = /<handoff-note>([\s\S]*?)<\/handoff-note>/g
51
52/**
53 * Blocks between tags on lines of their own, as the save prompt asks. Tag
54 * names quoted in prose don't match, and tags inside a code fence (an example
55 * in a draft) belong to the note's text.
56 */
57function ownLineNotes(answer: string): string[] {
58 const lines = answer.split(/\r?\n/)
59 const notes: string[] = []
60 let fence: string | null = null
61 let open: number | null = null
62 lines.forEach((line, i) => {
63 const marker = FENCE.exec(line)?.[1]
64 if (marker) {
65 if (fence === null) fence = marker
66 else if (marker[0] === fence[0] && marker.length >= fence.length && line.trim() === marker) fence = null
67 return
68 }
69 if (fence !== null) return
70 if (OPEN_TAG.test(line)) open = i
71 else if (CLOSE_TAG.test(line) && open !== null) {
72 notes.push(lines.slice(open + 1, i).join('\n'))
73 open = null
74 }
75 })
76 return notes
77}
78
79/**
80 * The note inside the save turn's <handoff-note> tags: the last block whose
81 * tags sit on their own lines, else the last inline pair, else the whole message.
82 */
83export function extractNote(answer: string): string {
84 const note = ownLineNotes(answer).at(-1) ?? [...answer.matchAll(INLINE_NOTE)].at(-1)?.[1] ?? answer
85 return note.trim()
86}
87
88/** Longest stretch of the note quoted into the fork prompt. */
89const NOTE_LIMIT = 8000
90
91/**
92 * The fork replays the main thread's last request, which ends before the save
93 * turn's final message (the handoff note), so the note rides along.
94 */
95export function continuationPrompt(note: string, notePath: string): string {
96 const trimmed = note.trim()
97 const quoted = trimmed.length > NOTE_LIMIT ? `${trimmed.slice(0, NOTE_LIMIT)}\n[…]` : trimmed
98 return (
99 `The checkpoint turn's final message is the handoff note, saved to ${notePath}:\n\n` +
100 `<handoff-note path="${notePath}">\n${quoted}\n</handoff-note>\n\n` +
101 `List @${notePath} first among the files to read.\n\n${CONTINUATION_PROMPT}`
102 )
103}
104
105/** Drops one code fence wrapping the whole reply, and surrounding whitespace. */
106export function cleanContinuation(text: string): string {
107 const trimmed = text.trim()
108 const fenced = /^(`{3,}|~{3,})[^\n]*\n([\s\S]*?)\n?\1$/.exec(trimmed)
109 if (!fenced) return trimmed
110 const [, fence = '', inner = ''] = fenced
111 // A line opening the same fence inside means several blocks, not one wrapper.
112 const opensAgain = inner.split('\n').some(line => line.trimStart().startsWith(fence))
113 return opensAgain ? trimmed : inner.trim()
114}
115
116/** Where the generated continuation prompt is kept: beside its note, so it can be compared with what was sent. */
117export function promptPathFor(notePath: string): string {
118 return /\.md$/.test(notePath) ? notePath.replace(/\.md$/, '.prompt.md') : `${notePath}.prompt.md`
119}
120
121/**
122 * Deliveries that start a turn on their own: background tasks, other
123 * sessions, schedules. Held from the save turn's start until the person's
124 * next prompt's turn starts, so none runs between the checkpoint and the
125 * continuation prompt. Not `channel`: that may be the person driving the
126 * session remotely, who couldn't end a hold from there.
127 */
128const HELD_ORIGINS = new Set([
129 'task-notification',
130 'peer',
131 'peer-send-message',
132 'projects-relay',
133 'coordinator',
134 'observer',
135 'observer-activity',
136 'scheduled-trigger',
137])
138
139export function isHeldOrigin(kind: string): boolean {
140 return HELD_ORIGINS.has(kind)
141}
142
143/** The person's own prompt, which ends the hold. */
144export function isPersonOrigin(kind: string): boolean {
145 return kind === 'composer' || kind === 'bridge' || kind === 'sdk' || kind === 'slack-ping'
146}
147
148/** The hold with `text` added, or null when it isn't holding (a release won the race), so the delivery passes. */
149export function holdAppend(cur: Hold, text: string): Hold | null {
150 return cur.isHolding ? { ...cur, items: [...cur.items, text] } : null
151}
152
153/**
154 * The hold after a prompt that took `taken` (when the hold was at `gen`) was
155 * refused further down, or null when the hold has been released or restarted
156 * since and must not be revived. A prompt that ended the hold gives it back,
157 * items first; one that took nothing leaves another prompt's handoff alone.
158 */
159export function restoreHold(cur: Hold, taken: readonly string[], gen: number, didEnd: boolean): Hold | null {
160 if ((cur.gen ?? 0) !== gen) return null
161 if (!didEnd) return cur
162 return { ...cur, isHolding: true, endsAtTurn: false, items: [...taken, ...cur.items] }
163}
164
165/** The held deliveries, in the order they arrived, for the prompt that ends the hold. */
166export function heldNotice(items: readonly string[]): string {
167 return (
168 'relay held these messages while it compacted the conversation, so none would start a turn before the continuation prompt. They arrived in this order:\n\n' +
169 items.join('\n\n')
170 )
171}
172
173/** A plugin's submitted prompt doesn't expand `@` mentions, so the model is told to read them. */
174export function forSubmit(text: string): string {
175 return `Read every file below whose path is prefixed with @ before doing anything else (they are not attached automatically), then continue.\n\n${text}`
176}
177
178/**
179 * Whether a compaction rejection means the person cancelled it (Esc or
180 * Ctrl+C). Claude Code 2.1.294 rejects with "Compaction canceled.".
181 */
182export function isCanceled(message: string): boolean {
183 return /\bcancel(?:l?ed)?\b/i.test(message)
184}
185
186export function parseArgs(args: string): Command {
187 const trimmed = args.trim()
188 switch (trimmed.toLowerCase()) {
189 case 'status':
190 return { kind: 'status' }
191 case 'cancel':
192 return { kind: 'cancel' }
193 case 'paste':
194 return { kind: 'paste' }
195 default:
196 return { kind: 'start', focus: trimmed }
197 }
198}
199types/index.d.ts 68 lines1export type Deliver = 'fill' | 'submit'
2
3export type Config = {
4 deliver: Deliver
5 compactInstructions: string
6 copyToClipboard: boolean
7 /** Where handoff notes go; empty for the system temp directory's claude-relay/. */
8 noteDir: string
9 /** Replaces the save turn's first step; empty for the default (update stale docs in place). */
10 saveInstructions: string
11 /** Fill the box as compaction starts (true) or once it has finished (false). */
12 fillDuringCompaction: boolean
13}
14
15/**
16 * Background deliveries (task notifications, other sessions' messages) held
17 * from the save turn's start until the person's next prompt, which carries
18 * them, and until that prompt's turn starts.
19 */
20export type Hold = {
21 isHolding: boolean
22 /** The held prompts' text, in arrival order. */
23 items: string[]
24 /**
25 * The person's prompt took what was held; the hold lasts until its turn
26 * starts, and what arrives in between is resubmitted then.
27 */
28 endsAtTurn: boolean
29 /** Bumped when the hold starts or is released, so a late rollback can't revive a hold that ended. */
30 gen: number
31}
32
33/**
34 * idle: nothing running. saving: the save turn was submitted and hasn't
35 * ended. continuing: the save turn ended; forking, compacting, delivering.
36 */
37export type Phase = 'idle' | 'saving' | 'continuing'
38
39export type Run = {
40 phase: Phase
41 /** Bumped on every start and cancel, so a stale continuation stops itself. */
42 runId: number
43 /** The save turn's id, once its turn.start is seen. */
44 saveTurnId: string | null
45 startedAt: number | null
46 /** Where the save turn's final message (the handoff note) is written. */
47 notePath: string | null
48}
49
50/** The last continuation prompt, kept in $.store across sessions for /relay paste. */
51export type SavedPrompt = {
52 text: string
53 at: number
54 sessionId: string
55}
56
57export type Command =
58 | { kind: 'start'; focus: string }
59 | { kind: 'status' }
60 | { kind: 'cancel' }
61 | { kind: 'paste' }
62
63declare module 'claude-code' {
64 interface PluginState {
65 relay: { run: Run; hold: Hold }
66 }
67}
68