Past a context size you set, at a good stopping point, moves the work to a fresh session with a handoff Claude writes.

Every model call re-reads the whole session, mostly as cache reads, and accuracy drops as the context grows. handoff watches the context size. Past a size you set, at a good stopping point, it has Claude write a short handoff over the warm cache, runs /clear, and seeds the fresh session with that handoff. The old session stays resumable. You never lose a prompt, a draft, or the old session.
Success means fewer cache-read tokens per turn in long sessions, measured against the shadow baseline that off mode logs.
Status: early. The tests pass against Claude Code 2.1.302. Parts of the handoff have been watched in live terminals (a hand run on 2.1.299, tmux harness runs on 2.1.299 through 2.1.302, the latest on 2026-10-17 after the
register.tsxsplit); the rest has not. See What has been verified live and What has not been verified.
Type this at the prompt of a Claude Code terminal session:
/plugin install handoff --marketplace mikelane/thrift
Answer y to add the marketplace, then choose a scope. To run it from a checkout instead:
claude --plugin-dir ~/dev/thrift/plugins/handoff
handoffMode is off by default. Change it in /config.
| Mode | What it does |
|---|---|
off | Acts on nothing. Logs a shadow record for every evaluation, so you can see what ask or act would have done. |
ask | Shows a band above the prompt with buttons. Nothing happens until you press one. |
act | Hands off or compacts on its own. |
/handoff hands off at any time, in every mode, including off.
1 + the advisor calls, and the smaller of that and the session's reported size is the context size. Subagent steps are ignored.compactBeforeClear on, the line stays up for the whole compaction, which took about 30 seconds on 2.1.299, so "a few seconds" understates it there. The status line shows whatever started the handoff: a band press, act mode, /handoff, or a held prompt handed off first. Presses and hotkeys do nothing while it is up. It comes down when the clear runs, when the handoff is abandoned, or when a step throws. If you type /clear before it goes up, it goes up in the fresh session and comes down just before the note is delivered there. While a turn is running (step 3) it reads "Handoff note written. The handoff continues when the current turn ends. Your prompts stay held.", and that text is a toast too.compactBeforeClear is on, compact the old session now, after the wait, so the compaction never lands inside a turn. A failed or vetoed compaction is logged and the handoff goes on. A successful one writes no record of its own. The record that ends the handoff carries compacted_before_clear instead, so a handoff that stops later still shows the session was compacted. If a turn started during the compaction, go back to step 3./handoff: stop. Nothing is cleared. A toast and a transcript line say the work's results would reach a fresh session without this conversation, whether the session was compacted, and that typing /handoff hands off anyway. Held prompts go back as they do on any failure, and a none record with reason background_busy is written./handoff: go on, as it does when it starts while work is busy./clear after the last check for a running turn. $.command.run only queues the command, so the clear does not run in the same tick. A prompt the engine queued earlier (a peer's message, a task notification) runs first, in the old session, so a turn can still start before the clear takes effect. Such a turn is a late turn: it adds the "A turn ran in the previous session" line in step 6 and sets late_turn on the cleared record. The plugin reports a late turn; it does not prevent one. A person's /clear queued ahead of the plugin's counts too: the plugin sees it through its own command.run hook. On 2.1.302 the engine does not run that hook for the plugin's own clear (it logs a re-entry skip), so the hook sees only other clears. The hook still ignores a clear whose origin is { kind: 'plugin', name: 'handoff' }, as a safeguard in case an engine release stops skipping it. The session end that clear causes is not taken for the plugin's, nor is the end of one that was still running when the plugin issued its clear, and a turn in the session either clear made is a late turn. The plugin's clear then wipes that session, and the record says handoff. A /clear that another hook answers in its place ends no session and is not counted. command.run takes no priority, and the declarations give no read of the prompt queue. A session.receive hook can take a delivery before it is queued (a peer's message, or a relay's event or trigger under origin task-notification) by returning { consumed }, so one that arrives during the handoff could be held and sent after the clear. The plugin does not do that yet.claude --resume <id>"); the note itself is not rewritten.claude --resume <id>". If both were refused and it was put in the prompt box instead, the note is not sent until you press Enter: "Handed off. The note summarizing the previous session is in your prompt box. Press Enter to send it. To reopen the full previous conversation: claude --resume <id>". If nothing could carry it: "The handoff note could not be added to this session. To reopen the full previous conversation: claude --resume <id>". Claude Code puts the plugin's name in front of its toasts and transcript lines, so the plugin's own strings carry no handoff: prefix.cleared record's held_other_delivery field says how those groups went. This holds whether the handoff was started by handing it off first or by running /handoff while the prompt was held. A held prompt from a person (this terminal, the bridge, or the SDK) is submitted as their own words, so the model reads it bare, with no "The handoff plugin sent a message" in front. That goes for every way the plugin sends one again: after the clear, a prompt that arrived while the delivery ran, Hand off and send it, Send here, and the restore after an abandoned handoff. The plugin's own note and a scheduled prompt keep the plugin's name in front. Hooks and the transcript still show the plugin as the sender of all of them. A person's prompt follows the note, so it is not submitted when the note did not enter the fresh session as a message (it was left in the prompt box or written to the transcript), for an attended and a scheduled handoff alike. It is held back after the note instead: in the prompt box if it was typed at this terminal, otherwise in the transcript. That includes a prompt that arrives while the delivery runs. Scheduled prompts are still submitted. A prompt that arrives while this step runs is held too. It is delivered after everything above, one prompt at a time in the order it arrived, the same way: submitted, then put in the prompt box if it was typed at this terminal, then written to the transcript. A prompt from the bridge, the SDK, or a scheduled trigger is never put in the box: its sender is not at the terminal, and filling the box could displace the draft of the person who is. It never enters ahead of the note or the held prompts, but one of them left in the prompt box waits for Enter, so a later prompt can run first. Claude Code leaves the text of a prompt it dropped in the prompt box, so the plugin takes that text back out of the box for every prompt typed at this terminal:one then two would be held as one and onetwo. The clear is skipped for a prompt the handoff has already taken to deliver or put back, since a restore may have put its text back in the box. The clear can run before Claude Code has put the text back, so the plugin also remembers the text it left until a clear finds and removes it. If the next prompt arrives as that text followed by the new one (five, then fivesix), only the part after it is held (six). A prompt that merely starts like the earlier one is kept whole once a clear has removed the leftover, or once the plugin has put a held prompt back in the box for the person to send. One case is stripped wrongly: the clear never found the leftover, the person cleared the box by hand, and the next prompt really does start with the same text. yes is held, the box is cleared by hand, then yes please is typed, and it is held as please, space first. The plugin cannot tell that from a joined prompt. leftover_strips in the record that ends the handoff counts every strip, so a handoff where this may have happened shows a value above 0.act runs, since the handoff sends that prompt itself. This clear can also run before Claude Code has put the text back, so the prompt is remembered and stripped from the front of the next one the same way, and counted in leftover_strips.Only the lines that match the prompt are removed: for a group, its last prompt typed at this terminal, even when a bridge or SDK prompt joined it. Any other text in the box is kept. A draft line that is word for word the same as the prompt just sent is removed too.
Every step that runs a command, a compaction, or a prompt submission is scheduled through the clock, because Claude Code refuses them inside a hook that the turn is waiting on.
The signal is none under the threshold. At or over it:
| Signal | When |
|---|---|
| strong | A finished task, or a prompt that names new work, and no background work is running |
| weak | Anything else over the threshold, including a stopping point while background work is running |
A finished task is a main-session Bash call in this turn that succeeded with git commit, git push, gh pr create, or gh pr merge.
git -C <dir> and leading VAR=value assignments are accepted.--dry-run is rejected. -n is rejected for push only, because commit -n still commits.;, |, &, &&, ||, and newlines. Text in quotes, a # comment, or a heredoc body is not a command, and a <<EOF inside quotes or a comment opens no heredoc.A prompt that names new work is a prompt typed by a person whose tickets and PRs are all new: earlier prompts named work, and this prompt names only references that none of them named.
| Reference | Counts as | Rule |
|---|---|---|
ENG-12 | A ticket | Only under a prefix the current git branch names (alice/eng-42-fix names ENG) or that a Linear (/issue/) or Jira (/browse/) URL in any prompt named. So UTF-8 then UTF-16 is never new work. |
PR #12, pr 12, issue #12, pull request 12 | A PR or issue | Case-insensitive. |
.../pull/12, .../issues/12 | A PR or issue | Any URL. |
#12 | Nothing | A bare number does not count. |
Outside a git repo only URLs name prefixes. The branch is read with a five-second timeout, and only when the prompt holds a ticket-shaped token.
Background work is a subagent with status pending, running, or waiting, or a background Bash or Monitor task that has not reported back. A <task-notification> prompt that carries the task id marks it done, and so does a TaskStop or KillShell call that was not denied. Task ids are validated against ^[A-Za-z0-9_-]+$. If the agent list cannot be read, the plugin assumes background work is running. Background work survives a clear and reports in the fresh session (seen with background Bash on 2.1.299; subagents were not tested). Its results would reach a session that has only the note, not the conversation that started the work, so background work turns a strong signal into a weak one.
| Signal | off | ask | act |
|---|---|---|---|
| Strong, finished task | Log only | Band: Hand off and clear, Not now | Hand off |
| Strong, prompt names new work | Log only | Hold the prompt and refill the box (only a prompt typed in this terminal; one from the bridge or an SDK client runs at once, and the turn it starts can still raise the band). Band: Hand off and send it, Send here. Enter again sends it here. | Drop the prompt, hand off, resend it in the fresh session |
| Weak, background work running | Log only | Band: Compact, Not now. No handoff button. | Compact |
| Weak, otherwise | Log only | Band: Compact, Hand off and clear, Not now | Compact |
A weak signal is acted on at the end of a turn. A prompt that names new work while the signal is weak only logs.
Special cases:
/loop acts on a strong signal in every mode except off, and ignores a weak signal. That covers the prompt itself and the end of the turn it started. A scheduled prompt a handoff held and sends again, in the fresh session or back in this one, is still treated this way: prompt.submit takes no origin, so the plugin marks the turn itself. It is also submitted under the plugin's name, not as a person's words, because nobody typed it.claude -p or the SDK the plugin only logs. The process can exit before a handoff ends, and a held prompt would be lost.composer, bridge, sdk, and scheduled-trigger count), and any prompt that arrives while a compaction is pending./clear never runs inside its turn./clear ends the session too, and that is not counted./clear: the handoff runs no second clear. The note (with the turn-after-note line, if it applies) and the held prompts go into the fresh session you made, as they would after the handoff's own clear, and the record is cleared./resume and so on): the handoff stops. Nothing is cleared and no note is added. A toast and a transcript line say the handoff stopped because the session ended and no note was carried over, held prompts go back as they do on any failure, and a none record with reason session_ended is written.The band draws above the prompt from a typed atom. It states the context in thousands, says that accuracy drops as context grows, and varies its wording for a held prompt, a finished task, background work, or plain size. In ask mode a dim hint line says how to answer and that handoffMode act does this without asking. It yields to a survey. A band that cannot be taken down does not stop later turns from being evaluated.
c: Compact, h: Hand off and clear, 0: Not now. Hand off is h, Compact is c, Send here is s, and Not now is 0. A held-prompt band has h: Hand off and send it and s: Send here, and no 0.1 to answer one of Claude's numbered questions. Typing 0 into an empty prompt dismisses. The letters work once the band has the keyboard: press ctrl+x Tab, or click a button (fullscreen). The held-prompt band never takes 0, because the box holds the prompt.autoFocus and variant="primary", so ctrl+x Tab then Enter runs it. A plain terminal button draws the same with or without variant, so the recommendation shows as the button focus lands on and as the action the hint line names, not as a highlight. A desktop surface draws it as the primary button.ask mode it ends by saying handoffMode act does this without asking.hooks/register.tsx 331 lines1import type { EngineInterface, On, Register, PromptSubmitInput, TurnCompleteInput } from 'claude-code'
2
3import {
4 claimAndRunPress,
5 drawBand,
6 offerBand,
7 readBand,
8 refreshBandBusyState,
9 takeDownBand,
10 takeDownBandFromBeforeReload,
11 type PressActions,
12} from './band-controller'
13import { snapshotTrigger, type Trigger } from './decision-record'
14import { announce } from './announcement'
15import { registerHandoffCommand } from './command-registration'
16import { debug, logFailure } from './engine-log'
17import { startHandoffCommand } from './handoff-command'
18import { submitOrKeepInTranscript } from './handoff-delivery'
19import { isBackgroundBusy } from './background-busy'
20import { scheduleCompaction } from './compaction'
21import { scheduleHandoff } from './handoff-run'
22import { inspectPrompt } from './prompt-inspection'
23import { writeRecord } from './record-writer'
24import { decideDuringHandoff } from './handoff-hold'
25import { noteBoxLeftover } from './box-leftover'
26import { isUntestedEngine } from './engine-version'
27import { clearBoxCopyWhileHeld, composerPrompt, refillBox } from './prompt-box'
28import {
29 canHoldPrompt,
30 carriesExtras,
31 isPersonOrigin,
32 isComposerOrigin,
33 isUnattendedOrigin,
34 planNewWorkPrompt,
35} from './prompt-plan'
36import {
37 createState,
38 endMainTurn,
39 noteCacheReads,
40 forgetForeignClear,
41 recordForeignClear,
42 recordSessionEnd,
43 releaseTurnEndWaiter,
44 resetForNewSession,
45 startMainTurn,
46 startSubagentTurn,
47 endSubagentTurn,
48 type SessionState,
49} from './session-state'
50import { asMode, asThreshold, contextFromStep, type Mode } from './signals'
51import { notifiedTaskId } from './tasks'
52import { noteToolCall } from './tool-call-tracking'
53import { planTurnEnd } from './turn-end-plan'
54
55const HANDING_OFF_FIRST = 'Handing off first. Your prompt will be sent in the fresh session.'
56const HELD_PROMPT = 'Held your prompt. Choose below, or press Enter again to send it here.'
57
58// /handoff is registered only when a person is at the prompt, so only then is it there to mention.
59const untestedEngineNotice = (engineVersion: string, isInteractive: boolean): string =>
60 `Untested on Claude Code ${engineVersion}, so this session only logs decisions.${isInteractive ? ' /handoff still works.' : ''}`
61
62const readVersion = async ($: EngineInterface) => {
63 try {
64 const { version, base } = await $.session.version()
65 return { engineVersion: base ?? version, base }
66 } catch (error) {
67 debug($, `could not read the engine version: ${String(error)}`)
68 return { engineVersion: 'unknown', base: undefined }
69 }
70}
71
72const reportedContext = async ($: EngineInterface): Promise<number | undefined> => {
73 try {
74 return (await $.session.usage()).context.tokens
75 } catch (error) {
76 debug($, `could not read session usage: ${String(error)}`)
77 return undefined
78 }
79}
80
81const evaluateTurnEnd = async (
82 $: EngineInterface,
83 state: SessionState,
84 e: TurnCompleteInput,
85 hasFinishedTask: boolean,
86) => {
87 if (state.pending !== null) return
88 noteCacheReads(state, e.usage?.cache_read_input_tokens)
89 const isBusy = await isBackgroundBusy($, state)
90 const { signal, outcome } = planTurnEnd({
91 contextTokens: state.contextTokens,
92 threshold: state.threshold,
93 hasFinishedTask,
94 isBackgroundBusy: isBusy,
95 mode: state.mode,
96 isUnattended: state.isTurnUnattended,
97 backoffFrom: state.backoffFrom,
98 })
99 const trigger = snapshotTrigger(state, 'turn-end', signal, isBusy)
100 if (outcome.kind === 'back-off') {
101 await takeDownBand($, state)
102 return writeRecord($, state, { ...trigger, action: 'none', reason: 'backoff' })
103 }
104 if (outcome.kind === 'advise') return offerBand($, state, trigger, outcome.holdsPrompt)
105 await takeDownBand($, state)
106 if (outcome.kind === 'compact') return scheduleCompaction($, state, trigger)
107 if (outcome.kind === 'handoff') return scheduleHandoff($, state, { trigger, isUnattended: state.isTurnUnattended })
108 return writeRecord($, state, { ...trigger, action: 'none' })
109}
110
111const refillHeldPrompt = async ($: EngineInterface, state: SessionState, text: string) => {
112 if (state.heldPrompt !== text) return
113 if (await refillBox($, { text })) return
114 if (state.heldPrompt !== text) return
115 state.heldPrompt = null
116 await takeDownBand($, state)
117 await submitOrKeepInTranscript($, state, composerPrompt(text))
118}
119
120const holdPrompt = async ($: EngineInterface, state: SessionState, text: string, trigger: Trigger) => {
121 state.heldPrompt = text
122 $.clock.after(0, () => {
123 void logFailure($, refillHeldPrompt($, state, text))
124 })
125 await offerBand($, state, trigger, true)
126 return { drop: HELD_PROMPT }
127}
128
129const decidePrompt = async ($: EngineInterface, state: SessionState, e: PromptSubmitInput) => {
130 const duringHandoff = decideDuringHandoff($, state, e)
131 if (duringHandoff !== undefined) return duringHandoff
132 const isUnattended = isUnattendedOrigin(e.origin.kind)
133 state.heldPrompt = null
134 state.isTurnUnattended = isUnattended
135 const isNewWork = await inspectPrompt($, state, e.text)
136 const canHold = canHoldPrompt({
137 isNewWork,
138 hasPendingAction: state.pending !== null,
139 hasTurnId: e.turnId !== undefined,
140 hasExtras: carriesExtras(e),
141 })
142 if (!canHold) return null
143 const isBusy = await isBackgroundBusy($, state)
144 const { signal, action } = planNewWorkPrompt({
145 contextTokens: state.contextTokens,
146 threshold: state.threshold,
147 isBackgroundBusy: isBusy,
148 mode: state.mode,
149 isUnattended,
150 isFromComposer: isComposerOrigin(e.origin.kind),
151 })
152 const trigger = snapshotTrigger(state, 'prompt', signal, isBusy)
153 if (action === 'handoff') {
154 // Claude Code leaves the dropped text in the box; the handoff sends the prompt itself, so that copy is taken out first.
155 // That clear can read the box before the text is back, as a held prompt's can, so the text is remembered as the box's
156 // leftover once the hold has begun (beginHandoffHold forgets any earlier one).
157 const isFromComposer = isComposerOrigin(e.origin.kind)
158 const emptyBox = isFromComposer ? () => clearBoxCopyWhileHeld($, state, e.text) : undefined
159 const isClaimed = scheduleHandoff($, state, { trigger, heldPrompt: e.text, heldPromptOrigin: e.origin.kind, isUnattended }, emptyBox)
160 if (isClaimed && isFromComposer) noteBoxLeftover(state, e.text)
161 return isClaimed ? { drop: HANDING_OFF_FIRST } : null
162 }
163 if (action === 'hold') return holdPrompt($, state, e.text, trigger)
164 await writeRecord($, state, { ...trigger, action: 'none' })
165 return null
166}
167
168const pressActionsFor = ($: EngineInterface): PressActions => ({
169 scheduleHandoff: (state, request) => scheduleHandoff($, state, request),
170 scheduleCompaction: (state, trigger) => scheduleCompaction($, state, trigger),
171})
172
173const registerLifecycleHooks = (on: On, state: SessionState, setting: Mode) => {
174 on('session.start', async ($, e, next) => {
175 const started = await next(e)
176 await takeDownBandFromBeforeReload($, state)
177 const { engineVersion, base } = await readVersion($)
178 const isUntested = isUntestedEngine(base)
179 state.engineVersion = engineVersion
180 state.mode = e.isInteractive && !isUntested ? setting : 'off'
181 if (e.isInteractive) await registerHandoffCommand($)
182 if (isUntested) {
183 // In the transcript as well as the toast: a toast can be gone before a screen reader reads it.
184 if (setting !== 'off') announce($, untestedEngineNotice(engineVersion, e.isInteractive))
185 await writeRecord($, state, { ...snapshotTrigger(state, 'session-start', 'none', false), action: 'untested_engine' })
186 }
187 return started
188 }).catch(($, e, next) => next(e))
189
190 // The engine skips the calling plugin's hook for the plugin's own clear (seen live on 2.1.302: the re-entry line), so the
191 // handoff's own clear does not reach this hook. recordForeignClear still drops it by origin as a safeguard. The test kit
192 // skips the whole plugin too, so only the pure tests cover the own-origin branch.
193 // Counted from the note on, before next, since the clear's session end may come inside it (the kit's does). Core sets ref on a run it made; a
194 // hook beneath that answers in the clear's place leaves it off, and a clear that throws ran nothing: no end is coming.
195 // SAFETY: a hook beneath that calls next and then rewrites the output also leaves ref off. The end already spent the count,
196 // so forgetting is a no-op, unless a second foreign clear is still pending, whose count it eats: that clear's end is then
197 // taken for the handoff's, and a late turn after it goes unreported. Needs two queued clears and such a hook. No guard.
198 on('command.run', { command: 'clear' }, async ($, e, next) => {
199 recordForeignClear(state, e.origin)
200 try {
201 const clearOutput = await next(e)
202 if (clearOutput.ref === undefined) forgetForeignClear(state)
203 return clearOutput
204 } catch (error) {
205 forgetForeignClear(state)
206 throw error
207 }
208 }).catch(($, e, next) => next(e))
209
210 on('session.end', async ($, e, next) => {
211 recordSessionEnd(state, e.reason)
212 await takeDownBand($, state)
213 resetForNewSession(state)
214 // A handoff waiting on a turn resumes in a later tick, so it never runs inside this hook.
215 $.clock.after(0, () => releaseTurnEndWaiter(state))
216 if (e.reason === 'clear') {
217 $.clock.after(0, () => {
218 void logFailure($, registerHandoffCommand($))
219 })
220 }
221 return next(e)
222 }).catch(($, e, next) => next(e))
223}
224
225const registerTurnHooks = (on: On, state: SessionState) => {
226 on('turn.step', async function* ($, e, next) {
227 const step = yield* next(e)
228 if (e.agentId === undefined && step.usage) {
229 const reported = await reportedContext($)
230 state.contextTokens = contextFromStep({
231 input: step.usage.input_tokens,
232 created: step.usage.cache_creation_input_tokens,
233 read: step.usage.cache_read_input_tokens,
234 advisorCalls: (step.serverToolUses ?? []).filter(use => use.name === 'advisor').length,
235 reported,
236 })
237 }
238 return step
239 }).catch(async function* ($, e, next) {
240 return yield* next(e)
241 })
242
243 // next<string> skips inferring the tool name from every MCP tool in the types file, which made tsc time grow with the connected servers.
244 on('tool.call', async ($, e, next) => {
245 const ran = await next<string>(e)
246 if (e.agentId === undefined) noteToolCall(state, e, ran)
247 return ran
248 }).catch(($, e, next) => next<string>(e))
249
250 on('turn.start', async ($, e, next) => {
251 if (e.agentId === undefined) startMainTurn(state, e.text)
252 else startSubagentTurn(state, e.turnId)
253 return next(e)
254 }).catch(($, e, next) => next(e))
255
256 on('turn.complete', async ($, e, next) => {
257 const result = await next(e)
258 if (e.agentId !== undefined) {
259 endSubagentTurn(state, e.turnId)
260 return result
261 }
262 const hasFinishedTask = state.hasFinishedTask
263 state.hasFinishedTask = false
264 endMainTurn(state)
265 const deferredPress = state.deferredPress
266 state.deferredPress = null
267 try {
268 if (deferredPress !== null) {
269 noteCacheReads(state, e.usage?.cache_read_input_tokens)
270 await claimAndRunPress($, state, pressActionsFor($), deferredPress)
271 } else if (e.reason === 'answer') await evaluateTurnEnd($, state, e, hasFinishedTask)
272 else await refreshBandBusyState($, state)
273 } finally {
274 // The handoff clears in a later tick: /clear inside the hook the turn is waiting on is refused.
275 // SAFETY: every call in the try block catches its own engine failures (isBackgroundBusy, takeDownBand, writeRecord,
276 // offerBand, refreshBandBusyState), and the toast and log calls return void, so the kit cannot make the block throw
277 // and no test reaches this finally on a throw. Keep it: it is the only thing that frees a waiting handoff if a
278 // future call in the block forgets to catch.
279 $.clock.after(0, () => releaseTurnEndWaiter(state))
280 }
281 return result
282 }).catch(($, e, next) => next(e))
283}
284
285const registerPromptHooks = (on: On, state: SessionState) => {
286 on('prompt.submit', async ($, e, next) => {
287 if (state.heldPrompt !== null && isPersonOrigin(e.origin.kind)) await takeDownBand($, state)
288 const finishedTaskId = e.origin.kind === 'task-notification' ? notifiedTaskId(e.text) : null
289 if (finishedTaskId !== null) state.backgroundTasks.delete(finishedTaskId)
290 // Only the person origins are held or refused during a handoff. A task notification or a peer prompt passes through, in
291 // every phase including the delivery, on purpose (decided on #6): it does not come from the person, so it has no place in
292 // the order of their prompts.
293 const dropped = isPersonOrigin(e.origin.kind) ? await decidePrompt($, state, e) : null
294 return dropped ?? next(e)
295 }).catch(($, e, next) => next(e))
296
297 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
298 const band = await readBand($)
299 if (e.props.hasSurvey || band === null) return next(e)
300 return drawBand($, state, pressActionsFor($), e, band)
301 }).catch(($, e, next) => next(e))
302
303 // SAFETY: startHandoffCommand's only await is isBackgroundBusy, which catches its own failures, so no test reaches this catch.
304 // Keep it: every hook must never break a turn.
305 on('command.run', { command: 'handoff' }, $ => startHandoffCommand($, state)).catch(() => ({
306 text: 'Could not start a handoff.',
307 }))
308}
309
310export const register: Register = (on, options) => {
311 const setting = asMode(options.handoffMode)
312 // SAFETY: a reload that runs register again gives the new state pending null and nothing held. On 2.1.299 a setting
313 // changed in /config did so (a handoff right after one recorded context_tokens 0); /reload-plugins kept the old
314 // state. A handoff already running keeps the old state and its old closures. Its prompts are no longer held, so they
315 // pass through and /clear can land inside their turn. The old hooks are gone too, so nothing releases a wait for a
316 // turn to end, and that handoff waits forever and never clears. Both need a reload while a handoff runs, from the
317 // note being written until its prompts are delivered. No guard: carrying the state across a reload would need it in
318 // an atom.
319 // After a reload, run /handoff again.
320 const state = createState({
321 setting,
322 threshold: asThreshold(options.handoffContextTokens),
323 compactBeforeClear: options.compactBeforeClear === true,
324 continueAfterHandoff: options.continueAfterHandoff === true,
325 })
326
327 registerLifecycleHooks(on, state, setting)
328 registerTurnHooks(on, state)
329 registerPromptHooks(on, state)
330}
331hooks/band-controller.tsx 229 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, RenderInput } from 'claude-code'
3
4import type { BandState, Offer, Writing } from '../types'
5import {
6 BUTTON_LABELS,
7 bandControls,
8 bandHint,
9 bandMessage,
10 clearsSession,
11 isSameOffer,
12 isWriting,
13 offerWithBusyState,
14 statusText,
15} from './band-text'
16import { isBackgroundBusy } from './background-busy'
17import { snapshotTrigger, type HandoffRequest, type Trigger } from './decision-record'
18import { debug, logFailure } from './engine-log'
19import { sendOrKeepInBox } from './handoff-delivery'
20import { ALREADY_PENDING, busyRefusalMessage } from './handoff-note'
21import { composerPrompt, emptyBoxIfHolding } from './prompt-box'
22import { writeRecord } from './record-writer'
23import type { ButtonPress, SessionState } from './session-state'
24import { bandButtons, busyRefusalTrigger, type Button } from './signals'
25
26const PRESS_WAITS_FOR_TURN = 'This turn is still running, so your choice will run when it ends.'
27const PROMPT_NOT_HELD = 'That prompt is no longer held, so there is nothing to send.'
28
29// What a press can start, with $ already bound. handoff-run.tsx imports this module, so importing scheduleHandoff here
30// would make a cycle; register.tsx builds both actions from handoff-run.tsx and compaction.tsx instead.
31export type PressActions = {
32 scheduleHandoff: (state: SessionState, request: HandoffRequest) => boolean
33 scheduleCompaction: (state: SessionState, trigger: Trigger) => boolean
34}
35
36// The shape names the Offer fields, so a reload finds an offer an older version wrote (heldPrompt, not hasHeldPrompt) absent.
37const offerAtom = atom({ plugin: 'handoff', key: 'offer' } as const, null, { shape: 'offer-has-held-prompt' })
38
39export function readBand($: EngineInterface): Promise<BandState | null> {
40 return read($, offerAtom)
41}
42
43export async function takeDownBand($: EngineInterface, state: SessionState): Promise<void> {
44 if (!state.hasBand) return
45 try {
46 await update($, offerAtom, () => null)
47 state.hasBand = false
48 } catch (error) {
49 debug($, `could not take down the band: ${String(error)}`)
50 }
51}
52
53// The offer atom outlives a reload but `state.hasBand` does not, so a band left up would stick.
54export async function takeDownBandFromBeforeReload($: EngineInterface, state: SessionState): Promise<void> {
55 try {
56 if ((await read($, offerAtom)) !== null) state.hasBand = true
57 } catch (error) {
58 debug($, `could not read the band: ${String(error)}`)
59 }
60 await takeDownBand($, state)
61}
62
63export async function offerBand($: EngineInterface, state: SessionState, trigger: Trigger, hasHeldPrompt: boolean): Promise<void> {
64 const raisedSignal = trigger.signal === 'strong' ? 'strong' : 'weak'
65 const offer: Offer = {
66 signal: raisedSignal,
67 contextTokens: trigger.contextTokens,
68 hasHeldPrompt,
69 isBusy: trigger.isBusy,
70 }
71 try {
72 await update($, offerAtom, () => offer)
73 state.hasBand = true
74 state.bandRaisedSignal = raisedSignal
75 await writeRecord($, state, { ...trigger, action: 'advised' })
76 } catch (error) {
77 debug($, `could not show the band: ${String(error)}`)
78 await writeRecord($, state, { ...trigger, action: 'none', reason: 'band_failed' })
79 }
80}
81
82export async function redrawBand($: EngineInterface, state: SessionState, band: BandState): Promise<void> {
83 try {
84 await update($, offerAtom, () => band)
85 state.hasBand = true
86 } catch (error) {
87 debug($, `could not redraw the band: ${String(error)}`)
88 }
89}
90
91// Only the band the press was made on may be redrawn: one taken down or replaced since stays as it is.
92async function redrawIfStillShown($: EngineInterface, state: SessionState, shown: Offer, redrawn: Offer): Promise<void> {
93 try {
94 const current = await read($, offerAtom)
95 if (current !== null && isSameOffer(current, shown)) await redrawBand($, state, redrawn)
96 } catch (error) {
97 debug($, `could not read the band: ${String(error)}`)
98 }
99}
100
101// A turn that ends without an answer gets no evaluation, so a band left up could still offer a handoff over work
102// that started during it.
103export async function refreshBandBusyState($: EngineInterface, state: SessionState): Promise<void> {
104 try {
105 const offer = await read($, offerAtom)
106 if (offer === null || isWriting(offer)) return
107 const isBusy = await isBackgroundBusy($, state)
108 if (offer.isBusy !== isBusy) await redrawBand($, state, offerWithBusyState(offer, state.contextTokens, isBusy, state.bandRaisedSignal))
109 } catch (error) {
110 debug($, `could not read the band: ${String(error)}`)
111 }
112}
113
114async function refuseToClear($: EngineInterface, state: SessionState, offer: Offer, trigger: Trigger): Promise<void> {
115 $.ui.toast(busyRefusalMessage(false))
116 await redrawIfStillShown($, state, offer, offerWithBusyState(offer, state.contextTokens, true, state.bandRaisedSignal))
117 await writeRecord($, state, { ...busyRefusalTrigger(trigger), action: 'none', reason: 'background_busy' })
118}
119
120async function pressHeldPromptButton(
121 $: EngineInterface,
122 state: SessionState,
123 actions: PressActions,
124 trigger: Trigger,
125 button: Button,
126): Promise<void> {
127 const heldPrompt = state.heldPrompt
128 if (heldPrompt === null) {
129 debug($, `dropped a ${button} press: no prompt is held`)
130 $.ui.toast(PROMPT_NOT_HELD)
131 return takeDownBand($, state)
132 }
133 state.heldPrompt = null
134 await takeDownBand($, state)
135 await emptyBoxIfHolding($, heldPrompt)
136 if (button === 'handoff-send' && actions.scheduleHandoff(state, { trigger, heldPrompt, isUnattended: false })) return
137 await writeRecord($, state, { ...trigger, action: 'none', reason: 'send_here' })
138 $.clock.after(0, () => {
139 void logFailure($, sendOrKeepInBox($, state, composerPrompt(heldPrompt)))
140 })
141}
142
143// Busyness is read when the press runs, not taken from the offer: a shell may have started since the band was drawn.
144async function runPress($: EngineInterface, state: SessionState, actions: PressActions, { offer, button }: ButtonPress): Promise<void> {
145 const isBusy = await isBackgroundBusy($, state)
146 if (state.pending !== null) {
147 debug($, `dropped a ${button} press: a ${state.pending} is already pending`)
148 return $.ui.toast(ALREADY_PENDING)
149 }
150 const trigger = snapshotTrigger(state, 'button', offer.signal, isBusy)
151 if (isBusy && clearsSession(button)) return refuseToClear($, state, offer, trigger)
152 if (button === 'handoff-send' || button === 'send-here') return pressHeldPromptButton($, state, actions, trigger, button)
153 if (button === 'not-now') state.backoffFrom = state.contextTokens
154 else if (button === 'compact') actions.scheduleCompaction(state, trigger)
155 else return void actions.scheduleHandoff(state, { trigger, isUnattended: false })
156 await takeDownBand($, state)
157 if (button === 'not-now') await writeRecord($, state, { ...trigger, action: 'none', reason: 'not_now' })
158}
159
160// runPress awaits the busy check before it claims anything, so the press is marked in flight in the same tick:
161// a second press, Not now included, is dropped until this one settles.
162export async function claimAndRunPress(
163 $: EngineInterface,
164 state: SessionState,
165 actions: PressActions,
166 press: ButtonPress,
167): Promise<void> {
168 state.isPressRunning = true
169 try {
170 await runPress($, state, actions, press)
171 } finally {
172 state.isPressRunning = false
173 }
174}
175
176// A press that clears or compacts made mid-turn waits, so /clear and compaction never land inside a turn. The first
177// press wins; the band stays up until it runs, and it runs at the end of that turn in place of a fresh evaluation.
178// Not now has no such hazard, so it runs at once.
179async function pressButton($: EngineInterface, state: SessionState, actions: PressActions, offer: Offer, button: Button): Promise<void> {
180 if (state.pending !== null || state.deferredPress !== null || state.isPressRunning) {
181 return debug($, `dropped a ${button} press: another press or a handoff or compaction comes first`)
182 }
183 if (!state.isTurnRunning || button === 'not-now') return claimAndRunPress($, state, actions, { offer, button })
184 state.deferredPress = { offer, button }
185 $.ui.toast(PRESS_WAITS_FOR_TURN)
186}
187
188function drawWritingStatus($: EngineInterface, e: RenderInput<'AbovePrompt'>, band: Writing) {
189 const { Box, Text } = $.ui.resolve(e)
190 return (
191 <Box flexDirection="column" backgroundColor="subtle">
192 <Text>{statusText(band)}</Text>
193 </Box>
194 )
195}
196
197function drawOffer($: EngineInterface, state: SessionState, actions: PressActions, e: RenderInput<'AbovePrompt'>, offer: Offer) {
198 const { Box, Text, Button } = $.ui.resolve(e)
199 return (
200 <Box flexDirection="column" backgroundColor="subtle">
201 <Text>{bandMessage(offer)}</Text>
202 <Box flexWrap="wrap" columnGap={2}>
203 {bandControls(bandButtons(offer)).map(({ button, hotkey, isPrimary, isDismiss }) => (
204 <Button
205 key={button}
206 label={BUTTON_LABELS[button]}
207 hotkey={hotkey}
208 plain
209 {...(isPrimary ? { variant: 'primary' as const, autoFocus: true as const } : {})}
210 {...(isDismiss ? { role: 'dismiss' as const } : {})}
211 onPress={() => logFailure($, pressButton($, state, actions, offer, button))}
212 />
213 ))}
214 </Box>
215 <Text dimColor>{bandHint(offer)}</Text>
216 </Box>
217 )
218}
219
220export function drawBand(
221 $: EngineInterface,
222 state: SessionState,
223 actions: PressActions,
224 e: RenderInput<'AbovePrompt'>,
225 band: BandState,
226) {
227 return isWriting(band) ? drawWritingStatus($, e, band) : drawOffer($, state, actions, e, band)
228}
229hooks/decision-record.ts 184 lines1import type { ContinueFields, ContinueSkip } from './continue-decision'
2import type { DecisionReason } from './decision-reasons'
3import type { ForkReason } from './fork-outcome'
4import type { NoteDelivery } from './handoff-note'
5import type { GroupDelivery } from './held-delivery'
6import type { HeldPrompt, HeldPromptGroup, SessionState } from './session-state'
7import type { Mode, Signal } from './signals'
8
9export type { DecisionReason }
10
11// Who ran the clear that a `cleared` record follows: the person's own /clear during the wait, or the handoff's.
12export type ClearedBy = 'person' | 'handoff'
13
14export type DecisionAction = 'none' | 'advised' | 'cleared' | 'compacted' | 'untested_engine'
15
16export type TriggerValues = {
17 point: 'turn-end' | 'prompt' | 'command' | 'button' | 'session-start'
18 signal: Signal
19 context_tokens: number
20 threshold: number
21 is_background_busy: boolean
22 setting: Mode
23 cache_read_tokens: number
24 reason?: DecisionReason
25 fork_reason?: ForkReason
26 note?: NoteDelivery
27 held_groups?: number
28 held_unattended?: boolean
29 handoff_unattended?: boolean
30 held_other_delivery?: GroupDelivery
31 held_restore?: GroupDelivery
32 leftover_strips?: number
33 cleared_by?: ClearedBy
34 compacted_before_clear?: true
35 late_turn?: true
36 continued?: ContinueFields['continued']
37 continue_skip?: ContinueSkip
38}
39
40type HeldGroupFields = Required<Pick<TriggerValues, 'held_groups' | 'held_unattended'>>
41
42export type HeldRecordFields = HeldGroupFields &
43 Pick<TriggerValues, 'handoff_unattended' | 'held_other_delivery' | 'held_restore' | 'leftover_strips'>
44
45export const heldGroupFields = (groups: readonly HeldPromptGroup[]): HeldGroupFields => ({
46 held_groups: groups.length,
47 held_unattended: groups.some(group => group.isUnattended),
48})
49
50// Present only when a held prompt had a leftover taken off its front, like the other fields that only an event sets.
51export const leftoverStripFields = (strips: number): Pick<TriggerValues, 'leftover_strips'> => (strips > 0 ? { leftover_strips: strips } : {})
52
53type RecordInput = {
54 now: number
55 sessionId: string
56 action: DecisionAction
57 engineVersion: string
58 effectiveMode: Mode
59 triggerValues: TriggerValues
60}
61
62export type Trigger = {
63 point: TriggerValues['point']
64 signal: Signal
65 isBusy: boolean
66 contextTokens: number
67 cacheReadTokens: number
68 effectiveMode: Mode
69}
70
71export type Evaluation = Trigger & {
72 action: DecisionAction
73 reason?: DecisionReason
74 forkReason?: ForkReason
75 note?: NoteDelivery
76 clearedBy?: ClearedBy
77 compactedBeforeClear?: boolean
78 lateTurn?: boolean
79 continueFields?: ContinueFields
80 heldFields?: HeldRecordFields
81 sessionId?: string
82}
83
84export type HandoffRequest = {
85 trigger: Trigger
86 heldPrompt?: string
87 // The origin kind of heldPrompt; the composer when absent, as for a prompt held in the box.
88 heldPromptOrigin?: HeldPrompt['origin']
89 isUnattended: boolean
90}
91
92// What a handoff delivers once its held prompts are taken: one group per origin, each following its own flag.
93export type SettledHandoff = {
94 trigger: Trigger
95 isUnattended: boolean
96 heldGroups: HeldPromptGroup[]
97 hasCompactedBeforeClear?: boolean
98}
99
100export type RecordSessionFields = Pick<
101 SessionState,
102 'mode' | 'setting' | 'threshold' | 'engineVersion' | 'contextTokens' | 'cacheReadTokens'
103>
104
105// What a record reads from the session when it is written. The mode and sizes come from the evaluation's snapshot.
106export type RecordStateFields = Pick<SessionState, 'setting' | 'threshold' | 'engineVersion'>
107
108export const snapshotTrigger = (state: RecordSessionFields, point: Trigger['point'], signal: Signal, isBusy: boolean): Trigger => ({
109 point,
110 signal,
111 isBusy,
112 contextTokens: state.contextTokens,
113 cacheReadTokens: state.cacheReadTokens,
114 effectiveMode: state.mode,
115})
116
117// umask only applies when the file is created, so a log that already exists is made owner-only by the chmod. `mkdir -p --`
118// works on BSD and GNU alike. chmod takes no `--`: BSD chmod (macOS) reads it as a file operand, sets the mode, then fails on it
119// and exits 1, while GNU chmod accepts it. The file is always absolute (see isUsableThriftHome), so it cannot read as an option.
120export const LOG_WRITER = ['sh', '-c', 'umask 077 && mkdir -p -- "$1" && cat >> "$2" && chmod 600 "$2"', 'sh'] as const
121
122// A person asked for these, so the plugin acted on their request whatever mode it ran in.
123const isPersonAction = (point: TriggerValues['point']): boolean => point === 'command' || point === 'button'
124
125export const decisionRecord = ({ now, sessionId, action, engineVersion, effectiveMode, triggerValues }: RecordInput) => ({
126 ts: new Date(now).toISOString(),
127 session_id: sessionId,
128 component: 'handoff',
129 mode: action === 'none' && effectiveMode === 'off' && !isPersonAction(triggerValues.point) ? 'shadow' : 'active',
130 action,
131 engine_version: engineVersion,
132 trigger_values: { ...triggerValues, effective_mode: effectiveMode },
133})
134
135export type DecisionRecord = ReturnType<typeof decisionRecord>
136
137export const recordFromEvaluation = (
138 state: RecordStateFields,
139 evaluation: Evaluation,
140 now: number,
141 sessionId: string,
142): DecisionRecord => {
143 const { action, point, signal, isBusy, contextTokens, cacheReadTokens, effectiveMode, reason, forkReason, note, clearedBy, compactedBeforeClear, lateTurn, continueFields, heldFields } = evaluation
144 const compactedFields: Pick<TriggerValues, 'compacted_before_clear'> = compactedBeforeClear ? { compacted_before_clear: true } : {}
145 const lateTurnFields: Pick<TriggerValues, 'late_turn'> = lateTurn ? { late_turn: true } : {}
146 return decisionRecord({
147 now,
148 sessionId,
149 action,
150 engineVersion: state.engineVersion,
151 effectiveMode,
152 triggerValues: {
153 point,
154 signal,
155 context_tokens: contextTokens,
156 threshold: state.threshold,
157 is_background_busy: isBusy,
158 setting: state.setting,
159 cache_read_tokens: cacheReadTokens,
160 ...(reason ? { reason } : {}),
161 ...(forkReason ? { fork_reason: forkReason } : {}),
162 ...(note ? { note } : {}),
163 ...(clearedBy ? { cleared_by: clearedBy } : {}),
164 ...compactedFields,
165 ...lateTurnFields,
166 ...continueFields,
167 ...heldFields,
168 },
169 })
170}
171
172// A relative THRIFT_HOME, or one that starts with ~, would resolve against the session's working directory, not the home.
173export const isUsableThriftHome = (thriftHome: string | undefined): thriftHome is string => thriftHome?.startsWith('/') === true
174
175export const logLocation = (
176 thriftHome: string | undefined,
177 home: string | undefined,
178): { dir: string; file: string } | null => {
179 const dir = isUsableThriftHome(thriftHome) ? thriftHome.replace(/\/+$/, '') : home ? `${home.replace(/\/+$/, '')}/.claude/thrift` : null
180 // THRIFT_HOME=/ strips to nothing: the log then goes in the root directory itself, as asked.
181 if (dir === '') return { dir: '/', file: '/decisions.jsonl' }
182 return dir === null ? null : { dir, file: `${dir}/decisions.jsonl` }
183}
184hooks/announcement.tsx 7 lines1import type { EngineInterface } from 'claude-code'
2
3export function announce($: EngineInterface, message: string): void {
4 $.ui.log(message)
5 $.ui.toast(message)
6}
7hooks/command-registration.tsx 15 lines1import type { EngineInterface } from 'claude-code'
2
3import { debug } from './engine-log'
4
5export async function registerHandoffCommand($: EngineInterface): Promise<void> {
6 try {
7 await $.command.register({
8 name: 'handoff',
9 description: 'Write a handoff, clear, and continue in a fresh session',
10 })
11 } catch (error) {
12 debug($, `could not register /handoff: ${String(error)}`)
13 }
14}
15hooks/engine-log.tsx 13 lines1import type { EngineInterface } from 'claude-code'
2
3// Declared as functions: the engine follows `$` past an import only into a function declaration, not a const arrow.
4export function debug($: EngineInterface, line: string): void {
5 return $.ui.log(`handoff: ${line}`, { to: 'debug' })
6}
7
8// SAFETY: every current caller catches its own engine failures, so no test reaches this catch.
9// Keep it: it is the only guard against an unhandled rejection if a future caller forgets.
10export function logFailure($: EngineInterface, work: Promise<unknown>): Promise<unknown> {
11 return work.catch(error => debug($, `background work failed: ${String(error)}`))
12}
13hooks/handoff-command.tsx 24 lines1import type { EngineInterface } from 'claude-code'
2
3import { isBackgroundBusy } from './background-busy'
4import { snapshotTrigger } from './decision-record'
5import { scheduleHandoff } from './handoff-run'
6import { ALREADY_PENDING } from './handoff-note'
7import { emptyBoxIfHolding } from './prompt-box'
8import type { SessionState } from './session-state'
9
10const WRITING_COMMAND_REPLY = 'Writing a handoff for a fresh session...'
11
12export async function startHandoffCommand($: EngineInterface, state: SessionState): Promise<{ text: string }> {
13 const trigger = snapshotTrigger(state, 'command', 'none', await isBackgroundBusy($, state))
14 const heldPrompt = state.heldPrompt
15 const emptyBox = heldPrompt === null ? undefined : () => emptyBoxIfHolding($, heldPrompt)
16 const isClaimed = scheduleHandoff(
17 $,
18 state,
19 { trigger, ...(heldPrompt === null ? {} : { heldPrompt }), isUnattended: false },
20 emptyBox,
21 )
22 return { text: isClaimed ? WRITING_COMMAND_REPLY : ALREADY_PENDING }
23}
24hooks/handoff-delivery.tsx 315 lines1import type { EngineInterface } from 'claude-code'
2
3import { heldGroupFields, leftoverStripFields, type ClearedBy, type SettledHandoff } from './decision-record'
4import { announce } from './announcement'
5import { CONTINUE_PROMPT, decideContinue, type ContinueFields } from './continue-decision'
6import { registerHandoffCommand } from './command-registration'
7import { debug } from './engine-log'
8import {
9 FINAL_MESSAGES,
10 boxCopyOf,
11 deliveryAfterNote,
12 groupHeldPrompts,
13 groupJoiningNote,
14 groupsLeftToSend,
15 handoffMessage,
16 joinPrompts,
17 noteTookGroupAlong,
18 speaksForPerson,
19 type Carried,
20 type NoteDelivery,
21} from './handoff-note'
22import { worstDelivery } from './held-delivery'
23import { inspectPrompt } from './prompt-inspection'
24import { canUseBox, emptySentPromptFromBox, keepInTranscript, markKeptInBox, refillBox } from './prompt-box'
25import { noteOrigin } from './prompt-plan'
26import { writeRecord } from './record-writer'
27import {
28 beginSending,
29 queueResubmittedPrompt,
30 releaseCarried,
31 releaseCarriedGroup,
32 removeResubmittedPrompt,
33 takeLateArrivalsOrEndSending,
34 type BoxPlacement,
35 type HeldPrompt,
36 type HeldPromptGroup,
37 type SessionState,
38} from './session-state'
39
40const UNSENT_NOTE = 'The handoff note could not be sent or put in the prompt box. Here it is:'
41const UNSENT_UNATTENDED_NOTE = 'The handoff note could not be sent, so here it is:'
42// Held back by design, not by a failed send: none was tried, because the note did not enter the fresh session.
43const HELD_BACK_PROMPT = 'Your prompt was held back after the handoff note, so read the note first. Here it is:'
44const HELD_BACK_OTHER_PROMPT = 'A prompt was held back after the handoff note, so read the note first. Here it is:'
45const UNSENT_NOTE_AND_OTHER_PROMPT = 'The handoff note and a prompt could not be sent, so here they are:'
46
47// Declared as functions: the engine follows `$` past an import only into a function declaration, not a const arrow.
48
49// The engine cannot submit a prompt under another origin: the plugin's submission arrives as origin 'plugin', which this
50// plugin's prompt.submit hook does not classify. Submit resolves once the prompt's turn started or once it was queued behind
51// the running turn, so a resolved submit does not mean its turn has begun. So the origin goes into a queue here and the
52// turn.start hook takes it. A hook beneath the plugin that refuses the prompt makes submit resolve with { drop } instead of
53// rejecting.
54async function submitEntered(
55 $: EngineInterface,
56 state: SessionState,
57 prompt: HeldPrompt,
58 failureLabel: string,
59 asUser: boolean,
60): Promise<boolean> {
61 queueResubmittedPrompt(state, prompt)
62 try {
63 const result = await $.prompt.submit(asUser ? { text: prompt.text, asUser: true } : { text: prompt.text })
64 if (result.drop === undefined) return true
65 debug($, `${failureLabel}: ${result.drop}`)
66 } catch (error) {
67 debug($, `${failureLabel}: ${String(error)}`)
68 }
69 removeResubmittedPrompt(state, prompt)
70 return false
71}
72
73export async function submitOrKeepInTranscript($: EngineInterface, state: SessionState, prompt: HeldPrompt): Promise<Carried> {
74 if (await submitEntered($, state, prompt, 'could not restore the held prompt', speaksForPerson(prompt))) return 'submitted'
75 keepInTranscript($, prompt)
76 return 'not_carried'
77}
78
79async function restorePrompt(
80 $: EngineInterface,
81 state: SessionState,
82 prompt: HeldPrompt,
83 placement: BoxPlacement = 'before_draft',
84): Promise<Carried> {
85 if (canUseBox(prompt) && (await refillBox($, prompt, placement))) return markKeptInBox(state)
86 const carried = await submitOrKeepInTranscript($, state, prompt)
87 if (carried === 'submitted') await emptySentPromptFromBox($, state, prompt)
88 return carried
89}
90
91// SAFETY: the record is written after restoreHeldGroups and sendHeldGroups return, so a throw inside either loop would lose
92// the record. refillBox and submitEntered catch their own failures, and keepInTranscript and releaseCarriedGroup make no
93// async calls, so no test can make a loop throw. Any call added to a loop must not throw either.
94export async function restoreHeldGroups($: EngineInterface, state: SessionState, settledHandoff: SettledHandoff): Promise<Carried[]> {
95 const restores: Carried[] = []
96 for (const group of settledHandoff.heldGroups) {
97 restores.push(await restorePrompt($, state, group))
98 releaseCarriedGroup(state, group, settledHandoff.isUnattended)
99 }
100 return restores
101}
102
103type LateArrivals = { prompts: HeldPrompt[]; deliveries: Carried[] }
104
105// Prompts that arrived during a delivery or a restore go back one by one in arrival order, and more may arrive while they do.
106async function forEachLateArrival(
107 state: SessionState,
108 carryPrompt: (prompt: HeldPrompt) => Promise<Carried>,
109): Promise<LateArrivals> {
110 const prompts: HeldPrompt[] = []
111 const deliveries: Carried[] = []
112 for (let arrived = takeLateArrivalsOrEndSending(state); arrived.length > 0; arrived = takeLateArrivalsOrEndSending(state)) {
113 for (const prompt of arrived) deliveries.push(await carryPrompt(prompt))
114 prompts.push(...arrived)
115 }
116 return { prompts, deliveries }
117}
118
119export function restoreLateArrivals($: EngineInterface, state: SessionState): Promise<LateArrivals> {
120 return forEachLateArrival(state, prompt => restorePrompt($, state, prompt, 'after_draft'))
121}
122
123async function appendNote($: EngineInterface, message: string): Promise<boolean> {
124 try {
125 const appended = await $.session.append({ message: { type: 'user', content: [{ type: 'text', text: message }] } })
126 if (appended.deny === undefined) return true
127 debug($, `append denied: ${appended.deny}`)
128 return false
129 // The test kit cannot make the default append reject: a throwing session.append hook is treated as a hook failure,
130 // and the plugin sees a successful append. Whether the live default append can reject is unverified.
131 // Keep it: without it, a rejected append skips the prompt fallback and drops the handoff note.
132 } catch (error) {
133 debug($, `append failed: ${String(error)}`)
134 return false
135 }
136}
137
138// holdBack keeps a prompt out of the fresh session: a person's prompt must not run ahead of a note that never entered it.
139type SendOptions = { placement?: BoxPlacement; notice?: string | undefined; holdBack?: boolean }
140
141export async function sendOrKeepInBox(
142 $: EngineInterface,
143 state: SessionState,
144 prompt: HeldPrompt,
145 { placement = 'before_draft', notice, holdBack = false }: SendOptions = {},
146): Promise<Carried> {
147 if (!holdBack && (await submitEntered($, state, prompt, 'could not send the prompt', speaksForPerson(prompt)))) {
148 await emptySentPromptFromBox($, state, prompt)
149 return 'submitted'
150 }
151 if (canUseBox(prompt) && (await refillBox($, prompt, placement))) return markKeptInBox(state)
152 keepInTranscript($, prompt, holdBack ? (canUseBox(prompt) ? HELD_BACK_PROMPT : HELD_BACK_OTHER_PROMPT) : notice)
153 return 'not_carried'
154}
155
156// A scheduled handoff's note rides with the scheduled group, both under the plugin's frame. An attended handoff's note goes alone
157// and framed, then the person's prompts follow it as the person's own words.
158// A note that is never offered to the box (a scheduled handoff's) gets a notice that does not say it was, and a note joined to
159// a scheduled prompt names both.
160function unsentNoteNotice(note: HeldPrompt, isJoined: boolean): string {
161 if (isJoined) return UNSENT_NOTE_AND_OTHER_PROMPT
162 return canUseBox(note) ? UNSENT_NOTE : UNSENT_UNATTENDED_NOTE
163}
164
165async function deliverNote(
166 $: EngineInterface,
167 state: SessionState,
168 settledHandoff: SettledHandoff,
169 message: string,
170): Promise<NoteDelivery> {
171 if (await appendNote($, message)) return 'appended'
172 const sameOriginGroup = groupJoiningNote(settledHandoff.heldGroups, settledHandoff.isUnattended)
173 const origin = sameOriginGroup?.origin ?? noteOrigin(settledHandoff.isUnattended)
174 // SAFETY: the joined group is a scheduled one, and only a prompt typed at the composer leaves a copy in the box, so boxCopy is
175 // always undefined today and no test can tell whether it is passed on. It stays so a group that does carry one is not lost.
176 const boxCopy = sameOriginGroup === undefined ? undefined : boxCopyOf(sameOriginGroup)
177 const note: HeldPrompt = {
178 text: joinPrompts(message, sameOriginGroup?.text),
179 isUnattended: settledHandoff.isUnattended,
180 origin,
181 author: 'plugin',
182 ...(boxCopy === undefined ? {} : { boxText: boxCopy }),
183 }
184 return sendOrKeepInBox($, state, note, { notice: unsentNoteNotice(note, sameOriginGroup !== undefined) })
185}
186
187async function sendHeldGroups(
188 $: EngineInterface,
189 state: SessionState,
190 groups: readonly HeldPromptGroup[],
191 handoffIsUnattended: boolean,
192 { placement, holdBackPersonGroups }: { placement: BoxPlacement; holdBackPersonGroups: boolean },
193): Promise<Carried[]> {
194 const deliveries: Carried[] = []
195 for (const group of groups) {
196 deliveries.push(await sendOrKeepInBox($, state, group, { placement, holdBack: holdBackPersonGroups && speaksForPerson(group) }))
197 releaseCarriedGroup(state, group, handoffIsUnattended)
198 }
199 return deliveries
200}
201
202function sendLateArrivals($: EngineInterface, state: SessionState, holdBackPersonPrompts: boolean): Promise<LateArrivals> {
203 return forEachLateArrival(state, async prompt => {
204 // Counted as seen like the held groups are before they go in, so a ticket named in a late prompt is not new work later.
205 await inspectPrompt($, state, prompt.text)
206 return sendOrKeepInBox($, state, prompt, { placement: 'after_draft', holdBack: holdBackPersonPrompts && speaksForPerson(prompt) })
207 })
208}
209
210async function readSessionId($: EngineInterface): Promise<string | undefined> {
211 try {
212 return await $.session.id()
213 } catch (error) {
214 debug($, `could not read the session id: ${String(error)}`)
215 return undefined
216 }
217}
218
219// The same mode decideContinue reads, so the id is read exactly when a continue can follow.
220function isContinuing(state: SessionState, settledHandoff: SettledHandoff): boolean {
221 return state.continueAfterHandoff && settledHandoff.trigger.effectiveMode !== 'off'
222}
223
224// The fresh session's id, read straight after the clear; only when a continue is possible, so no other path reads it.
225function readFreshSessionId($: EngineInterface, state: SessionState, settledHandoff: SettledHandoff): Promise<string | undefined> {
226 return isContinuing(state, settledHandoff) ? readSessionId($) : Promise.resolve(undefined)
227}
228
229// The submit runs in a clock tick, since the engine refuses one from a hook the turn may be waiting on.
230// SAFETY: readSessionId and submitEntered catch their own failures, so run never rejects and no test reaches the reject.
231// Keep it: a run that did reject would otherwise leave the handoff waiting forever with its claim held.
232function afterTick<T>($: EngineInterface, run: () => Promise<T>): Promise<T> {
233 return new Promise((resolve, reject) => {
234 $.clock.after(0, () => {
235 run().then(resolve, reject)
236 })
237 })
238}
239
240type ContinueContext = { freshSessionId: string | undefined; noteDelivery: NoteDelivery; hasHeldPromptStartedTurn: boolean }
241
242async function submitContinuePrompt(
243 $: EngineInterface,
244 state: SessionState,
245 settledHandoff: SettledHandoff,
246 { freshSessionId, noteDelivery, hasHeldPromptStartedTurn }: ContinueContext,
247): Promise<ContinueFields> {
248 const decide = (isSameSession: boolean, hasTurnStarted: boolean) =>
249 decideContinue({
250 isEnabled: state.continueAfterHandoff,
251 effectiveMode: settledHandoff.trigger.effectiveMode,
252 signal: settledHandoff.trigger.signal,
253 noteDelivery,
254 hasHeldPromptStartedTurn: hasTurnStarted,
255 isSameSession,
256 })
257 const beforeTick = decide(true, hasHeldPromptStartedTurn)
258 if (!beforeTick.submit) return beforeTick.fields
259 // The session and turn checks run inside the tick, straight before the submit: the hold on prompts has ended, so a
260 // /resume, /clear, or prompt the person sends before the tick is seen here rather than overtaken by the submit.
261 return afterTick($, async () => {
262 const isSameSession = freshSessionId !== undefined && (await readSessionId($)) === freshSessionId
263 const decision = decide(isSameSession, hasHeldPromptStartedTurn || state.isTurnRunning)
264 if (!decision.submit) return decision.fields
265 const { isUnattended } = settledHandoff
266 const prompt: HeldPrompt = { text: CONTINUE_PROMPT, isUnattended, origin: noteOrigin(isUnattended), author: 'plugin' }
267 const isSubmitted = await submitEntered($, state, prompt, 'could not submit the continue prompt', false)
268 return isSubmitted ? { continued: 'submitted' } : { continued: 'skipped', continue_skip: 'submit_failed' }
269 })
270}
271
272export async function continueInFreshSession(
273 $: EngineInterface,
274 state: SessionState,
275 settledHandoff: SettledHandoff,
276 oldId: string,
277 note: string,
278 hasTurnAfterNote: boolean,
279 clearedBy: ClearedBy,
280): Promise<void> {
281 // Before the first await, so no prompt passes unheld after settleHandoff took the held ones: from here a prompt that
282 // arrives is held until the note, the held prompts, and every prompt that arrived meanwhile have been delivered.
283 beginSending(state)
284 const freshSessionId = await readFreshSessionId($, state, settledHandoff)
285 await registerHandoffCommand($)
286 // Read once the clear has run: a turn the clear let in ahead of itself started in the old session after the last check.
287 const hasLateTurn = state.hasLateTurn
288 const noteDelivery = await deliverNote($, state, settledHandoff, handoffMessage(oldId, note, hasTurnAfterNote || hasLateTurn))
289 if (noteTookGroupAlong(settledHandoff.heldGroups, settledHandoff.isUnattended, noteDelivery)) releaseCarried(state)
290 announce($, FINAL_MESSAGES[noteDelivery](oldId))
291 for (const { text } of settledHandoff.heldGroups) await inspectPrompt($, state, text)
292 const groupsToSend = groupsLeftToSend(settledHandoff.heldGroups, settledHandoff.isUnattended, noteDelivery)
293 const { holdBackPerson, placement } = deliveryAfterNote(noteDelivery)
294 const deliveries = await sendHeldGroups($, state, groupsToSend, settledHandoff.isUnattended, { placement, holdBackPersonGroups: holdBackPerson })
295 const late = await sendLateArrivals($, state, holdBackPerson)
296 const hasHeldPromptStartedTurn = [...deliveries, ...late.deliveries].includes('submitted')
297 const continueFields = await submitContinuePrompt($, state, settledHandoff, { freshSessionId, noteDelivery, hasHeldPromptStartedTurn })
298 await writeRecord($, state, {
299 ...settledHandoff.trigger,
300 action: 'cleared',
301 sessionId: oldId,
302 note: noteDelivery,
303 clearedBy,
304 compactedBeforeClear: settledHandoff.hasCompactedBeforeClear,
305 lateTurn: hasLateTurn,
306 continueFields,
307 heldFields: {
308 ...heldGroupFields(groupHeldPrompts([...settledHandoff.heldGroups, ...late.prompts])),
309 handoff_unattended: settledHandoff.isUnattended,
310 held_other_delivery: worstDelivery([...deliveries, ...late.deliveries]),
311 ...leftoverStripFields(state.leftoverStrips),
312 },
313 })
314}
315hooks/background-busy.tsx 17 lines1import type { EngineInterface } from 'claude-code'
2
3import { debug } from './engine-log'
4import type { SessionState } from './session-state'
5
6const BUSY_AGENT_STATUSES = new Set(['pending', 'running', 'waiting'])
7
8export async function isBackgroundBusy($: EngineInterface, state: SessionState): Promise<boolean> {
9 if (state.backgroundTasks.size > 0) return true
10 try {
11 return (await $.agent.list()).some(agent => BUSY_AGENT_STATUSES.has(agent.status))
12 } catch (error) {
13 debug($, `could not list agents, treating background work as busy: ${String(error)}`)
14 return true
15 }
16}
17hooks/compaction.tsx 36 lines1import type { EngineInterface } from 'claude-code'
2
3import type { Trigger } from './decision-record'
4import { debug, logFailure } from './engine-log'
5import { writeRecord } from './record-writer'
6import { claimPending, type SessionState } from './session-state'
7
8async function runCompaction($: EngineInterface, state: SessionState, trigger: Trigger): Promise<void> {
9 const sizeBefore = state.contextTokens
10 try {
11 const compaction = await $.session.compact()
12 if (compaction.skip !== undefined) {
13 state.backoffFrom = sizeBefore
14 await writeRecord($, state, { ...trigger, action: 'none', reason: 'compaction_vetoed' })
15 } else {
16 await writeRecord($, state, { ...trigger, action: 'compacted' })
17 state.backoffFrom = compaction.tokensAfter ?? sizeBefore
18 state.contextTokens = compaction.tokensAfter ?? sizeBefore
19 }
20 } catch (error) {
21 state.backoffFrom = sizeBefore
22 debug($, `compaction failed: ${String(error)}`)
23 await writeRecord($, state, { ...trigger, action: 'none', reason: 'compaction_failed' })
24 } finally {
25 state.pending = null
26 }
27}
28
29export function scheduleCompaction($: EngineInterface, state: SessionState, trigger: Trigger): boolean {
30 if (!claimPending(state, 'compact')) return false
31 $.clock.after(0, () => {
32 void logFailure($, runCompaction($, state, trigger))
33 })
34 return true
35}
36hooks/handoff-run.tsx 185 lines1import type { EngineInterface } from 'claude-code'
2
3import type { BandState } from '../types'
4import { WRITING, WRITING_STATUS } from './band-text'
5import { redrawBand, takeDownBand } from './band-controller'
6import { CLEARED_BY, abandonAfterWait, type AbandonHandoff, waitForClearWindow } from './clear-window'
7import {
8 heldGroupFields,
9 leftoverStripFields,
10 type DecisionReason,
11 type HandoffRequest,
12 type SettledHandoff,
13} from './decision-record'
14import { announce } from './announcement'
15import { debug, logFailure } from './engine-log'
16import { noteOutcome, type ForkReason, type NoteOutcome } from './fork-outcome'
17import { continueInFreshSession, restoreHeldGroups, restoreLateArrivals } from './handoff-delivery'
18import { HANDOFF_PROMPT, NO_HANDOFF_MESSAGE, groupHeldPrompts, noHandoffMessage } from './handoff-note'
19import { worstDelivery } from './held-delivery'
20import { writeRecord } from './record-writer'
21import {
22 beginBeforeClear,
23 beginHandoffHold,
24 beginNoteWindow,
25 beginSending,
26 claimPending,
27 endHandoff,
28 takeHeldPrompts,
29 type SessionState,
30} from './session-state'
31
32// A failed read leaves the id to writeRecord, which reads it again. If that fails too, no record is written and
33// writeRecord leaves its own debug line.
34async function readSessionId($: EngineInterface): Promise<string | undefined> {
35 try {
36 return await $.session.id()
37 } catch (error) {
38 debug($, `could not read the session id: ${String(error)}`)
39 return undefined
40 }
41}
42
43async function abandonHandoff(
44 $: EngineInterface,
45 state: SessionState,
46 settledHandoff: SettledHandoff,
47 reason: DecisionReason,
48 message: string,
49 sessionId?: string,
50 forkReason?: ForkReason,
51) {
52 // Before the first await, as in continueInFreshSession: the caller took the held prompts in the same synchronous run, so a
53 // prompt that arrives while they are restored is held until they, and every prompt that arrived meanwhile, are back.
54 beginSending(state)
55 await takeDownBand($, state)
56 announce($, message)
57 const recordedSessionId = sessionId ?? (await readSessionId($))
58 const restores = await restoreHeldGroups($, state, settledHandoff)
59 const late = await restoreLateArrivals($, state)
60 await writeRecord($, state, {
61 ...settledHandoff.trigger,
62 action: 'none',
63 reason,
64 forkReason,
65 compactedBeforeClear: settledHandoff.hasCompactedBeforeClear,
66 heldFields: {
67 ...heldGroupFields(groupHeldPrompts([...settledHandoff.heldGroups, ...late.prompts])),
68 handoff_unattended: settledHandoff.isUnattended,
69 held_restore: worstDelivery([...restores, ...late.deliveries]),
70 ...leftoverStripFields(state.leftoverStrips),
71 },
72 sessionId: recordedSessionId,
73 })
74}
75
76async function writeNote($: EngineInterface): Promise<NoteOutcome> {
77 try {
78 const answer = await $.model.fork({ prompt: HANDOFF_PROMPT })
79 // nothing-to-fork already reaches the record as fork_reason; every other non-answer is explained only here.
80 if (!answer.isAnswered && answer.reason !== 'nothing-to-fork') {
81 const detail = answer.reason === 'api-error' ? ` (status ${String(answer.status)}, ${answer.error})` : ''
82 debug($, `the fork wrote no handoff note: ${answer.reason}${detail}`)
83 }
84 return noteOutcome(answer)
85 } catch (error) {
86 debug($, `could not write the handoff note: ${String(error)}`)
87 return { note: null }
88 }
89}
90
91async function prepareHandoff($: EngineInterface, state: SessionState, request: HandoffRequest) {
92 let oldId: string | undefined
93 try {
94 await redrawBand($, state, WRITING)
95 $.ui.toast(WRITING_STATUS)
96 // SAFETY: a session end between scheduleHandoff and this read would make oldId the new session's id. That needs a
97 // /clear in the same clock.after(0) tick as /handoff, which a person typing cannot produce; SDK or bridge commands
98 // sent back to back could. No guard: the note would still be delivered, but the resume line and the cleared record's
99 // session_id would name the new session instead of the one the note came from.
100 oldId = await $.session.id()
101 beginNoteWindow(state)
102 const outcome = await writeNote($)
103 if (outcome.note === null) {
104 await abandonHandoff($, state, settleHandoff(state, request), 'no_handoff_written', noHandoffMessage(outcome.forkReason), oldId, outcome.forkReason)
105 return null
106 }
107 return { oldId, note: outcome.note }
108 } catch (error) {
109 debug($, `handoff failed before the clear: ${String(error)}`)
110 await abandonHandoff($, state, settleHandoff(state, request), 'handoff_failed', NO_HANDOFF_MESSAGE, oldId)
111 return null
112 }
113}
114
115async function runHandoff(
116 $: EngineInterface,
117 state: SessionState,
118 request: HandoffRequest,
119 beforeRun?: () => Promise<unknown>,
120) {
121 try {
122 // SAFETY: beforeRun is clearBoxCopyWhileHeld on the prompt path (it wraps emptyBoxIfHolding) and emptyBoxIfHolding
123 // on the command path. emptyBoxIfHolding catches its own failures, so no test can make it throw.
124 // It runs inside the try so a future beforeRun that throws still releases the claim.
125 await beforeRun?.()
126 const prepared = await prepareHandoff($, state, request)
127 if (prepared === null) return
128 const redraw = (band: BandState) => redrawBand($, state, band)
129 const abandon: AbandonHandoff = (settled, reason, message, sessionId) => abandonHandoff($, state, settled, reason, message, sessionId)
130 const { outcome, hasCompactedBeforeClear, hasTurnAfterNote, clearing } = await waitForClearWindow($, state, request, prepared.oldId, redraw)
131 const settleAfterWait = () => ({ ...settleHandoff(state, request), hasCompactedBeforeClear })
132 if (outcome === 'abandon_session_ended') return await abandonAfterWait(abandon, settleAfterWait(), 'session_ended', hasCompactedBeforeClear, prepared.oldId)
133 if (outcome === 'abandon_busy') return await abandonAfterWait(abandon, settleAfterWait(), 'busy', hasCompactedBeforeClear, prepared.oldId)
134 // The person already cleared: the fresh session they made takes the note, and no second clear runs.
135 let isCleared = true
136 if (clearing !== null) {
137 isCleared = await clearing
138 } else {
139 // No clear runs here, so this await is safe; the waiting status must not outlive the wait.
140 // SAFETY: a resume that lands during this await gets the note in the resumed session, as one landing during
141 // registerHandoffCommand already does. Each window is one engine round trip wide. No guard.
142 await takeDownBand($, state)
143 }
144 const settledHandoff = settleAfterWait()
145 if (!isCleared) {
146 return await abandonAfterWait(abandon, settledHandoff, 'clear_failed', hasCompactedBeforeClear, prepared.oldId)
147 }
148 const clearedBy = CLEARED_BY[outcome]
149 await continueInFreshSession($, state, settledHandoff, prepared.oldId, prepared.note, hasTurnAfterNote, clearedBy)
150 } finally {
151 endHandoff(state)
152 state.pending = null
153 }
154}
155
156export function scheduleHandoff(
157 $: EngineInterface,
158 state: SessionState,
159 request: HandoffRequest,
160 beforeRun?: () => Promise<unknown>,
161): boolean {
162 if (!claimPending(state, 'handoff')) return false
163 state.heldPrompt = null
164 beginBeforeClear(state)
165 beginHandoffHold(
166 state,
167 request.heldPrompt === undefined
168 ? null
169 : { text: request.heldPrompt, isUnattended: request.isUnattended, origin: request.heldPromptOrigin ?? 'composer', author: 'person' },
170 )
171 $.clock.after(0, () => {
172 void logFailure($, runHandoff($, state, request, beforeRun))
173 })
174 return true
175}
176
177// Taking the held prompts ends their holding: from here a prompt that arrives belongs to the fresh session or the old one.
178function settleHandoff(state: SessionState, request: HandoffRequest): SettledHandoff {
179 return {
180 trigger: request.trigger,
181 isUnattended: request.isUnattended,
182 heldGroups: groupHeldPrompts(takeHeldPrompts(state)),
183 }
184}
185hooks/prompt-inspection.tsx 27 lines1import type { EngineInterface } from 'claude-code'
2
3import { debug } from './engine-log'
4import type { SessionState } from './session-state'
5import { branchTicketPrefixes, hasTicketShapedToken, namesNewWork, ticketUrlPrefixes, workRefs } from './work-refs'
6
7const BRANCH_READ_TIMEOUT_MS = 5000
8
9async function readBranch($: EngineInterface): Promise<string> {
10 try {
11 const ran = await $.process.run(['git', 'branch', '--show-current'], { timeoutMs: BRANCH_READ_TIMEOUT_MS })
12 return ran.exitCode === 0 ? ran.stdout.trim() : ''
13 } catch (error) {
14 debug($, `could not read the git branch: ${String(error)}`)
15 return ''
16 }
17}
18
19export async function inspectPrompt($: EngineInterface, state: SessionState, text: string): Promise<boolean> {
20 for (const prefix of ticketUrlPrefixes(text)) state.urlPrefixes.add(prefix)
21 const branchPrefixes = hasTicketShapedToken(text) ? branchTicketPrefixes(await readBranch($)) : []
22 const prefixes = [...state.urlPrefixes, ...branchPrefixes]
23 const isNewWork = namesNewWork(text, state.seenRefs, prefixes)
24 for (const ref of workRefs(text, prefixes)) state.seenRefs.add(ref)
25 return isNewWork
26}
27