SLOPSHOPPER

sweet-spot

Hands a long session over, to a fresh one or by compacting, before the context gets too big

bandguardcommandpromptmodelprocess
★ 1v0.3.2MITupdated 2026-10-23muellerei/sweet-spot
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · sweet-spot
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /sweet-spot ⎿ sweet-spot: use `/sweet-spot status` to see where the context stands, `/sweet-spot later [tokens]` to move the next handov ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

<img src="docs/images/banner-light.svg" width="900" alt="sweet-spot: hands a long Claude Code session over, to a fresh one or by compacting">

<b>One job: keep your context in the sweet spot.</b><br> Not so long that answers get less reliable and every call re-reads a mountain.

<a href="https://github.com/muellerei/sweet-spot/actions/workflows/check.yml"><img src="https://github.com/muellerei/sweet-spot/actions/workflows/check.yml/badge.svg" alt="CI"></a> <a href="LICENSE"><img src="https://img.shields.io/github/license/muellerei/sweet-spot" alt="MIT license"></a>

<a href="#install">Install</a> · <a href="#why">Why</a> · <a href="#what-it-does">What it does</a> · <a href="#handoff-or-compact">Handoff or compact</a> · <a href="#what-it-can-reach">What it can reach</a> · <a href="#settings">Settings</a> · <a href="#limits">Limits</a> · <a href="CHANGELOG.md">Changelog</a> · <a href="CONTRIBUTING.md">Contributing</a>

sweet-spot never acts in the middle of a turn. It waits for a pause, counts down with a "Not now", and postpones while a subagent or a background task that will end is running. Only then does it hand a long Claude Code session over before the context gets too big: to a fresh session that starts from a handoff, or by Claude Code's own /compact. "Handover" is the word for all of these. It is a Claude Code mod (a plugin of function hooks).

The context bar fills past the threshold, the mod waits for a subagent, hands the session over and continues in a fresh session

Drawn, not recorded: an illustration of the sequence, looping.

Built to be safe

  • Only at a pause. An answer that ended in an error, a refusal or Esc is no pause, and neither is the end of a subagent.
  • Counts down first. A line above the prompt counts down 10 seconds, with "Not now" to move the handover back.
  • Waits for running work. A subagent, a background task or a timer holds it back, until the emergency brake: 150k past the threshold, never beyond 90 percent of the window. A dev server, a watcher or tail -f does not, since it never ends; the fresh session is told it still runs.
  • Typing is not lost. What you type during a handover is held and goes in when it is done.
  • Writes nothing. No files, no network, and one process only: tail, to read the end of a long transcript.

Install

Developed against Claude Code 2.1.296; older versions are not tested, and versions before 2.1.271 cannot load the mod at all (see Settings). Run inside Claude Code:

/plugin marketplace add muellerei/sweet-spot
/plugin install sweet-spot@muellerei-sweet-spot
/reload-plugins

That is all the setup there is. Work until the context passes 200k tokens, and at the end of an answer a line above the prompt counts down:

Handing over to a fresh session in 10 s · context 205000 of 200000 · 1: Not now, +25000

Press 1 to move the handover back, or start typing to keep working. Otherwise, when it runs out, you see:

handing over now, context 205000 tokens
handed over, the fresh session carries on from the handoff

By default the mod writes the handoff itself with a built-in prompt, clears the session and starts the fresh one with it; if that fails, it compacts the session instead. ~/.claude/sweet-spot/handoff-prompt.md replaces that prompt. handoff_method and handoff_fallback choose the ways: Claude Code's own /compact, the mod's handoff, or a handoff command of your own. To watch first, turn dry_run on in /config: then it only says when it would hand over. See Settings.

Ideas, questions and a quick "works on my setup" are all welcome: CONTRIBUTING.md.

Why

The sweet spot is the range where the context is big enough to hold the work and still small enough to be cheap and reliable.

The sweet spot on a scale of context size, the threshold, and where a fresh session starts

  • Cost. Every call re-reads the whole context. Measured over real sessions, most of the cost came from calls on more than 200k tokens.
  • Reliability. "As token count grows, accuracy and recall degrade" (Anthropic). An independent test of 18 models found the same (Chroma).

A fresh session starts at 62k to 98k tokens in real handovers. Nobody publishes where the line lies, and the picture is a sketch. The default of 200000 comes from the cost measurement. The mod does not claim that a fresh session answers better, only that a long one costs more.

What it does

At the end of an answer it looks at the context size. Past the threshold, and when nothing else is going on, it counts down and then hands over. By default that means it asks for a handoff, clears the session and submits the text of the handoff file, not its path, as the first message of the new one. The old session stays as it was: /resume takes you back to it. With /compact as the way, the session stays and only gets smaller; nothing is cleared or submitted.

  • Only at a pause. It acts when an answer is finished, never in the middle of a turn and never from a subagent. A turn that ended with an error, a refusal or Esc is no pause.
  • A countdown before it acts. A line above the prompt says what is coming and counts down countdown_seconds (10 by default). "Not now" (key 1 in an empty prompt) moves the handover back, as /sweet-spot later with no number does. Typing or sending a message stops the countdown without moving anything; the next pause counts down again. A draft in the prompt holds the countdown back until the next pause. After two pauses that did not hand over, the countdown comes without "Not now", typing no longer stops it, and your draft stays in the prompt. When the countdown runs out the mod looks again and hands over only if it still should.
  • Not now, if you say so. In the middle of something? /sweet-spot later 50k moves this one handover back: the mod hands over once the context has grown 50k tokens past where it is now. The next handover uses your threshold again. It never goes past the emergency brake and never brings a handover forward. With no number it takes later_tokens.
  • At the next pause, if you say so. /sweet-spot asap hands over at the next pause, wherever the context stands: it lifts the threshold and the minimum gap and has no countdown, because you asked for it. Typed while no answer runs, it hands over at once, a moment after it answers. It still waits for running work, as any handover does, but not for a dev server or a watcher, and it is spent by the handover it starts. A compact or /clear of your own, the end of the session and a context that has shrunk below where you asked end it; later after it takes it back.
  • Ask where it stands. /sweet-spot status shows the context against the window, where the next handover comes (with a later that holds) and the emergency brake. It only reads, and a countdown goes on while you ask.
  • It waits for running work. While a subagent, a background task or a one-shot timer is running, it postpones, because a handoff written now could not hold that work's result, and the result would come into a fresh session that does not know what it was for. It says so once ("handoff postponed, a subagent is running, context 201293 tokens"); it does not repeat the line at every stop. It acts at the first pause after the last one has finished (measured: the answer after the last subagent ended handed over). Past an emergency brake (150k above the threshold, never beyond 90 percent of the window) it goes ahead anyway and says so, with no countdown; if you moved the handover back, a countdown without "Not now" announces it once. A background command that never ends by itself is no work to wait for: npm run dev, vite, next dev, vitest --watch, tsc -w, docker compose up, tail -f, ngrok http and the like. The mod hands over past it, the countdown says · npm run dev keeps running, and the first message of the fresh session lists each such task with its command, so the fresh session knows the server is still there. At the emergency brake the same message lists the work it went past, whose results arrive in the fresh session.
  • You choose the way. handoff_method is the main way, handoff_fallback the one tried when the main way fails before it changed the session, and the change is said with its reason. The ways: the mod writes the handoff itself with a built-in prompt (internal-handoff, the default); Claude Code's own /compact (builtin-compact, the default fallback); or your own command, run as a turn of its own, whose file the mod reads (external-command, needs handoff_command). If Claude Code refuses the compact (it does in a headless -p or SDK session) or a hook vetoes it, the fallback takes over; if you press Esc during it, nothing else hands over.
  • A compact that is not enough is not repeated. If the context is still above the threshold right after a compact (at the first tool call of the next turn, or its pause), the next time the fallback takes over; with no fallback, the mod says so once and leaves the session alone until a pause is below the threshold again.
  • Typing is held, not lost. What you type while a handover runs is held and goes in when it is done: into the fresh session with the handoff, or into the compacted session. If submitting the message fails, /sweet-spot redeliver is the way out: it submits it again.
  • After a long pause, a fresh session. When you leave a session alone for more than an hour, the prompt cache expires, and your next message would send the whole conversation again at the price of writing the cache. With an hour of cache and a context well past what a fresh session starts with, the mod writes a handoff at minute 55, while the cache is still warm, and leaves the session as it is. Come back while the cache is warm and nothing changes; come back after it has expired, and your message starts a fresh session with the handoff, and a line says how long the session sat idle and that the old one is in /resume. The band above the prompt says so once the cache has expired, and /sweet-spot later keeps you in the session. Running work or an attachment keeps your message in the session too. Claude Code 2.1.299 and later can compact a large idle session itself instead; how the two differ and how to choose: docs/idle-handoff.md. The details, the costs and the limits: docs/idle-handoff.md.
  • Report only, if you want. With dry_run on it only says "would hand over now" and does nothing.
  • Bad settings are refused, not repaired. A threshold so low that every fresh session would trigger the next handover is rejected with the reason, and the mod stays off.

What happens to what you type while a handoff runs, and what redeliver is for:

What you type during a handover is held and goes into the fresh session; if the submit fails, redeliver puts it in

Drawn, not recorded: an illustration of the sequence, looping.

And the questions the mod asks at every pause, in this order. The first one that says stop ends the check:

The five questions at every pause: a normal end of the answer, the threshold, running work, the minimum gap, dry run

Drawn, not recorded: an illustration of the sequence, looping.

Handoff or compact

Both ways bring the context down. They differ in what the session holds afterwards.

Past the threshold the session goes one of two ways: a handoff clears it and starts a fresh session that holds only the handoff; a compact keeps the same session with Claude Code's summary in place of the history

Handoff (default)Compact
AfterwardsA fresh session that holds only the handoffThe same session, with Claude Code's summary in place of the history
What it keepsWhat the handoff prompt asks for; ~/.claude/sweet-spot/handoff-prompt.md replaces itWhat Claude Code's /compact keeps; the mod has no say in it
Can you read itYes, it is the first message of the fresh sessionNo file; the summary goes straight into the session
Time, measuredFrom the end of the answer to the fresh session's first message: 20 to 34 s with your own command at 202k to 224k tokens. With the built-in prompt 15 to 21 s, measured when it stood in for a missing commandThe compact itself: about 15 s at 65k tokens, 56.5 s at 408k; it grows with the context
Context after, measuredAt the start of the fresh session: 62k to 98k tokens with your own command, 31k once with the built-in prompt130k at the first pause after a compact at 408k; that pause already holds the next turn

handoff_method picks the way and handoff_fallback the one tried when it fails. A handoff command of your own (external-command) goes the handoff way: its file starts the fresh session. See Settings.

What it can reach

  • Reads: the transcript of the session, to learn how long its prompt cache lives (the whole file up to 4 MiB, above that its last 256 KiB, or, when the idle handoff comes due, everything written since the pause began if that is more), your handoff file, ~/.claude/sweet-spot/handoff-prompt.md if you made one, a listing of the folder of the file the answer names, and the environment variable HOME, to find your prompt file.
  • Writes: nothing. The message waiting to be delivered, and the baseline of each project folder for the idle handoff, live in the mod's store in Claude Code, which /clear does not touch.
  • Network: none. The model call that writes the handoff runs through Claude Code, and so does the compact.
  • Own processes: one. A transcript above 4 MiB is read at its end with tail -c 262144 <transcript>, or from where the pause began with tail -c +<offset> <transcript>, with no shell; Claude Code's file read stops at 4 MiB. Without tail (Windows without the Git tools on the path) the idle handoff stays off for that session and a warn line says so.

To check this against the code yourself:

claude plugin validate .

It lists every call the hooks make and every environment variable they read.

How it differs

There are several context mods. They fall into a few approaches, and this table compares features, not projects. It reflects the code of the context mods read in October 2026 and is meant as a map, not a ranking. Only features this version has are listed; corrections are welcome.

Compacts in placeHands over (typical)sweet-spot
New session instead of a summary in the same onenoyesyes, or a compact if you choose
Acts only when an answer is finishedmostlymostlyyes
Waits for subagents and background worksomesomeyes, not for a dev server, watcher or tail -f
Report-only mode before it actsone, as its defaultonly a manual dry runyes, a setting
Falls back to a second way if the first failsrarerareyes
Writes into your projectrarelyoften, or by asking Claude tonever

What it does not do

No memory, no rules, no panel or status line; the line above the prompt shows only while a countdown runs, or once an idle handoff waits for a cache that has expired. It has no summarizer of its own: when it compacts, it starts Claude Code's own /compact. Those belong in other tools. The first version also has no cache keep-warm and no log file; the CHANGELOG lists them under "Not in this version".

Settings

In the /config menu under sweet-spot.

SettingDefaultWhat it does
threshold200000Context size in tokens at which it hands over. Values below 130000 are refused. On a small window it is lowered to 80 percent of the window.
dry_runoffOnly say that a handoff would happen, and do nothing. Turn on to watch what the mod would do before it acts.
min_gap_minutes10Least time between two attempts. 0 turns the whole gap off.
min_gap_turns5Least number of turns between two attempts. 0 turns the whole gap off.
later_tokens25000How far /sweet-spot later moves the next handover back when you give it no number, in tokens.
countdown_seconds10Seconds the line above the prompt counts down before a handover, with "Not now". A whole number from 0 to 60; 0 hands over at once. Without a terminal or desktop window to show it (VS Code, mobile), it hands over at once too.
handoff_methodinternal-handoffHow the session is handed over. internal-handoff: the mod writes a handoff and starts a fresh session with it. builtin-compact: Claude Code's own /compact, the session stays. external-command: your own command.
handoff_fallbackbuiltin-compactUsed when the main method fails before it changed the session: any of the three, or none for no second try (the mod says why). The same value as handoff_method means no fallback.
idle_handoffonAfter a long pause, write a handoff shortly before the prompt cache expires, and start a fresh session with it when you come back after it has. Only with an hour of cache. See docs/idle-handoff.md.
idle_handoff_min_tokens0Context size from which the idle handoff is written. 0: the session's baseline, what a fresh session sends with its first message, plus 30000.
handoff_commandemptyOnly used with external-command (advanced). Name of your own handoff command, without the slash. external-command with no command here switches the mod off and says why.

The two ways are choices in /config, so they cannot be mistyped; an unknown value is refused. Does not load before Claude Code 2.1.271: the host rejects a mod with fixed choices in an older version ("If you declare options on any field, users on Claude Code versions before v2.1.271 can't load the plugin", Claude Code plugin reference, section "Limit a field to fixed options"). Examples:

  • Compact only: handoff_method builtin-compact, handoff_fallback none.
  • Compact when it works, otherwise a handoff: builtin-compact and internal-handoff.
  • Only your own command: external-command and none, with handoff_command set.

The gap ends after the minutes or the turns, whichever comes first. Both are starting points; raise them if attempts come too close together.

A change in /config takes effect at once: the host reloads the mod, which starts from a clean state, so the minimum gap, the redeliver pointer, a later, an asap and an idle handoff written are forgotten. A reload while a handoff is running (the seconds after the mod decides to hand over, see Handoff or compact) ends that handoff without a message, so leave the settings alone during that time.

Commands

The mod has one command, /sweet-spot, and the word after it says what it does. It runs at once, also while an answer is still running.

CommandWhat it does
/sweet-spot statusSays where the context stands: the tokens against the window, where the next handover comes (with a later that holds) and the emergency brake, then a standing asap and where the idle handoff stands. It only reads; a countdown keeps running.
/sweet-spot asapHands over at the next pause, below the threshold and inside the minimum gap too, with no countdown. It still waits for running work, not for a dev server. It says the context, or why it did not take the request. With an idle handoff written and the cache expired, it hands that one over.
/sweet-spot later [tokens]Moves the next handover back until the context has grown that many tokens past where it is now (50000 or 50k; with no number, later_tokens). It says the value it hands over at, or why not. With the idle handoff written after a long pause, it drops that too, so your next message stays in this session.
/sweet-spot redeliverSubmits again the first message of a handoff that did not reach the fresh session.

Limits

  • Where an organisation manages Claude Code, the mod does next to nothing. There Claude Code passes over a plugin you installed yourself for some of the events the mod relies on, among them the one that says an answer has ended and the one that says the session was compacted; only a plugin the organisation lists in its managed settings gets them. Without them the mod never judges a pause: no handover at the threshold and no idle handoff. If that is your setup, ask whoever manages Claude Code to list sweet-spot there. This comes from claude plugin validate; I have no managed installation to try it on.
  • The idle handoff gives way to Claude Code's own idle compaction. From 200,000 tokens Claude Code may compact an idle session itself at minute 54, a minute before the mod would write the handoff; the session then carries on compacted, and no handoff is written. To keep the idle handoff for large sessions, set idleCompaction to false in your settings.json. How the two differ: docs/idle-handoff.md.
  • It waits only for what the host reports as a subagent, a background task or a one-shot timer. Work the host does not repor
Source 18 files
hooks/register.tsx 1406 lines
1import type { EngineInterface as Engine, Register } from 'claude-code'
2
3import { configOf, type Config, type ConfigResult } from './config'
4import { ASAP_OVER, RUNNING_UNKNOWN, asapFor } from './asap'
5import {
6  brakeFor,
7  brakeOf,
8  busyReason,
9  decide,
10  effectiveThreshold,
11  laterAt,
12  oneShots,
13  shrunk,
14  standingOf,
15  thresholdInForce,
16  waiting,
17  type Decision,
18  type Snapshot,
19} from './decide'
20import { claim, hold, HELD_MOMENT } from './hold'
21import { LATER_OVER, laterFor, tokensOf } from './later'
22import { idlePart, statusFor, statusTail } from './status'
23import { checkOf, firstMethod, judgedLine } from './compact-check'
24import { bandOf, kindAt, moveBack, NOT_NOW_KEY, typed, type Countdown, type Start } from './countdown'
25import { standingPart } from './standing'
26import { begin, end, endedLine, press, surveyed, type Answer, type CountdownIo, type EndReason, type Expiry } from './countdown-flow'
27import { logger, refresh, shows } from './log'
28import {
29  carryOut,
30  deliverReturn,
31  endOfTurn,
32  noteToolResult,
33  prepare,
34  redeliver,
35  release,
36  startOfTurn,
37  throughMethods,
38  why,
39  type Failure,
40  type Io,
41  type Outcome,
42} from './relay'
43import {
44  ANSWER_RUNNING,
45  COMPACTED,
46  HANDED_OVER,
47  HANDOFF_UNDER_WAY,
48  NOTHING_TO_REDELIVER,
49  REDELIVER_UNDER_WAY,
50  REDELIVERING,
51  REDELIVERED,
52  usageFor,
53  CANCELLED,
54  notPreparedLine,
55  switchedLine,
56  COLD_BAND,
57  IDLE_DROPPED,
58  ATTACHMENTS_STAY,
59  DRY_RUN_RETURN,
60  WORK_STAYS,
61  CONTEXT_UNKNOWN,
62  contextUnreadLine,
63  decidedOf,
64  failedLine,
65  offLine,
66  reportOf,
67  unreadLine,
68  unregisteredLine,
69} from './report'
70import { endSeen, judgeable, stopSeen, turnStarted, type Stop } from './pairing'
71import { freshIdle, freshState, underWay, type IdlePrepared, type Pause, type State } from './state'
72import {
73  HOUR_MS,
74  baselineOf,
75  compactedSince,
76  fireVerdict,
77  firstBaselineOf,
78  floorOf,
79  hasAnswer,
80  idleFor,
81  isHit,
82  lifetimeOf,
83  planVerdict,
84  prepareDueAt,
85  readPlan,
86  returnVerdict,
87  TAIL_BYTES,
88  type InputUsage,
89} from './idle-handoff'
90
91// The host follows `$` only into functions declared at the top of this file, so what takes `$` lives here and not inside `register`.
92
93const say = ($: Engine, text: string) => {
94  $.ui.toast(text)
95  $.ui.log(text)
96}
97
98// One line of the diagnostic output, for finding out why a handoff did or did not happen. It goes to the transcript, where the host stamps
99// the time. The level is looked up at each line, so a line from a timer goes by the latest read.
100const toLog = ($: Engine) => (text: string) => $.ui.log(text)
101
102const logTo = ($: Engine, state: State) => logger(() => state.logLevel, toLog($))
103
104// An empty name is no command of the user's own: shown as `none`, not as an empty quote.
105const commandShown = (name: string) => (name === '' ? 'none' : `"${name}"`)
106
107// The command's name is of interest only where a way uses it.
108const usesCommand = (c: Config) => c.handoffMethod === 'external-command' || c.handoffFallback === 'external-command'
109
110// The log level, read afresh at the start of every handler (see `refresh`). The host wants the variable's name as a literal at the call.
111// Each change to a level that shows `info` is marked with the settings in force, so that a log turned on halfway through a session says
112// them too, and shows from where on its finer lines start. Settings the mod rejects have their own line, said where the person looks.
113const readLevel = async ($: Engine, settings: ConfigResult, state: State) => {
114  const before = await refresh(() => $.env.get('SWEET_SPOT_LOG_LEVEL'), toLog($), state)
115  if (!settings.ok || state.logLevel === before || !shows(state.logLevel, 'info')) return
116  const c = settings.config
117  logTo($, state)(
118    'info',
119    `settings: threshold ${c.threshold}, dry_run ${c.dryRun ? 'on' : 'off'}, min gap ${c.minGapMinutes} minutes and ${c.minGapTurns} turns, later_tokens ${c.laterTokens}, countdown_seconds ${c.countdownSeconds}, idle_handoff ${c.idleHandoff ? 'on' : 'off'}, idle_handoff_min_tokens ${c.idleHandoffMinTokens}, method ${c.handoffMethod}, fallback ${c.handoffFallback}${usesCommand(c) ? `, handoff command ${commandShown(c.handoffCommand)}` : ''}, log level ${state.logLevel}`,
120  )
121}
122
123const announce = ($: Engine, settings: ConfigResult, state: State) => {
124  if (settings.ok) return
125  say($, offLine(settings.errors))
126  const n = settings.errors.length
127  logTo($, state)('warn', `settings rejected, ${n} ${n === 1 ? 'error' : 'errors'}`)
128}
129
130const sessionIo = ($: Engine, state: State): Io => ({
131  commands: async () => (await $.command.list()).map(c => c.name),
132  now: () => $.clock.now(),
133  run: (command, args) => $.command.run(args === undefined ? { command } : { command, args }),
134  after: (ms, fn) => $.clock.after(ms, fn),
135  readFile: path => $.fs.read(path),
136  listDir: path => $.fs.list(path),
137  home: () => $.env.get('HOME'),
138  modelFork: async prompt => {
139    const r = await $.model.fork({ prompt })
140    return r.isAnswered
141      ? { isAnswered: true, text: r.text, usage: r.usage }
142      : { isAnswered: false, reason: r.reason, ...('status' in r ? { status: r.status } : {}) }
143  },
144  compact: async () => {
145    const r = await $.session.compact()
146    return r.skip === undefined ? {} : { skip: r.skip }
147  },
148  tell: text => say($, text),
149  log: logTo($, state),
150  submit: text => $.prompt.submit({ text }),
151  sessionId: () => $.session.id(),
152  keep: (key, value) => $.store.set(key, value),
153  recall: key => $.store.get(key),
154  forget: key => $.store.delete(key),
155})
156
157const countdownIo = ($: Engine, state: State): CountdownIo => ({
158  now: () => $.clock.now(),
159  after: (ms, fn) => $.clock.after(ms, fn),
160  every: (ms, fn) => $.clock.every(ms, fn),
161  surfaces: () => $.session.surfaces(),
162  prompt: async () => (await $.prompt.read()).text,
163  redraw: () => $.ui.invalidate('ui.render'),
164  toast: text => $.ui.toast(text),
165  log: logTo($, state),
166})
167
168// The message about invalid settings and the command, once per load: at the session start, or at the first turn of a session that was already running.
169const introduce = async ($: Engine, settings: ConfigResult, state: State) => {
170  if (state.introduced) return
171  state.introduced = true
172  announce($, settings, state)
173  await registerCommand($, state)
174}
175
176const NOT_NOW_BUTTON = 'not-now'
177
178// The one command of the mod; what it does is the word after it.
179const COMMAND = 'sweet-spot'
180
181const registerCommand = async ($: Engine, state: State) => {
182  try {
183    // Immediate: a command typed while an answer runs would otherwise wait until the pause that ends the answer has been judged
184    // (docs/host-behaviour.md, Commands).
185    await $.command.register({
186      name: COMMAND,
187      description:
188        'Show where the context stands, move the next handover back or drop the idle handoff, hand over at the next pause, or submit again the handoff that did not reach the fresh session',
189      argumentHint: 'status | later [tokens] | asap | redeliver',
190      immediate: true,
191    })
192  } catch (err) {
193    say($, unregisteredLine(why(err)))
194    logTo($, state)('warn', 'could not register the command')
195  }
196}
197
198// Says how a run ended. Whatever goes wrong ends here as a line, never as an error into the host. The log names the stage, not the
199// reason: that can carry paths, the host's words and what was typed.
200const settle = async (
201  $: Engine,
202  state: State,
203  run: { name: 'handover' | 'redelivery'; done: (outcome: Outcome) => string; sayFailure?: (failure: Failure) => boolean },
204  carry: () => Promise<Outcome>,
205) => {
206  const log = logTo($, state)
207  try {
208    const outcome = await carry()
209    const failure = outcome.failure
210    if (failure === undefined) say($, run.done(outcome))
211    else if (failure.stage === 'cancelled') {
212      say($, CANCELLED)
213      log('info', `${run.name} cancelled`)
214    } else {
215      if (run.sayFailure?.(failure) ?? true) say($, failedLine(failure.reason))
216      log('warn', `${run.name} failed (stage ${failure.stage})`)
217    }
218  } catch (err) {
219    say($, failedLine(why(err)))
220    log('warn', `${run.name} failed (unexpected error)`)
221  }
222}
223
224// The submit waits for the session to be idle, so it is not waited for in the command: the command answers at once.
225const runRedelivery = async ($: Engine, state: State) => {
226  try {
227    await settle($, state, { name: 'redelivery', done: () => REDELIVERED }, async () => ({ failure: await redeliver(sessionIo($, state), state) }))
228  } finally {
229    state.redelivering = false
230  }
231}
232
233// Without usable settings (`config` undefined) the mod never handed anything over, so there is nothing to redeliver.
234const redeliverText = ($: Engine, config: Config | undefined, args: string, state: State): string => {
235  if (args.trim() !== 'redeliver') return usageFor(args)
236  if (underWay(state)) return HANDOFF_UNDER_WAY
237  if (state.answerRunning) return ANSWER_RUNNING
238  if (state.redelivering) return REDELIVER_UNDER_WAY
239  if (state.pending === undefined || config === undefined) return NOTHING_TO_REDELIVER
240  state.redelivering = true
241  $.clock.after(0, () => void runRedelivery($, state))
242  return REDELIVERING
243}
244
245const turnedDown = (text: string, why: string, verb = 'later'): Answer => ({ text, lines: [['debug', `${verb}: turned down, ${why}`]] })
246
247// What a command that acts on the context needs before it does: settings it can trust, no handover under way (nor, for `asap`, a step of
248// its own still to come), and the context size, read at that moment. Otherwise the answer that turns it down. The command answers whatever
249// goes wrong with the read; the hook's `.catch` would only pass the error to the host.
250const contextFor = async (
251  $: Engine,
252  settings: ConfigResult,
253  state: State,
254  verb: 'later' | 'asap',
255): Promise<{ config: Config; tokens: number; window: number } | Answer> => {
256  if (!settings.ok) return turnedDown(offLine(settings.errors), 'the settings are rejected', verb)
257  const busy = () => underWay(state) || (verb === 'asap' && state.asapScheduled)
258  if (busy()) return turnedDown(HANDOFF_UNDER_WAY, 'a handover is in progress', verb)
259  let context: { tokens?: number; window: number }
260  try {
261    context = (await $.session.usage()).context
262  } catch (err) {
263    return { text: contextUnreadLine(why(err)), lines: [['warn', `${verb}: could not read the context size`]] }
264  }
265  // A pause may have started a handover during the read: a later handover or a mark set beside it would come too late for it and hold on in
266  // the fresh session.
267  if (underWay(state)) return turnedDown(HANDOFF_UNDER_WAY, 'a handover is in progress', verb)
268  if (context.tokens === undefined) return turnedDown(CONTEXT_UNKNOWN, 'the context size is unknown', verb)
269  return { config: settings.config, tokens: context.tokens, window: context.window }
270}
271
272// Moves the next handover back. It needs the context at the time it is typed, so its answer waits for that read.
273const laterText = async ($: Engine, settings: ConfigResult, rest: string, state: State): Promise<Answer> => {
274  const asked = tokensOf(rest)
275  if ('error' in asked) return turnedDown(asked.error, 'not a number of tokens')
276  // Staying in this session after a long pause: the handoff written goes, and the rest is `later` as ever.
277  if (state.idle.prepared !== undefined) {
278    const over = endPause($, state, 'later')
279    const answer = await laterText($, settings, rest, state)
280    const lines: Answer['lines'] = over === undefined ? [] : [['debug', over]]
281    return { text: IDLE_DROPPED + answer.text, lines: [...lines, ...(answer.lines ?? [])] }
282  }
283  const ready = await contextFor($, settings, state, 'later')
284  if ('text' in ready) return ready
285  const { config, tokens, window } = ready
286  const before = laterAt(state.later, tokens)
287  const result = laterFor(config, window, tokens, state.later, asked.tokens === 'setting' ? config.laterTokens : asked.tokens)
288  state.later = result.later
289  // The last word counts: `later` after `asap` takes the mark back, whether `later` itself was turned down or not.
290  const withdrawn = state.asap !== undefined
291  state.asap = undefined
292  // A step of `asap` still to come finds no mark and does nothing; a new `asap` before it must not be turned down for it.
293  state.asapScheduled = false
294  // Moving the handover back is the person's answer, not a pause that dodged it: the deferred pauses start over. A later turned down moves
295  // nothing and leaves them.
296  if (result.later !== before) state.deferred = undefined
297  const lines: Answer['lines'] = result.lines.map(line => ['debug', line])
298  if (withdrawn) lines.unshift(['debug', 'asap: withdrawn by later'])
299  return { text: withdrawn ? `asap withdrawn, ${result.text}` : result.text, lines }
300}
301
302const verbOf = (args: string) => args.trim().split(/\s/, 1)[0]
303
304// Reads the context and says where it stands; nothing in the state changes. It answers during a handover too, and says so.
305const statusText = async ($: Engine, settings: ConfigResult, state: State): Promise<Answer> => {
306  if (!settings.ok) return { text: offLine(settings.errors) }
307  let context: { tokens?: number; window: number }
308  try {
309    context = (await $.session.usage()).context
310  } catch (err) {
311    return { text: contextUnreadLine(why(err)), lines: [['warn', 'status: could not read the context size']] }
312  }
313  const { tokens, window } = context
314  const text =
315    statusFor(settings.config, window, tokens, laterAt(state.later, tokens)) + statusTail(state.asap !== undefined, idlePart(state.idle, await $.clock.now()))
316  return {
317    text: state.handingOver ? `${text}, a handover is in progress` : text,
318    lines: [
319      [
320        'debug',
321        tokens === undefined ? `status: answered, context size unknown, window ${window} tokens` : `status: answered, context ${tokens} of ${window} tokens`,
322      ],
323    ],
324  }
325}
326
327// Hands over at the next pause, wherever the context stands. It needs the context at the time it is typed, so its answer waits for that read.
328const asapText = async ($: Engine, settings: ConfigResult, state: State): Promise<Answer> => {
329  const ready = await contextFor($, settings, state, 'asap')
330  if ('text' in ready) return ready
331  const { config, tokens, window } = ready
332  const result = asapFor(config, tokens)
333  state.asap = result.asap
334  // The last word counts: `asap` after `later` drops the later handover.
335  const dropped = state.later !== undefined
336  state.later = undefined
337  const lines: NonNullable<Answer['lines']> = result.lines.map(line => ['debug', line])
338  if (dropped) lines.unshift(['debug', 'later: dropped by asap'])
339  const prefix = dropped ? 'later dropped, ' : ''
340  // An answer that runs ends in a pause, and that pause judges. At rest no pause comes.
341  if (state.answerRunning) return { text: prefix + result.text, lines }
342  const rest = await asapAtRest($, config, state, tokens, window, result.text)
343  if (rest === undefined) return { text: prefix + result.text, lines }
344  return { text: prefix + rest, lines: [...lines, ['debug', 'asap: judged at rest']] }
345}
346
347// What the last stop said plus what runs now, as a pause would read them, for `asap` typed at rest.
348const restSnapshot = async ($: Engine, state: State, tokens: number, window: number): Promise<Snapshot | undefined> => {
349  const stop = state.lastStop
350  if (stop === undefined) return undefined
351  const [agents, turns, now] = await Promise.all([$.agent.list(), $.session.turns(), $.clock.now()])
352  // `later` is gone: `asapText` dropped it before this reads.
353  return { ...snapshotOf(stop, { tokens, window }, agents, turns, state), now, later: undefined }
354}
355
356// The step that starts the handover of `asap` at rest comes this long after the command's answer: the host refuses a compact, a /clear and a
357// user command inside the command itself (docs/host-behaviour.md, Commands).
358const ASAP_STEP_MS = 300
359
360// `asap` typed with no answer running: no stop and no pause will judge, so the command does. It judges as a pause does, and the handover that
361// follows begins in a step of its own. Not known what runs (no stop seen since the last turn started): the mark stays for the next pause.
362// The text it answers with, or `undefined` for the answer of the mark alone.
363const asapAtRest = async ($: Engine, config: Config, state: State, tokens: number, window: number, text: string): Promise<string | undefined> => {
364  let snapshot: Snapshot | undefined
365  try {
366    snapshot = await restSnapshot($, state, tokens, window)
367  } catch (err) {
368    // Not known what runs, as with no stop seen: the mark stays for the next pause, which reads it again.
369    logTo($, state)('warn', 'asap: could not read what runs')
370    return `${text}, ${RUNNING_UNKNOWN}`
371  }
372  // A turn or a handover may have started during the reads: the mark waits for its pause.
373  if (state.answerRunning || underWay(state)) return undefined
374  if (snapshot === undefined) return `${text}, ${RUNNING_UNKNOWN}`
375  const decision = decide(snapshot, config)
376  if (decision.kind === 'none') return undefined
377  if (decision.kind === 'defer') return reported(decision, config, state)
378  // The answer says it; a toast would say it twice.
379  if (decision.kind === 'dry-run') {
380    spendMarks($, state, snapshot.now, snapshot.turns)
381    return reported(decision, config, state)
382  }
383  state.asapScheduled = true
384  $.clock.after(ASAP_STEP_MS, () => void asapStep($, config, state))
385  return reported(decision, config, state)
386}
387
388// The step: it judges again with a fresh snapshot, and begins only if the judgment is still to hand over. Otherwise the mark stays and the
389// next pause judges.
390const asapStep = async ($: Engine, config: Config, state: State) => {
391  state.asapScheduled = false
392  try {
393    if (state.asap === undefined) return
394    const { tokens, window } = (await $.session.usage()).context
395    if (tokens === undefined) return
396    const snapshot = await restSnapshot($, state, tokens, window)
397    if (snapshot === undefined || state.asap === undefined || state.answerRunning || underWay(state)) return
398    const decision = decide(snapshot, config)
399    if (decision.kind === 'defer') sayOnce($, state, decision.reason, reported(decision, config, state))
400    else if (decision.kind === 'act' && handOverPrepared($, state, snapshot.now, snapshot.turns)) return
401    // The command's answer has said it is handing over; saying it again would double the line.
402    else if (decision.kind !== 'none') beginHandover($, decision, config, state, snapshot.now, snapshot.turns, false)
403  } catch (err) {
404    sayUnread($, state, err)
405  }
406}
407
408// The handoff written in a long pause, when `asap` is about to hand over: cold, it is the one handed over, since writing it anew on a cold
409// cache would read the whole context again; warm, it goes, and a fresh one carries everything up to now for little. True when it is handed over.
410const handOverPrepared = ($: Engine, state: State, now: number, turns: number): boolean => {
411  const prepared = state.idle.prepared
412  if (prepared?.kind !== 'real') return false
413  const log = logTo($, state)
414  if (now - (state.idle.touch ?? now) < HOUR_MS) {
415    const over = endPause($, state, 'asap with the cache warm')
416    if (over !== undefined) log('debug', over)
417    return false
418  }
419  // In one step with no wait, as a handover begins: the band and the timers go with the handoff.
420  const over = endPause($, state, 'asap takes the handoff written')
421  spendMarks($, state, now, turns)
422  state.handingOver = true
423  state.held = []
424  if (over !== undefined) log('debug', over)
425  log('info', 'idle: asap hands over the handoff written')
426  void returnInto($, state, prepared, undefined, () => HANDED_OVER)
427  return true
428}
429
430// A failed read is said once; the log carries the warning the first time only.
431const sayUnread = ($: Engine, state: State, err: unknown) => {
432  const line = unreadLine(why(err))
433  if (sayOnce($, state, line, line)) logTo($, state)('warn', 'could not check for a handoff')
434}
435
436// What the command does is the word after it. `later` takes an argument, so the rest is its argument; `status` and `redeliver` take none.
437const commandText = ($: Engine, settings: ConfigResult, args: string, state: State): Promise<Answer> | Answer => {
438  const words = args.trim()
439  const verb = verbOf(words)
440  if (verb === 'later') return laterText($, settings, words.slice(verb.length), state)
441  if (words === 'status') return statusText($, settings, state)
442  if (words === 'asap') return asapText($, settings, state)
443  return { text: redeliverText($, settings.ok ? settings.config : undefined, args, state) }
444}
445
446// Runs the handoff to its end and says how it went.
447const handoff = async ($: Engine, config: Config, state: State, tokens: number) => {
448  const io = sessionIo($, state)
449  io.log('info', `handoff starts, method ${config.handoffMethod}`)
450  try {
451    const done = (outcome: Outcome) => (outcome.method === 'builtin-compact' ? COMPACTED : HANDED_OVER)
452    // The failure that the mark alone causes (a compact as the only way, not asked because the last one was not enough) is told once for each mark.
453    const sayFailure = (failure: Failure) => {
454      const check = state.compactCheck
455      const byMarkAlone = failure.stage === 'compact' && config.handoffMethod === 'builtin-compact' && config.handoffFallback === 'none'
456      if (!byMarkAlone || check?.kind !== 'insufficient') return true
457      if (check.said) return false
458      check.said = true
459      return true
460    }
461    await settle($, state, { name: 'handover', done, sayFailure }, async () => {
462      const outcome = await carryOut(io, state, () => throughMethods(io, state, config))
463      if (outcome.failure === undefined) {
464        state.afterHandoff = { before: tokens, pauses: 0 }
465        // A compact is checked at the first tool call or pause after it; a handoff into a fresh session starts over.
466        state.compactCheck = outcome.method === 'builtin-compact' ? { kind: 'pending' } : undefined
467      }
468      return outcome
469    })
470  } finally {
471    // `carryOut` ends the holding itself, in one step with its last look at what was held; this covers a throw before that.
472    state.handingOver = false
473    state.still = undefined
474  }
475}
476
477// A reason for postponing, or a failure, is said once: `key` is what makes two lines the same one.
478const sayOnce = ($: Engine, state: State, key: string, text: string): boolean => {
479  if (state.said === key) return false
480  state.said = key
481  say($, text)
482  return true
483}
484
485// `act` comes only with the dry run off. It starts the handoff after the stop has returned: the stop is a hook the turn waits on, and the
486// command is a turn of its own that would wait on this one.
487const handOver = ($: Engine, decision: Extract<Decision, { kind: 'act' }>, config: Config, state: State, announce = true) => {
488  // Without a first way (a compact that was not enough, and no fallback) there is nothing to announce: the run fails at the mark.
489  const first = firstMethod(config, state)
490  if (announce && first !== undefined) say($, reportOf(decision, first))
491  state.handingOver = true
492  state.held = []
493  const tasks = state.lastStop?.background_tasks
494  state.still = { standing: standingOf(tasks), forced: decision.forced === undefined ? [] : waiting(tasks) }
495  $.clock.after(0, () => void handoff($, config, state, decision.tokens))
496}
497
498// The first call of a tool in the main loop after a compact says whether it was enough. The size counts the model call that asked for the
499// tool, not the tool's result, and reads the same before and after `next(e)`: it is what the compact left and the prompt (measured,
500// host-behaviour). The pause would already hold the whole turn, and a turn that reads a lot would look like a compact that did too little.
501// Only the first reading judges. One with no size leaves it to the next call, whose size holds at most the results before it: still nearer
502// than the pause.
503const checkAtToolCall = async ($: Engine, settings: ConfigResult, config: Config, state: State) => {
504  if (state.compactCheck?.kind !== 'pending') return
505  const { tokens, window } = (await $.session.usage()).context
506  const before = state.compactCheck
507  if (before?.kind !== 'pending') return
508  state.compactCheck = checkOf(before, tokens, effectiveThreshold(config.threshold, window))
509  const line = judgedLine(before, state.compactCheck, tokens)
510  if (line === undefined) return
511  await readLevel($, settings, state)
512  logTo($, state)('debug', line)
513}
514
515// The pauses after a handoff that are logged against the context it left: enough to see where the fresh session starts and how it grows.
516const AFTER_HANDOFF_PAUSES = 3
517
518// The account's windows as the status line shows them; none off a subscription, and then the line has nothing of it.
519const limitsOf = (limits: readonly { kind: string; percentUsed: number }[]): string =>
520  limits.length === 0 ? '' : `, limits ${limits.map(l => `${l.kind} ${l.percentUsed}%`).join(', ')}`
521
522// What a pause judges, but the clock, built the same way for the pause and for the end of a countdown. `later` is checked against the
523// context: the pause has already ended it in the state, the end of a countdown only reads it.
524const snapshotOf = (
525  seen: Pick<Stop, 'background_tasks' | 'session_crons'>,
526  context: { tokens?: number; window: number },
527  agents: readonly { status: string }[],
528  turns: number,
529  state: State,
530): Omit<Snapshot, 'now'> => ({
531  tokens: context.tokens,
532  window: context.window,
533  backgroundTasks: waiting(seen.background_tasks).length,
534  standingTasks: standingOf(seen.background_tasks).length,
535  oneShotTimers: oneShots(seen.session_crons),
536  subagents: agents.filter(a => a.status === 'running').length,
537  turns,
538  lastAttempt: state.lastAttempt,
539  later: laterAt(state.later, context.tokens),
540  asap: state.asap,
541})
542
543// The line for a decision names the way tried first; with none known (a compact that was not enough, and no fallback), the setting's way.
544const reported = (decision: Exclude<Decision, { kind: 'none' }>, config: Config, state: State): string =>
545  reportOf(decision, firstMethod(config, state) ?? config.handoffMethod)
546
547// Carried out at the pause, when the countdown runs out with a judgment of its own, or by `asap` at rest: only then is it an attempt and are
548// `later` and the mark spent. A countdown that ends without a handover leaves both as they were.
549const spendMarks = ($: Engine, state: State, at: number, atTurns: number) => {
550  const log = logTo($, state)
551  // A dry run counts as an attempt too: it shows the pace the real run would keep.
552  state.said = undefined
553  state.lastAttempt = { at, turns: atTurns }
554  // `later` held for this handover, whether it goes through or not: the next one comes at the threshold.
555  if (state.later !== undefined) log('debug', 'later: spent by this handover')
556  state.later = undefined
557  // `asap` is spent by the same handover.
558  if (state.asap !== undefined) log('debug', 'asap: spent by this handover')
559  state.asap = undefined
560  // A handover that began, whether it goes through or not, ends the deferred pauses.
561  state.deferred = undefined
562}
563
564const beginHandover = ($: Engine, judged: Countdown['decision'], config: Config, state: State, at: number, atTurns: number, announce = true) => {
565  // A second source of a handover (a countdown that was still being set up when `asap` began one at rest) finds it under way.
566  if (underWay(state)) return logTo($, state)('debug', 'handover: already under way')
567  spendMarks($, state, at, atTurns)
568  if (judged.kind === 'act') handOver($, judged, config, state, announce)
569  else say($, reported(judged, config, state))
570}
571
572// What a pause reads of the host, in one go. Planning the idle handoff after it goes by the same context.
573const pauseRead = ($: Engine) => Promise.all([$.session.usage(), $.agent.list(), $.session.turns(), $.clock.now()])
574type PauseRead = Awaited<ReturnType<typeof pauseRead>>
575
576const atPause = async ($: Engine, e: Stop, config: Config, state: State, [{ context, rateLimits }, agents, turns, now]: PauseRead) => {
577  // A context below where `later` was asked has shrunk (a compact, /clear): the later handover is over before `decide` judges.
578  const kept = laterAt(state.later, context.tokens)
579  const over = state.later !== undefined && kept === undefined
580  state.later = kept
581  // The mark ends the same way.
582  const asapKept = shrunk(state.asap, context.tokens)
583  const asapOver = state.asap !== undefined && asapKept === undefined
584  state.asap = asapKept
585  // The deferred pauses end the same way.
586  const deferred = shrunk(state.deferred, context.tokens)
587  const deferredOver = state.deferred !== undefined && deferred === undefined
588  state.deferred = deferred
589  const snapshot = { ...snapshotOf(e, context, agents, turns, state), now }
590  const log = logTo($, state)
591  if (over) log('debug', LATER_OVER)
592  if (asapOver) log('debug', ASAP_OVER)
593  if (deferredOver) log('debug', 'countdown: deferred pauses over, the context shrank')
594  const fresh = state.afterHandoff
595  if (fresh !== undefined && fresh.pauses < AFTER_HANDOFF_PAUSES && snapshot.tokens !== undefined && snapshot.tokens < fresh.before) {
596    fresh.pauses += 1
597    log('debug', `after handoff: context ${snapshot.tokens} tokens (${fresh.before} before the handoff), pause ${fresh.pauses}`)
598  }
599  // Before `decide` judges and `firstMethod` names the first way: at the first pause after a compact that was not enough the context is above
600  // the threshold, so `decide` says `act`, and a mark set only after it would let that run compact once more to no effect.
601  const threshold = effectiveThreshold(config.threshold, snapshot.window)
602  const before = state.compactCheck
603  state.compactCheck = checkOf(before, snapshot.tokens, threshold)
604  const judged = judgedLine(before, state.compactCheck, snapshot.tokens)
605  if (judged !== undefined) log('debug', judged)
606  const decision = decide(snapshot, config)
607  log(
608    'info',
609    `pause: context ${snapshot.tokens} of ${snapshot.window} tokens (threshold ${threshold}${state.later === undefined ? '' : `, later ${thresholdInForce(config.threshold, snapshot.window, state.later)}`}${state.asap === undefined ? '' : ', asap'}, brake ${brakeOf(threshold, snapshot.window)}), ${snapshot.backgroundTasks + snapshot.standingTasks} background tasks (${snapshot.standingTasks} standing), ${snapshot.oneShotTimers} timers, ${snapshot.subagents} subagents, turn ${turns}, ${state.lastAttempt === undefined ? 'no attempt before' : `last attempt at turn ${state.lastAttempt.turns}`}${limitsOf(rateLimits)}, ${decidedOf(decision)}${'forced' in decision && decision.forced !== undefined ? `, forced past the brake by ${decision.forced}` : ''}`,
610  )
611  if (decision.kind === 'none') {
612    state.said = undefined
613    return
614  }
615  if (decision.kind === 'defer') {
616    sayOnce($, state, decision.reason, reported(decision, config, state))
617    return
618  }
619  // Carried out at the pause, or when the countdown runs out with a judgment of its own: only then is it an attempt and is `later` spent. A
620  // countdown that ends without a handover leaves both as they were.
621  const carry = (judged: Countdown['decision'], at: number, atTurns: number) => beginHandover($, judged, config, state, at, atTurns)
622  const postpone = (judged: Extract<Decision, { kind: 'defer' }>) => void sayOnce($, state, judged.reason, reported(judged, config, state))
623  const expiry: Expiry = { look: () => lookAgain($, e, state), judge: s => decide(s, config), carry, postpone }
624  // `asap` was asked for by the person: there is no countdown to say it again.
625  if (snapshot.asap === undefined && (await countdownBegun($, decision, config, state, snapshot, expiry))) return
626  carry(decision, now, turns)
627}
628
629// What the end of a countdown reads to judge again, as a pause does. Background tasks and one-shot timers are the stop's: after it they
630// cannot be read, and they change only in a turn, which ends the countdown.
631const lookAgain = async ($: Engine, e: Stop, state: State): Promise<Omit<Snapshot, 'now'>> => {
632  const [{ context }, agents, turns] = await Promise.all([$.session.usage(), $.agent.list(), $.session.turns()])
633  return snapshotOf(e, context, agents, turns, state)
634}
635
636// A countdown before the handover, where one is set and the first way is known; without a first way the pause goes on as before and
637// the run says why it fails.
638const countdownBegun = async ($: Engine, decision: Countdown['decision'], config: Config, state: State, snapshot: Snapshot, expiry: Expiry) => {
639  if (config.countdownSeconds === 0) return false
640  const method = firstMethod(config, state)
641  if (method === undefined) return false
642  const { window } = snapshot
643  const kind = kindAt(snapshot, config, state.deferred?.pauses ?? 0)
644  if (kind === 'immediate') {
645    logTo($, state)('debug', 'countdown: none, at the emergency brake')
646    return false
647  }
648  // The countdown at the brake counts down to the brake, which is where it hands over.
649  const threshold = kind === 'brake' ? brakeFor(config, window) : thresholdInForce(config.threshold, window, state.later)
650  const running = standingOf(state.lastStop?.background_tasks)
651    .map(t => standingPart(t.command ?? ''))
652    .filter(part => part !== undefined)
653  const start: Start = {
654    ...(kind === 'button' ? { kind, moveBack: moveBack(config, window, decision.tokens) } : { kind }),
655    method,
656    decision,
657    threshold,
658    running,
659  }
660  return begin(countdownIo($, state), state, config.countdownSeconds, start, expiry)
661}
662
663// Ends a running countdown for what a person did, at once and before any wait of the handler; the line comes after its read of the log
664// level. Nothing is moved back: the next pause counts down again.
665//
666// A hook that only watches for it passes the event on whatever goes wrong here (the `.catch` at its call): the event is the host's, and
667// a `.catch` on the hook itself would pass it on a second time where `next(e)` was what failed.
668const endCountdown = async ($: Engine, settings: ConfigResult, state: State, reason: EndReason) => {
669  if (!end(countdownIo($, state), state)) return
670  await readLevel($, settings, state)
671  logTo($, state)('debug', endedLine(reason))
672}
673
674// Ends the mark for what happened to the session, at once; the line comes after its read of the log level. Like the countdown it only watches.
675const endAsap = async ($: Engine, settings: ConfigResult, state: State, why: string) => {
676  if (state.asap === undefined) return
677  state.asap = undefined
678  await readLevel($, settings, state)
679  logTo($, state)('debug', `asap: ended, ${why}`)
680}
681
682// "Not now" moves the handover back as the command `later` with no number does, and answers the same way.
683const notNow = async ($: Engine, settings: ConfigResult, state: State) => {
684  const lines = await press(countdownIo($, state), state, () => laterText($, settings, '', state))
685  await readLevel($, settings, state)
686  const log = logTo($, state)
687  for (const [level, line] of lines) log(level, line)
688}
689
690// The stop is a hook the turn waits on and can only be asked to go on: an error here is said once and the stop ends as if the mod were absent.
691// The answer is what was read, or nothing where the read itself failed.
692const atPauseOrSay = async ($: Engine, e: Stop, config: Config, state: State): Promise<PauseRead | undefined> => {
693  let read: PauseRead | undefined
694  try {
695    read = await pauseRead($)
696    await atPause($, e, config, state, read)
697  } catch (err) {
698    sayUnread($, state, err)
699  }
700  return read
701}
702
703// This is the one place that judges, once the stop and the end of its turn are both in; a stop whose turn ended otherwise is dropped.
704// What it judges is taken by the caller before its read of the log level, together with whether a handoff runs: see `register`.
705// Only a turn that ended in an answer is a pause: Esc, an error or a refusal never starts a handoff.
706const judge = async ($: Engine, config: Config, state: State, paired: ReturnType<typeof judgeable>, handingOver: boolean) => {
707  const log = logTo($, state)
708  if ('waitingFor' in paired) {
709    log('debug', `judge: waiting for ${paired.waitingFor}`)
710    return
711  }
712  if (!handingOver && paired.end === 'answer') {
713    log('debug', 'judge: the stop and the end of the turn are both in, the turn ended in answer')
714    const read = await atPauseOrSay($, paired.stop, config, state)
715    // A handover begun at this pause replaces the session: there is no pause of it to plan for.
716    if (underWay(state)) return
717    // The plan goes by the context the pause judged; where the pause could not read, the plan reads the context itself.
718    try {
719      const tokens = read === undefined ? (await $.session.usage()).context.tokens : read[0].context.tokens
720      await planIdle($, config, state, paired.stop, tokens)
721    } catch {
722      log('warn', 'idle: could not plan')
723    }
724  } else log('debug', `judge: the turn ended in ${paired.end}, no pause`)
725}
726
727// The context the host reports, or `undefined` where it reports none or the read fails.
728const readContext = async ($: Engine, state: State): Promise<number | undefined> => {
729  try {
730    const tokens = (await $.session.usage()).context.tokens
731    return tokens !== undefined && tokens > 0 ? tokens : undefined
732  } catch {
733    logTo($, state)('debug', 'idle: the context after the request could not be read')
734    return undefined
735  }
736}
737
738// The baseline belongs to the project's setup (system prompt, tools, MCP servers, CLAUDE.md), not to one session: kept per project folder.
739const baselineKey = (cwd: string) => `idle-baseline:${cwd}`
740
741// The first request of a fresh session is the project's baseline, unless the session is one a handoff of the mod began: its first message
742// is the handoff. A request with the advisor inside it reports the sum of its passes, so where the usage sums several, the context the host
743// reported after it counts. Whatever fails here leaves the baseline as it was; the next fresh session tries again.
744const keepBaseline = async ($: Engine, state: State, usage: InputUsage, context: number | undefined) => {
745  try {
746    const [id, cwd, at] = await Promise.all([$.session.id(), $.session.cwd(), $.clock.now()])
747    if (id === state.deliveredInto) return
748    const tokens = baselineOf(usage, context)
749    state.idle.baseline = tokens
750    await $.store.set(baselineKey(cwd), { tokens, at })
751  } catch {
752    // Not kept: the transcript of a resumed session is the fallback.
753  }
754}
755
756// Reads the transcript for the cache lifetime, and finds the baseline where the first request did not give it: kept for the project, or for
757// a resumed session with none kept, the first request in its transcript. A transcript above the limit is read at its end through `tail`, the
758// one process the mod starts; it holds the latest writes, not the first request. The path is never logged.
759const readIdle = async ($: Engine, state: State, sizeAtPause?: number) => {
760  const idle = state.idle
761  idle.read = false
762  const log = logTo($, state)
763  let text: string | undefined
764  let whole = false
765  const path = idle.transcript
766  if (path !== undefined) {
767    try {
768      const size = (await $.fs.stat(path)).size
769      const plan = readPlan(size)
770      if (plan === 'read') text = String(await $.fs.read(path))
771      else {
772        // When the step comes, from where the pause began where that is further back than the end: a compact that keeps messages word for
773        // word writes them again after its mark (docs/host-behaviour.md, "a compact another hook answers"). `tail -c +n` starts at byte n,
774        // counted from 1. Its output is cut after 4 MiB, and the mark is the first thing a compact writes.
775        const from = sizeAtPause !== undefined && sizeAtPause < size - TAIL_BYTES ? `+${sizeAtPause + 1}` : String(TAIL_BYTES)
776        const end = await $.process.run(['tail', '-c', from, path])
777        if (end.exitCode !== 0) throw new Error(`tail ended with ${end.exitCode}`)
778        text = end.stdout
779      }
780      whole = plan === 'read'
781    } catch {
782      if (!idle.unreadSaid) log('warn', 'idle: the transcript could not be read')
783      idle.unreadSaid = true
784    }
785  }
786  // An end read with no write in it leaves the lifetime read before.
787  const lifetime = text === undefined ? undefined : lifetimeOf(text)
788  if (lifetime !== undefined) idle.lifetime = lifetime
789  // A turn can end before the host has written its answer to the transcript, the first of a fresh session as well as a later one
790  // (docs/host-behaviour.md, "the transcript can still lack the turn's answer"): where what was read holds no answer yet, the next turn
791  // reads again. A transcript that could not be read, or holds answers with no write, says the same next time.
792  if (idle.lifetime === undefined && text !== undefined && !hasAnswer(text)) idle.read = true
793  if (idle.baseline === undefined) {
794    try {
795      const kept = (await $.store.get(baselineKey(await $.session.cwd()))) as { tokens?: unknown } | undefined
796      if (typeof kept?.tokens === 'number') idle.baseline = kept.tokens
797    } catch {
798      // Unknown, as with none kept.
799    }
800  }
801  if (idle.baseline === undefined && !idle.fresh && whole && text !== undefined) idle.baseline = firstBaselineOf(text)
802  log('debug', `idle: cache lifetime ${idle.lifetime ?? 'unknown'}, baseline ${idle.baseline === undefined ? 'unknown' : `${idle.baseline} tokens`}`)
803  return text
804}
805
806// The line of a pause that is over, and whether a handoff written went with it.
807const pauseOverLine = (why: string, dropped: boolean) => `idle: pause over, ${why}${dropped ? ', the handoff written is dropped' : ''}`
808
809// The pause is over: the planned step and a handoff written for it go. Only the state changes here; the line it gives back, for the log,
810// is the caller's to write once it has read the log level. `why` is for that line only.
811const endPause = ($: Engine, state: State, why: string): string | undefined => {
812  const idle = state.idle
813  // The step under way has no timer and nothing written yet: it is told, and drops what it writes.
814  if (state.preparing && idle.prepared === undefined) idle.endedWhilePreparing = why
815  idle.reread?.cancel()
816  idle.reread = undefined
817  if (idle.timer === undefined && idle.prepared === undefined) return undefined
818  idle.timer?.cancel()
819  idle.timer = undefined
820  idle.coldTimer?.cancel()
821  idle.coldTimer = undefined
822  if (idle.coldShown) void $.ui.invalidate('ui.render')
823  idle.coldShown = false
824  const dropped = idle.prepared !== undefined
825  idle.prepared = undefined
826  return pauseOverLine(why, dropped)
827}
828
829// Writes the line `endPause` gave back, after the read of the log level, for a handler that has nothing else to log.
830const logPauseOver = async ($: Engine, settings: ConfigResult, state: State, over: string | undefined) => {
831  if (over === undefined) return
832  await readLevel($, settings, state)
833  logTo($, state)('debug', over)
834}
835
836// At the end of each answer, the step that writes the handoff is planned anew, 55 minutes after the answer's last request.
837const planIdle = async ($: Engine, config: Config, state: State, stop: Stop, tokens: number | undefined) => {
838  const idle = state.idle
839  idle.timer?.cancel()
840  idle.timer = undefined
841  const log = logTo($, state)
842  const verdict = planVerdict({
843    on: config.idleHandoff,
844    lifetime: idle.lifetime,
845    tokens,
846    floor: floorOf(config.idleHandoffMinTokens, idle.baseline),
847    handingOver: underWay(state),
848    timers: stop.session_crons?.length ?? 0,
849  })
850  const touch = idle.touch
851  if (!verdict.plan || touch === undefined) {
852    log('debug', `idle: not planned, ${verdict.plan ? 'no request seen' : verdict.why}`)
853    // The answer of the first turn may not be in the transcript yet: read once more a little later, and plan from that read.
854    if (idle.lifetime === undefined && idle.read && idle.transcript !== undefined) {
855      idle.reread = $.clock.after(REREAD_MS, () => void rereadIdle($, config, state, stop, tokens))
856    }
857    return
858  }
859  const size = await transcriptSize($, idle.transcript)
860  const now = await $.clock.now()
861  const wait = armIdle($, config, state, touch, { since: now, size }, now)
862  log('debug', `idle: planned in ${Math.round(wait / 60_000)} min`)
863}
864
865// The size of the transcript, or none where it cannot be told: the step then reads its end only, as before.
866const transcriptSize = async ($: Engine, path: string | undefined) => {
867  if (path === undefined) return undefined
868  try {
869    return (await $.fs.stat(path)).size
870  } catch {
871    return undefined
872  }
873}
874
875// The transcript missed the answer by 0.21 s, measured in one session (docs/host-behaviour.md, "the transcript can still lack the turn's
876// answer"); five seconds leave room above that.
877const REREAD_MS = 5_000
878
879// A turn that starts while the read runs ends the pause, and finds nothing to cancel yet: it is seen here, after the read.
880const rereadIdle = async ($: Engine, config: Config, state: State, stop: Stop, tokens: number | undefined) => {
881  state.idle.reread = undefined
882  await readIdle($, state).catch(() => {})
883  if (state.idle.lifetime !== undefined && !state.answerRunning) await planIdle($, config, state, stop, tokens).catch(() => {})
884}
885
886// Sets the step for its time, from the touch, for the pause it belongs to (`Pause` in state.ts). Gives the wait.
887const armIdle = ($: Engine, config: Config, state: State, touch: number, pause: Pause, now: number) => {
888  const wait = Math.max(0, prepareDueAt(touch) - now)
889  const timer = $.clock.after(wait, () => void prepareIdle($, config, state, pause))
890  state.idle.timer = { cancel: () => timer.cancel(), ...pause }
891  return wait
892}
893
894// Holds the planned step back while a compact runs, so that nothing is written of a context the compact replaces, and gives back what sets
895// it again where the compact did not go through. Meanwhile a timer that never fires stands in its place: the pause still has a step
896// planned, for `endPause` and the status, and a stop that plans anew replaces it as it would the step.
897const holdIdle = ($: Engine, config: Config | undefined, state: State) => {
898  const idle = state.idle
899  const held = idle.timer
900  if (held === undefined || config === undefined) return () => Promise.resolve()
901  held.cancel()
902  const pause: Pause = { since: held.since, size: held.size }
903  const standIn = { cancel: () => {}, ...pause }
904  idle.timer = standIn
905  return async () => {
906    if (idle.timer === standIn && idle.touch !== undefined) armIdle($, config, state, idle.touch, pause, await $.clock.now())
907  }
908}
909
910// The step itself: the reads first, then every check and the mark in one go with no wait between, so that a turn of the person's that starts
911// meanwhile is seen and not taken for the mod's own.
912const prepareIdle = async ($: Engine, config: Config, state: State, { since, size }: Pause) => {
913  const idle = state.idle
914  idle.timer = undefined
915  idle.endedWhilePreparing = undefined
916  const log = logTo($, state)
917  try {
918    const [agents, now, usage, text] = await Promise.all([
919      $.agent.list(),
920      $.clock.now(),
921      $.session.usage(),
922      idle.transcript === undefined ? undefined : readIdle($, state, size),
923    ])
924    // A hook above the mod can answer a compact with messages of its own and not pass it on, so the mod's own hook never ends the pause
925    // (docs/host-behaviour.md, "a compact another hook answers"). The host marks it in the transcript all the same.
926    if (text !== undefined && compactedSince(text, since)) return log('debug', pauseOverLine('a compact in the transcript', false))
927    const busy = state.answerRunning
928      ? 'a turn runs'
929      : underWay(state)
930        ? 'a handover runs'
931        : state.countdown !== undefined
932          ? 'a countdown runs'
933          : agents.some(a => a.status === 'running')
934            ? 'a subagent runs'
935            : undefined
936    const verdict = fireVerdict({ busy, lifetime: idle.lifetime, now, touch: idle.touch ?? now })
937    if (!verdict.go) return log('debug', `idle: not prepared, ${verdict.why}`)
938    if (config.dryRun) {
939      idle.prepared = { kind: 'simulated', since }
940      return log('info', 'idle: would prepare')
941    }
942    state.preparing = true
943    state.held = []
944    const io = sessionIo($, state)
945    // Nothing runs between this and the return (a turn ends the pause), so the list is the one the return is judged on. The first message is
946    // written here and kept in `idle.prepared`, so the list goes as soon as it is.
947    state.still = { standing: standingOf(state.lastStop?.background_tasks), forced: [] }
948    try {
949      const r = await prepare(io, state, config)
950      state.still = undefined
951      const over = idle.endedWhilePreparing
952      if (over !== undefined) log('debug', pauseOverLine(over, true))
953      else if ('stage' in r) {
954        say($, notPreparedLine(r.reason))
955        log('warn', `idle: preparing failed (stage ${r.stage})`)
956      } else {
957        idle.prepared = { kind: 'real', text: r.text, ...(r.file === undefined ? {} : { file: r.file }), since }
958        log('info', `idle: handoff prepared, ${r.text.length} characters`)
959        // Reading the cache keeps it for another hour from when the model was asked (measured); a request that missed it may have written a
960        // short-lived entry of its own. The command's turn needs no check: its requests read or write the session's own entry, and each moved
961        // the touch as it went out. A `$.model.fork` request that tries a tool is refused and asks again, and its usage sums both: the
962        // second reads what the first wrote. The context it is measured by is the session's, which the call leaves as it was (measured).
963        if (r.began !== undefined && !idle.doubted) {
964          const context = usage.context.tokens
965          if (isHit(r.usage, context ?? Number.POSITIVE_INFINITY, context)) idle.touch = r.began
966          else log('debug', 'idle: the handoff missed the cache, the touch stays')
967        }
968        const touch = idle.touch ?? now
969        idle.coldTimer = $.clock.after(Math.max(0, touch + HOUR_MS - (await $.clock.now())), () => {
970          idle.coldTimer = undefined
971          showCold($, state)
972        })
973      }
974    } finally {
975      state.still = undefined
976      await release(io, state, undefined, () => {
977        state.preparing = false
978      })
979    }
980  } catch (err) {
981    state.preparing = false
982    say($, notPreparedLine(why(err)))
983    log('warn', 'idle: preparing failed (unexpected error)')
984  }
985}
986
987// The message that came back after the handoff was written, which has already taken it (`claim`). Judged by the clock and by what runs;
988// whatever the verdict, the handoff written is gone. Only a cold cache with nothing running switches: the message is turned away here and
989// goes into the fresh session with the handoff, from a step of its own, since the host refuses a /clear from a hook that holds a turn.
990// Everything else lets the message through into this session. The answer is the drop reason, or `undefined` to let it through.
991const comeBack = async ($: Engine, state: State, prepared: IdlePrepared, input: { text: string; attachments?: readonly unknown[] }) => {
992  const log = logTo($, state)
993  let verdict: ReturnType<typeof returnVerdict>
994  let now: number
995  let turns: number
996  let tokens: number | undefined
997  try {
998    const [agents, at, count, usage] = await Promise.all([$.agent.list(), $.clock.now(), $.session.turns(), $.session.usage()])
999    now = at
1000    turns = count
1001    tokens = usage.context.tokens
1002    const stop = state.lastStop
1003    const busy =
1004      busyReason({
1005        subagents: agents.filter(a => a.status === 'running').length,
1006        backgroundTasks: waiting(stop?.background_tasks).length,
1007        oneShotTimers: oneShots(stop?.session_crons),
1008      }) !== undefined
1009    verdict = returnVerdict({ now, touch: state.idle.touch ?? now, busy, attachments: (input.attachments?.length ?? 0) > 0 })
1010  } catch {
1011    log('warn', 'idle: could not judge the return, the message stays in this session')
1012    endReturn($, state)
1013    return undefined
1014  }
1015  if (verdict === 'cold' && prepared.kind === 'real') {
1016    // In one step with no wait: from here the holding is the handover's, and the message is the first of what it carries.
1017    state.returning = false
1018    state.handingOver = true
1019    state.held.unshift(input.text)
1020    spendMarks($, state, now, turns)
1021    log('info', 'idle: return after the cache expired, handing over')
1022    $.clock.after(0, () => void returnInto($, state, prepared, input.text, () => switchedLine(idleFor(now - prepared.since))))
1023    return HELD_MOMENT
1024  }
1025  endReturn($, state)
1026  if (verdict === 'warm') {
1027    state.idle.checkAgainst = tokens
1028    log('debug', 'idle: return while the cache is warm, the handoff written is dropped')
1029    return undefined
1030  }
1031  // What remains keeps a cold cache in this session: running work, an attachment, or a dry run, which counts as an attempt as at the threshold.
1032  if (verdict === 'busy') say($, WORK_STAYS)
1033  else if (verdict === 'attachments') say($, ATTACHMENTS_STAY)
1034  else {
1035    spendMarks($, state, now, turns)
1036    say($, DRY_RUN_RETURN)
1037  }
1038  log('debug', `idle: return after the cache expired, ${verdict === 'cold' ? 'dry run' : verdict}, the message stays in this session`)
1039  return undefined
1040}
1041
1042// The judgment is over and the message goes into this session: what was typed meanwhile follows it, from a step of its own so that it comes
1043// after the message the hook lets through.
1044const endReturn = ($: Engine, state: State) => {
1045  if (state.held.length === 0) {
1046    state.returning = false
1047    return
1048  }
1049  $.clock.after(
1050    0,
1051    () =>
1052      void release(sessionIo($, state), state, undefined, () => {
1053        state.returning = false
1054      }),
1055  )
1056}
1057
1058// The switch: /clear, then the handoff with the message that came back. The host leaves a message a hook turned away in the prompt, and that
1059// survives the /clear: once the message is in, the prompt is cleared of it, unless the person has changed it since.
1060// `asap` hands the handoff over the same way, with no message of its own (`text` undefined) and its own line at the end.
1061const returnInto = async ($: Engine, state: State, prepared: Extract<IdlePrepared, { kind: 'real' }>, text: string | undefined, done: () => string) => {
1062  const io = sessionIo($, state)
1063  try {
1064    let delivered = false
1065    await settle($, state, { name: 'handover', done }, () =>
1066      carryOut(io, state, async () => {
1067        const failure = await deliverReturn(io, state, prepared, text !== undefined)
1068        delivered = failure === undefined
1069        return failure === undefined ? {} : { failure }
1070      }),
1071    )
1072    if (delivered && text !== undefined && (await $.prompt.read()).text.trim() === text.trim()) await $.prompt.fill({ text: '', mode: 'replace' })
1073  } catch {
1074    io.log('debug', 'idle: could not clear the prompt after the switch')
1075  } finally {
1076    state.handingOver = false
1077  }
1078}
1079
1080// The band says it once the handoff written has gone cold. A late timer (system sleep) shows it late: typing checks the clock as well.
1081const showCold = ($: Engine, state: State) => {
1082  const idle = state.idle
1083  if (idle.prepared?.kind !== 'real' || idle.coldShown) return
1084  idle.coldShown = true
1085  void $.ui.invalidate('ui.render')
1086  logTo($, state)('debug', 'idle: the handoff written has gone cold, the band says so')
1087}
1088
1089// From typing: the level is read only once the band is to show, not at every key.
1090const checkCold = async ($: Engine, settings: ConfigResult, state: State) => {
1091  const touch = state.idle.touch
1092  if (touch === undefined || (await $.clock.now()) - touch < HOUR_MS) return
1093  await readLevel($, settings, state)
1094  showCold($, state)
1095}
1096
1097export const register: Register = (on, options) => {
1098  const settings = configOf(options)
1099  const config = settings.ok ? settings.config : undefined
1100  const state = freshState()
1101
1102  // Every handler reads the log level, each on its own: a value changed in a settings file reaches the host at the next turn. The read is a
1103  // wait, and two handlers' reads need not come back in the order they went out, so a handler changes the state before it reads, as it
1104  // would with no read at all, and logs after.
1105  on('session.start', async ($, e, next) => {
1106    // Every session reads the transcript at its first turn: a /clear does not reload the mod, but ends what was known of the session.
1107    state.idle.read = true
1108    await readLevel($, settings, state)
1109    await introduce($, settings, state)
1110    return next(e)
1111  })
1112
1113  // The redelivery's timer runs outside any handler; its lines come after its own waits, by when the read here is in.
1114  on('command.run', { command: COMMAND }, async ($, e) => {
1115    // `later` and `asap` end a countdown before they move the handover back or ask for one. Typed, its first character has already ended
1116    // it; a command raises no submit, and from the history it is expected to come with no edit either (docs/host-behaviour.md, Commands).
1117    // `redeliver` leaves it running.
1118    const verb = verbOf(e.args)
1119    const ended = (verb === 'later' || verb === 'asap') && end(countdownIo($, state), state)
1120    const { text, lines = [] } = await commandText($, settings, e.args, state)
1121    await readLevel($, settings, state)
1122    const log = logTo($, state)
1123    if (ended) log('debug', endedLine('command'))
1124    for (const [level, line] of lines) log(level, line)
1125    return { text }
1126  }).catch((_, e, next) => next(e))
1127
1128  // A reload puts the mod into a session that is already running, which raises no session start: the first turn says the settings then.
1129  on('turn.start', async ($, e, next) => {
1130    turnStarted(state.pairing)
1131    // Only a mod with settings it can trust sees the end of the answer (`turn.complete` is past the gate below), so only it marks one running.
1132    if (config !== undefined) state.answerRunning = true
1133    state.lastStop = undefined
1134    const awaited = state.turnWait !== undefined
1135    const own = startOfTurn(state, e.turnId)
1136    // A turn is the end of a pause, unless it is the command's own while it writes the handoff. Any other turn meanwhile ends it: a slash
1137    // command that starts one, or the message held meanwhile, whose turn starts while it is put in (its submit settles once the turn started).
1138    const over = state.preparing && own ? undefined : endPause($, state, 'a turn started')
1139    // A turn is work, whoever started it (a finished background task starts one too): no handover in the middle of it.
1140    const ended = end(countdownIo($, state), state)
1141    await readLevel($, settings, state)
1142    await introduce($, settings, state)
1143    const log = logTo($, state)
1144    log('trace', `turn.start ${e.turnId}`)
1145    if (ended) log('debug', endedLine('turn'))
1146    if (awaited) log('debug', own ? `turn ${e.turnId} is the command's turn` : `turn ${e.turnId} is not the command's turn`)
1147    if (over !== undefined) log('debug', over)
1148    return next(e)
1149  })
1150
1151  // A mod with settings it cannot trust goes no further: it has said why where the person looks, and answers its command.
1152  if (config === undefined) return
1153
1154  // How the session began: a start or a /clear has no conversation, so its first request is the project's baseline.
1155  on('classic.SessionStart', async ($, e, next) => {
1156    if (e.agent_id === undefined) {
1157      state.idle.fresh = e.source === 'startup' || e.source === 'clear'
1158      state.idle.baselineDue = state.idle.fresh
1159      state.idle.transcript = e.transcript_path
1160    }
1161    return next(e)
1162  })
1163
1164  // A change of model says the cache lifetime outright, the one place the host does.
1165  on('classic.PostModelSwitch', async ($, e, next) => {
1166    if (e.agent_id === undefined) {
1167      state.idle.lifetime = e.cache_ttl
1168      await logPauseOver($, settings, state, endPause($, state, 'a change of model'))
1169    }
1170    return next(e)
1171  })
1172
1173  // While the handoff is written nobody is there to answer a permission the command's turn asks for: it is turned down, which ends the turn
1174  // at once (measured), and the mod writes the handoff instead. The mod never grants one, and outside that turn every prompt shows as it is.
1175  on('classic.PermissionRequest', async ($, e, next) => {
1176    if (!state.preparing || state.turnWait?.own === undefined || e.agent_id !== undefined) return next(e)
1177    await readLevel($, settings, state)
1178    logTo($, state)('debug', `idle: a permission for ${e.tool_name} was turned down while the handoff is written`)
1179    return { decision: { behavior: 'deny', interrupt: true } }
1180  })
1181
1182  // Only for the path of the transcript: the end of the first turn reads it, and may come before the stop. After a reload no session start
1183  // came to give it.
1184  on('classic.UserPromptSubmit', async ($, e, next) => {
1185    if (e.agent_id === undefined) state.idle.transcript = e.transcript_path
1186    return next(e)
1187  })
1188
1189  // Each request of the main loop reads or writes the cache: its start is the touch, taken before the request goes out, which is never too
1190  // late. The first request of a fresh session gives the baseline. The level is not read here: a read at every request would be a round
1191  // trip each; the level in force is the one the turn's start read.
1192  on('turn.step', async function* ($, e, next) {
1193    if (e.agentId !== undefined) return yield* next(e)
1194    const idle = state.idle
1195    // The command's turn writing the handoff reads the cache like any turn, unless that is no longer believed.
1196    if (!(state.preparing && idle.doubted)) idle.touch = await $.clock.now()
1197    const r = yield* next(e)
1198    const against = idle.checkAgainst
1199    const due = e.index === 0 && r.usage !== null && (against !== undefined || idle.baselineDue)
1200    // The context after the request, read once and only where the check or the baseline needs it. Before the step the host still reports
hooks/config.ts 122 lines
1// Reads the settings of the plugin. A value that does not fit is rejected with its value and the reason, never replaced by a default:
2// a quiet replacement would hand over at a threshold nobody chose.
3
4// The ways to hand a session over, once: the type is read from this list, `plugin.json` offers the same values and `docs/src/check.py`
5// reads the list (a union type could only be read by a pattern that breaks easily).
6export const METHODS = ['external-command', 'internal-handoff', 'builtin-compact'] as const
7export type Method = (typeof METHODS)[number]
8
9export type Config = {
10  threshold: number
11  dryRun: boolean
12  minGapMinutes: number
13  minGapTurns: number
14  // How far `/sweet-spot later` with no number moves a handover back, in tokens.
15  laterTokens: number
16  // How long the mod waits before an automatic handover, in seconds. 0: no wait.
17  countdownSeconds: number
18  // The main way, and the one tried when it fails before it changed the session. 'none': no second try.
19  handoffMethod: Method
20  handoffFallback: Method | 'none'
21  handoffCommand: string
22  // The handoff after a long pause: on or off, and the context size it starts at. 0: the session's baseline plus a fixed distance.
23  idleHandoff: boolean
24  idleHandoffMinTokens: number
25}
26export type ConfigResult = { ok: true; config: Config } | { ok: false; errors: string[] }
27
28// The defaults of plugin.json. The host checks type and `min` of plugin.json before it loads the mod, so what is checked here is a second
29// line of defence, and the only one for the rules across values; the tests pin these and the defaults of plugin.json to the same values.
30// No command by default: one that merely shares the name `handoff` is not the user's to run.
31export const DEFAULTS: Config = {
32  threshold: 200_000,
33  dryRun: false,
34  minGapMinutes: 10,
35  minGapTurns: 5,
36  laterTokens: 25_000,
37  countdownSeconds: 10,
38  handoffMethod: 'internal-handoff',
39  handoffFallback: 'builtin-compact',
40  handoffCommand: '',
41  idleHandoff: true,
42  idleHandoffMinTokens: 0,
43}
44
45// The same number is `min` and the text of `threshold` in plugin.json and the README; the tests cannot read those files, so a change here
46// is made in all three. Below this a fresh session already starts near the threshold (the CHANGELOG has the numbers, under Chosen, with the reason): every pause would hand over again.
47const MIN_THRESHOLD = 130_000
48
49// The span of `countdown_seconds`, the same as `min` and `max` in plugin.json; `docs/src/check.py` compares the two. The test engine refuses a
50// value above `max` before the mod loads, but lets a fraction through; whether a real load checks `max` is not measured.
51export const COUNTDOWN_SECONDS = { min: 0, max: 60 } as const
52
53// `JSON.stringify` writes NaN and Infinity as null.
54const show = (raw: unknown): string => (typeof raw === 'number' ? String(raw) : (JSON.stringify(raw) ?? String(raw)))
55
56type Checked<T> = { value: T } | { error: string }
57
58const finiteAtLeast = (raw: unknown, min: number, whole: boolean, { why = '', max = Number.POSITIVE_INFINITY } = {}): Checked<number> => {
59  if (typeof raw !== 'number') return { error: `${show(raw)} is not a number` }
60  if (!Number.isFinite(raw)) return { error: `${show(raw)} is not a finite number` }
61  if (raw < min) return { error: `${show(raw)} is below ${min}${why}` }
62  if (raw > max) return { error: `${show(raw)} is above ${max}` }
63  if (whole && !Number.isInteger(raw)) return { error: `${show(raw)} is not a whole number` }
64  return { value: raw }
65}
66
67const flag = (raw: unknown): Checked<boolean> => (typeof raw === 'boolean' ? { value: raw } : { error: `${show(raw)} is not true or false` })
68
69const commandName = (raw: unknown): Checked<string> => {
70  if (typeof raw !== 'string') return { error: `${show(raw)} is not a text` }
71  // Empty is no command of your own: the internal handoff writes it.
72  if (raw.trim() === '') return { value: '' }
73  if (raw.startsWith('/')) return { error: `${show(raw)} starts with a slash, give the name without it` }
74  if (/\s/.test(raw)) return { error: `${show(raw)} has a space, give the name only` }
75  return { value: raw }
76}
77
78const oneOf =
79  <T extends string>(values: readonly T[]) =>
80  (raw: unknown): Checked<T> =>
81    typeof raw === 'string' && (values as readonly string[]).includes(raw) ? { value: raw as T } : { error: `${show(raw)} is not one of ${values.join(', ')}` }
82
83export const configOf = (options: Record<string, unknown>): ConfigResult => {
84  const errors: string[] = []
85  // An unset value is the default; a set one is checked as it is.
86  const take = <T>(key: string, fallback: T, check: (raw: unknown) => Checked<T>): T => {
87    const raw = options[key]
88    if (raw === undefined) return fallback
89    const checked = check(raw)
90    if ('error' in checked) {
91      errors.push(`${key}: ${checked.error}`)
92      return fallback
93    }
94    return checked.value
95  }
96  const config: Config = {
97    threshold: take('threshold', DEFAULTS.threshold, raw =>
98      finiteAtLeast(raw, MIN_THRESHOLD, false, { why: ', a handoff that close to the start would repeat' }),
99    ),
100    dryRun: take('dry_run', DEFAULTS.dryRun, flag),
101    minGapMinutes: take('min_gap_minutes', DEFAULTS.minGapMinutes, raw => finiteAtLeast(raw, 0, false)),
102    minGapTurns: take('min_gap_turns', DEFAULTS.minGapTurns, raw => finiteAtLeast(raw, 0, true)),
103    laterTokens: take('later_tokens', DEFAULTS.laterTokens, raw => finiteAtLeast(raw, 1, true)),
104    countdownSeconds: take('countdown_seconds', DEFAULTS.countdownSeconds, raw =>
105      finiteAtLeast(raw, COUNTDOWN_SECONDS.min, true, { max: COUNTDOWN_SECONDS.max }),
106    ),
107    handoffMethod: take('handoff_method', DEFAULTS.handoffMethod, oneOf(METHODS)),
108    handoffFallback: take('handoff_fallback', DEFAULTS.handoffFallback, oneOf([...METHODS, 'none'] as const)),
109    handoffCommand: take('handoff_command', DEFAULTS.handoffCommand, commandName),
110    idleHandoff: take('idle_handoff', DEFAULTS.idleHandoff, flag),
111    idleHandoffMinTokens: take('idle_handoff_min_tokens', DEFAULTS.idleHandoffMinTokens, raw => finiteAtLeast(raw, 0, true)),
112  }
113  // The same way twice is no second try. Done before the rule below, so that one field asking for the command is told once.
114  if (config.handoffFallback === config.handoffMethod) config.handoffFallback = 'none'
115  // A way that can never run switches the mod off with the reason, rather than failing at every handoff.
116  if (config.handoffCommand === '') {
117    const key = config.handoffMethod === 'external-command' ? 'handoff_method' : config.handoffFallback === 'external-command' ? 'handoff_fallback' : undefined
118    if (key) errors.push(`${key}: "external-command" needs handoff_command, which is empty`)
119  }
120  return errors.length > 0 ? { ok: false, errors } : { ok: true, config }
121}
122
hooks/asap.ts 19 lines
1// What `/sweet-spot asap` makes of the context it is typed at. Pure: the command reads the session and keeps what comes back, so that the
2// answer and the pause judge from the one mark.
3
4import type { Config } from './config'
5import type { Asap } from './decide'
6
7// The mark and the answer at a known context. An answer that is running ends in a pause, and that pause hands over.
8export const asapFor = (config: Config, tokens: number): { asap: Asap; text: string; lines: string[] } => ({
9  asap: { from: tokens },
10  text: `${config.dryRun ? 'dry run, would hand over' : 'hands over'} at the next pause, context ${tokens} tokens`,
11  lines: [`asap: set at context ${tokens}`],
12})
13
14// The debug line for a mark that a shrunken context ended, at a pause.
15export const ASAP_OVER = 'asap: over, the context shrank below where it was asked'
16
17// What the answer adds at rest when the last stop is not known (after /clear, or an Esc with no stop): the mod does not hand over blind.
18export const RUNNING_UNKNOWN = 'what is running is not known until the next answer'
19
hooks/decide.ts 105 lines
1// Whether to hand over now. Pure: the caller takes the snapshot, acts on the answer, and keeps the record of the last attempt.
2
3import type { Config } from './config'
4import type { TaskSummary } from './pairing'
5import { standing } from './standing'
6
7export type Attempt = { at: number; turns: number }
8
9// A handover moved back by `/sweet-spot later`: asked at a context of `from`, to hand over at `until`. `until` is kept as asked, not
10// capped: the cap comes from the window, which can change before the pause that judges it.
11export type Later = { from: number; until: number }
12
13// A handover asked for with `/sweet-spot asap`, at a context of `from`: it lifts the threshold and the minimum gap for the next handover, and
14// nothing else. Work that is running still holds it back, below the emergency brake.
15export type Asap = { from: number }
16
17export type Snapshot = {
18  // Input side of the last answer; undefined in a fresh session and after /clear.
19  tokens: number | undefined
20  window: number
21  // Waiting tasks: running, standing ones excluded. A dev server never ends, and nothing waits for its result.
22  backgroundTasks: number
23  // Running tasks that never end by themselves; they hold nothing back, and the pause line names how many there are.
24  standingTasks: number
25  oneShotTimers: number
26  subagents: number
27  now: number
28  turns: number
29  lastAttempt: Attempt | undefined
30  later: Later | undefined
31  asap: Asap | undefined
32}
33
34// Work that is still running and reports back to the session. A handoff written now cannot hold its result, and the result would come
35// into a fresh session that does not know what it was for.
36export type BusyReason = 'subagent' | 'background-task' | 'one-shot-timer'
37
38// `turn` only the end of a countdown finds: a turn that started while the countdown began, before there was one for it to end.
39export type DeferReason = BusyReason | 'min-gap' | 'turn'
40
41// `act` and `dry-run` ("would hand over") carry `forced`: the work the emergency brake handed over despite.
42export type Decision =
43  | { kind: 'none' }
44  | { kind: 'defer'; reason: DeferReason; tokens: number }
45  | { kind: 'act'; tokens: number; forced?: BusyReason }
46  | { kind: 'dry-run'; tokens: number; forced?: BusyReason }
47
48// Past the threshold the context may grow this far while work runs, and never beyond 90 percent of the window.
49const BRAKE_EXTRA = 150_000
50
51// Not a setting: 80 percent of the window, so that the handoff itself still fits. Whole numbers, because 0.8 has no exact binary form.
52export const effectiveThreshold = (threshold: number, window: number): number => Math.min(threshold, Math.floor((window * 4) / 5))
53
54// Counted from the threshold in force, which a small window has already lowered.
55export const brakeOf = (threshold: number, window: number): number => Math.min(Math.floor((window * 9) / 10), threshold + BRAKE_EXTRA)
56
57// The brake of the settings at a window, counted from the threshold in force there.
58export const brakeFor = (config: Pick<Config, 'threshold'>, window: number): number => brakeOf(effectiveThreshold(config.threshold, window), window)
59
60// The value a pause judges at: the threshold in force, or the one `later` asked for. That one is capped at the brake of the window as it
61// is now (after a change to a smaller window it would lie past the brake, or past the window, and nothing would ever hand over), and it never
62// lies below the threshold in force (after a change to a larger window it would bring the handover forward). The answer of `later`, the
63// pause's log line and `decide` all take it from here.
64export const thresholdInForce = (threshold: number, window: number, later: Later | undefined): number => {
65  const t = effectiveThreshold(threshold, window)
66  return later === undefined ? t : Math.max(t, Math.min(later.until, brakeOf(t, window)))
67}
68
69// A context below where a mark was set has shrunk (a compact of any kind, or /clear), and ends it; no reading of the context changes
70// nothing, as with the compact check.
71export const shrunk = <T extends { from: number }>(mark: T | undefined, tokens: number | undefined): T | undefined =>
72  mark === undefined || tokens === undefined || tokens >= mark.from ? mark : undefined
73export const laterAt = shrunk<Later>
74
75// The one rule of what counts as running work, for the pause and for coming back after a long one.
76export const busyReason = (s: Pick<Snapshot, 'subagents' | 'backgroundTasks' | 'oneShotTimers'>): BusyReason | undefined =>
77  s.subagents > 0 ? 'subagent' : s.backgroundTasks > 0 ? 'background-task' : s.oneShotTimers > 0 ? 'one-shot-timer' : undefined
78
79// Over when the minutes or the turns have passed, so a count of turns that starts over with a fresh session cannot hold the lock for good.
80// Kept after a failure as after a success: a handoff that fails every time must not retry at every stop.
81const withinGap = (s: Snapshot, config: Config): boolean =>
82  s.lastAttempt !== undefined && s.now - s.lastAttempt.at < config.minGapMinutes * 60_000 && s.turns - s.lastAttempt.turns < config.minGapTurns
83
84// The statuses after which a task no longer wakes the session.
85const FINAL = new Set(['completed', 'failed', 'killed', 'stopped', 'cancelled', 'canceled', 'error'])
86
87export const running = (tasks: readonly TaskSummary[] | undefined): TaskSummary[] => (tasks ?? []).filter(t => !FINAL.has(t.status))
88
89// What a handover waits for, and what it does not: a running task is one or the other.
90export const waiting = (tasks: readonly TaskSummary[] | undefined): TaskSummary[] => running(tasks).filter(t => !standing(t))
91export const standingOf = (tasks: readonly TaskSummary[] | undefined): TaskSummary[] => running(tasks).filter(standing)
92
93// A recurring timer is a standing loop: it would not end by waiting.
94export const oneShots = (crons: readonly { recurring: boolean }[] | undefined): number => (crons ?? []).filter(c => !c.recurring).length
95
96export const decide = (snapshot: Snapshot, config: Config): Decision => {
97  const { tokens, window } = snapshot
98  const threshold = effectiveThreshold(config.threshold, window)
99  if (tokens === undefined || (snapshot.asap === undefined && tokens < thresholdInForce(config.threshold, window, snapshot.later))) return { kind: 'none' }
100  const busy = busyReason(snapshot)
101  if (busy !== undefined && tokens < brakeOf(threshold, window)) return { kind: 'defer', reason: busy, tokens }
102  if (snapshot.asap === undefined && withinGap(snapshot, config)) return { kind: 'defer', reason: 'min-gap', tokens }
103  return { kind: config.dryRun ? 'dry-run' : 'act', tokens, ...(busy === undefined ? {} : { forced: busy }) }
104}
105
hooks/hold.ts 47 lines
1// What a person types while a handover runs: the typing is held and goes in when the handover is done, so it is neither lost nor sent into a
2// session that is about to be cleared. These lines carry the name themselves: the host puts it only in
3// front of log lines and command replies.
4
5import { underWay, type IdlePrepared, type State } from './state'
6
7export const HELD = 'sweet-spot: a handover is in progress, your message is held and goes in when it is done'
8export const NO_ATTACHMENTS = 'sweet-spot: a handover is in progress and attachments cannot be held, send the message again when it is done'
9
10// While the handoff after a long pause is written, which takes seconds and changes nothing the person sees.
11export const HELD_MOMENT = 'sweet-spot: your message is held for a moment and goes in right after'
12export const NO_ATTACHMENTS_MOMENT = 'sweet-spot: attachments cannot be held, send the message again in a moment'
13
14type Typing = { text: string; attachments?: readonly unknown[]; origin: { kind: string } }
15
16// Typed at the prompt by a person, and no slash command.
17const byPerson = (input: Typing): boolean => (input.origin.kind === 'composer' || input.origin.kind === 'bridge') && !input.text.trimStart().startsWith('/')
18
19// The reason to drop the input with, when it is held; `undefined` lets it through. Only what a person types at the prompt is held: a slash
20// command still runs, and what other parts of the system send is theirs.
21export const hold = (state: State, input: Typing): string | undefined => {
22  if (!underWay(state)) return undefined
23  const quiet = !state.handingOver
24  if (!byPerson(input)) return undefined
25  // The mod cannot get at the content of an attachment, so the whole input is turned away and nothing of it is half kept.
26  if ((input.attachments?.length ?? 0) > 0) return quiet ? NO_ATTACHMENTS_MOMENT : NO_ATTACHMENTS
27  const text = input.text.trim()
28  if (text === '') return undefined
29  state.held.push(input.text)
30  return quiet ? HELD_MOMENT : HELD
31}
32
33// The first message a person sends after the handoff was written takes it, at once and before any wait, so that a second message never sees
34// it too. Typing that is empty, a slash command and what other parts of the system send leave it: a slash command is no message to carry
35// into a fresh session (`/model`, `/clear`), and a turn it starts ends the pause.
36export const claim = (state: State, input: Typing): IdlePrepared | undefined => {
37  const prepared = state.idle.prepared
38  if (prepared === undefined || !byPerson(input) || input.text.trim() === '') return undefined
39  state.idle.prepared = undefined
40  state.idle.coldTimer?.cancel()
41  state.idle.coldTimer = undefined
42  state.idle.coldShown = false
43  state.returning = true
44  state.held = []
45  return prepared
46}
47
hooks/later.ts 54 lines
1// What `/sweet-spot later` makes of its argument and of the context it is typed at. Pure: the command reads the session and keeps what
2// comes back, so that the answer, the pause line and `decide` take the value in force from the one place (`thresholdInForce`).
3
4import type { Config } from './config'
5import { brakeOf, effectiveThreshold, laterAt, thresholdInForce, type Later } from './decide'
6
7// A whole number of tokens, with `k` for a thousand. Anything else is turned down with what was typed: the mod never quietly rounds
8// `1.5k` or reads `50 k` as 50000, as it never replaces a setting.
9const TOKENS = /^[0-9]+[kK]?$/
10
11// The argument after `later`: none takes `later_tokens`, which only the settings know.
12export const tokensOf = (rest: string): { tokens: number | 'setting' } | { error: string } => {
13  const text = rest.trim()
14  if (text === '') return { tokens: 'setting' }
15  const tokens = TOKENS.test(text) ? Number.parseInt(text, 10) * (/k$/i.test(text) ? 1000 : 1) : 0
16  return tokens >= 1 ? { tokens } : { error: `"${text}" is not a number of tokens, use /sweet-spot later <tokens>, e.g. later 50k` }
17}
18
19// The debug line for a later handover that a shrunken context ended, at a pause or at the command alike.
20export const LATER_OVER = 'later: over, the context shrank below where it was asked'
21
22// The command at a known context: what the answer says, the later handover that holds afterwards, and the debug lines about it. A later handover the context has
23// shrunk below is over here too, as at a pause: a turn that ended without an answer reads the context again without a pause to see it.
24export const laterFor = (
25  config: Config,
26  window: number,
27  tokens: number,
28  current: Later | undefined,
29  n: number,
30): { later: Later | undefined; text: string; lines: string[] } => {
31  const kept = laterAt(current, tokens)
32  const lines = current !== undefined && kept === undefined ? [LATER_OVER] : []
33  const inForce = thresholdInForce(config.threshold, window, kept)
34  const threshold = effectiveThreshold(config.threshold, window)
35  const brake = brakeOf(threshold, window)
36  const context = `context ${tokens} tokens`
37  // Only ever later: a value at or below the one in force would bring the handover forward or change nothing.
38  if (tokens + n <= inForce)
39    return { later: kept, text: `already hands over at ${inForce} tokens, ${context}`, lines: [...lines, `later: turned down, not past ${inForce}`] }
40  // At the brake no later is left to give, and a command with no effect is turned down.
41  if (tokens >= brake)
42    return { later: kept, text: `already at the emergency brake, ${brake} tokens, ${context}`, lines: [...lines, 'later: turned down, at the emergency brake'] }
43  const until = tokens + n
44  const asked = { from: tokens, until }
45  const at = thresholdInForce(config.threshold, window, asked)
46  const capped = until > brake ? ', capped at the emergency brake' : ''
47  const handsOver = config.dryRun ? 'dry run, would hand over' : 'hands over'
48  return {
49    later: asked,
50    text: `${handsOver} at ${at} tokens instead of ${threshold}, for this handover only${capped}, ${context}`,
51    lines: [...lines, `later: from context ${tokens}, ${n} tokens, hands over at ${at}${capped}`],
52  }
53}
54
hooks/status.ts 44 lines
1// What `/sweet-spot status` says: where the context stands against the threshold and the emergency brake. Pure, and built from the same
2// functions as the handover, so that the answer and the behaviour cannot part.
3
4import type { Config } from './config'
5import { brakeFor, effectiveThreshold, thresholdInForce, type Later } from './decide'
6import { HOUR_MS, prepareDueAt } from './idle-handoff'
7
8// `later` is the one that still holds at this context: the caller has already looked at whether the context fell below where it was asked.
9// With no size read yet (just after a compact) the context part says so, and a `later` that was held stays, as nothing says it is over.
10export const statusFor = (config: Config, window: number, tokens: number | undefined, later: Later | undefined): string => {
11  const handover = thresholdInForce(config.threshold, window, later)
12  const at = later === undefined ? `${handover}` : `${handover} (later, threshold ${effectiveThreshold(config.threshold, window)})`
13  const context = tokens === undefined ? `context size unknown until the next answer (window ${window})` : `context ${tokens} of ${window} tokens`
14  return `${config.dryRun ? 'dry run, only reports: ' : ''}${context}, hands over at ${at}, emergency brake at ${brakeFor(config, window)}`
15}
16
17// Where the handoff after a long pause stands: planned with the time left until it is written, written and warm until a time of day the
18// caller gives as text, or written and cold.
19export type IdlePart = { kind: 'planned'; inMs: number } | { kind: 'ready'; until: string } | { kind: 'cold' }
20
21// The time of day in the process's own zone, as a clock shows it.
22const timeOfDay = (ms: number): string => {
23  const d = new Date(ms)
24  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
25}
26
27// Where the handoff after a long pause stands, from what the session keeps of it; nothing while none is planned or written.
28export const idlePart = (idle: { prepared?: unknown; timer?: unknown; touch?: number }, now: number): IdlePart | undefined => {
29  const { prepared, timer, touch } = idle
30  if (touch === undefined) return undefined
31  if (prepared !== undefined) return now - touch >= HOUR_MS ? { kind: 'cold' } : { kind: 'ready', until: timeOfDay(touch + HOUR_MS) }
32  return timer === undefined ? undefined : { kind: 'planned', inMs: prepareDueAt(touch) - now }
33}
34
35// What follows the status: `asap` first, since it acts at the next pause, and the handoff after a long pause, which waits for the next
36// message. Nothing of a part that does not hold.
37export const statusTail = (asap: boolean, idle: IdlePart | undefined): string => {
38  const parts = asap ? ['asap: hands over at the next pause'] : []
39  if (idle?.kind === 'planned') parts.push(`idle handoff ready in ${Math.max(1, Math.ceil(idle.inMs / 60_000))} min`)
40  else if (idle?.kind === 'ready') parts.push(`idle handoff ready, goes with your next message after ${idle.until}`)
41  else if (idle?.kind === 'cold') parts.push('idle handoff ready, goes with your next message')
42  return parts.map(p => `, ${p}`).join('')
43}
44
hooks/compact-check.ts 32 lines
1// Whether a compact brought the context under the threshold. A compact that did not is not repeated at every pause: it counts as a failed
2// way until a pause is below the threshold again. Pure, so that the table of moves is tested on its own.
3
4import type { Config, Method } from './config'
5
6// `pending`: a compact succeeded and no reading of the size has said yet whether it was enough. `insufficient`: it was not; `said` is whether the failure
7// that follows from it has been told to the person (once for each mark).
8export type CompactCheck = { kind: 'pending' } | { kind: 'insufficient'; said: boolean } | undefined
9
10// The mark after a reading of the size: the first tool call after the compact, or a pause. A reading with no size changes nothing: the host
11// reports none right after a compact, and a reading that cannot tell does not decide. A size at or above the threshold turns `pending` into
12// `insufficient`; one below it clears either.
13export const checkOf = (check: CompactCheck, tokens: number | undefined, threshold: number): CompactCheck => {
14  if (check === undefined || tokens === undefined) return check
15  if (tokens < threshold) return undefined
16  return check.kind === 'pending' ? { kind: 'insufficient', said: false } : check
17}
18
19// The debug line for what a reading of the size made of a compact still to be judged: enough, or not. None while it stays to be judged.
20export const judgedLine = (before: CompactCheck, after: CompactCheck, tokens: number | undefined): string | undefined => {
21  if (before?.kind !== 'pending' || after?.kind === 'pending') return undefined
22  return after === undefined ? `compact left ${tokens} tokens, below the threshold` : 'compact left the context above the threshold'
23}
24
25// The way that is tried first. A compact that was not enough is not tried: where it is the main method the fallback is the first, and
26// where there is none, there is no first way and the run fails at the mark. The fallback is what the run opens with, the compact is the
27// failure it falls back from.
28export const firstMethod = (config: Config, state: { compactCheck: CompactCheck }): Method | undefined => {
29  if (config.handoffMethod !== 'builtin-compact' || state.compactCheck?.kind !== 'insufficient') return config.handoffMethod
30  return config.handoffFallback === 'none' ? undefined : config.handoffFallback
31}
32
hooks/countdown.ts 130 lines
1// The countdown before an automatic handover: its deadline, the seconds left, what "Not now" moves the handover back by, and what the
2// band says. Pure, like `log.ts`: what reads the clock and draws the band hands the values in.
3
4import type { Config, Method } from './config'
5import { brakeFor, thresholdInForce, type Decision, type Snapshot } from './decide'
6
7// The deadline is a time, not a count of ticks: a tick that does not come cannot move it.
8export const deadlineOf = (now: number, seconds: number): number => now + seconds * 1000
9
10// A second that has begun is still shown, so the band reads 10 at the start and 1 in the last second.
11export const secondsLeft = (deadline: number, now: number): number => Math.max(0, Math.ceil((deadline - now) / 1000))
12
13// How far past its deadline the end of a countdown may read the clock and still hand over. Later than that, the machine most likely slept
14// or the timer stayed out, and the person, likely away, never saw the band; the countdown ends as it does for typing. An assumption, not
15// measured: neither what the host does while the machine sleeps nor how late a timer usually fires.
16export const LATE_MS = 3000
17
18export const isLate = (deadline: number, now: number): boolean => now - deadline > LATE_MS
19
20// What "Not now" moves the handover back by: `later_tokens`, or less where the emergency brake comes first, as `later` caps it there. The
21// button says the value that holds, not the setting, so it never promises more than the press gives.
22export type MoveBack = { tokens: number; toBrake: boolean }
23
24export const moveBack = (config: Config, window: number, tokens: number): MoveBack => {
25  const until = tokens + config.laterTokens
26  return { tokens: thresholdInForce(config.threshold, window, { from: tokens, until }) - tokens, toBrake: until > brakeFor(config, window) }
27}
28
29// Which countdown a pause past the threshold begins, or none (`immediate`). At or past the emergency brake nothing moves the handover back,
30// so there is no button: with no later handover set it goes at once, as it did before there was a countdown; with one set (capped at the
31// brake, or jumped past by the context) a countdown with no button announces it (`brake`), for whoever pressed Not now expects to be asked
32// again. Below the brake, two deferred pauses or more give the countdown that typing does not stop (`cap`): not just two, since a cap that
33// ended without a handover counts as well and leaves three. Otherwise the countdown with "Not now" (`button`). The setting of 0 and a
34// session with no screen are checked before.
35export type CountdownKind = 'button' | 'cap' | 'brake'
36
37export const kindAt = (s: Pick<Snapshot, 'tokens' | 'window' | 'later'>, config: Config, deferredPauses: number): CountdownKind | 'immediate' => {
38  if (s.tokens !== undefined && s.tokens >= brakeFor(config, s.window)) return s.later === undefined ? 'immediate' : 'brake'
39  return deferredPauses >= 2 ? 'cap' : 'button'
40}
41
42// How a countdown begins. `button` is the countdown with "Not now", which a person can answer, and what it moves the handover back by.
43// `cap` (at the cap of deferred pauses) and `brake` (at the emergency brake) have no button, and typing does not stop them. `threshold`
44// is the threshold in force, the brake for `brake`; `decision` is what the pause decided, which the end of the countdown carries out.
45export type Start = ({ kind: 'button'; moveBack: MoveBack } | { kind: 'cap' | 'brake' }) & {
46  // The way tried first, which the band names.
47  method: Method
48  decision: Extract<Decision, { kind: 'act' | 'dry-run' }>
49  threshold: number
50  // The standing tasks the handover does not wait for, by the words their rule hit: the band names them, so that a task taken for one by
51  // mistake shows before the handover, while "Not now" can still hold it. Never the command itself, which can carry a path or a token.
52  running?: readonly string[]
53}
54
55// All the band shows, since drawing waits on nothing (the clock is a wait): the start and the seconds that the start or the last tick
56// read off the clock.
57export type Band = Start & { shown: number }
58
59// A countdown in the mod's state. The band only draws it; what changes here changes on an event, or on a survey coming up in the band or
60// going, which only the drawing sees.
61export type Countdown = Band & {
62  deadline: number
63  // Whether a survey holds the band, as the drawing last reported it.
64  survey: boolean
65  // The time left, kept while a survey holds the countdown: no timer runs then, and when the survey goes the deadline is set again from it.
66  remaining: number | undefined
67  // Stops the countdown's timers: the deadline and the tick that redraws the band.
68  stop: () => void
69  // Starts them again towards the deadline, from `now`.
70  run: (now: number) => void
71}
72
73const SEP = ' · '
74
75// A standing task named in the band is cut to this many characters.
76const RUNNING_CHARS = 30
77
78const runningOf = (running: readonly string[]): string | undefined => {
79  const [only] = running
80  if (only === undefined) return undefined
81  if (running.length > 1) return `${running.length} tasks keep running`
82  return `${only.length > RUNNING_CHARS ? `${only.slice(0, RUNNING_CHARS - 1)}…` : only} keeps running`
83}
84
85// What the band says. `width` is the cells the band lays its tree out in (`bodyColumns`); a band too narrow for all of it drops what keeps
86// running first, then ` of <threshold>`, then the context, and always keeps the way with the seconds and the end: the button, or for a
87// countdown with none, what it is. `text` comes before the button, which the terminal draws with its hotkey in front (`1: Not now, +25000`).
88export const bandOf = (c: Band, width: number): { text: string; button: string | undefined } => {
89  const dry = c.decision.kind === 'dry-run'
90  const way =
91    c.method === 'builtin-compact' ? (dry ? 'Would compact' : 'Compacting') : dry ? 'Would hand over to a fresh session' : 'Handing over to a fresh session'
92  const head = `${way} in ${c.shown} s`
93  const button = c.kind === 'button' ? `Not now, +${c.moveBack.tokens}${c.moveBack.toBrake ? ' to the brake' : ''}` : undefined
94  const end = button !== undefined ? `${NOT_NOW_KEY}: ${button}` : c.kind === 'cap' ? 'your draft stays in the prompt' : 'emergency brake'
95  const context = `${SEP}context ${c.decision.tokens}`
96  const fits = (text: string) => text.length + end.length <= width
97  const running = runningOf(c.running ?? [])
98  const candidates = [
99    ...(running === undefined ? [] : [`${head}${context} of ${c.threshold}${SEP}${running}${SEP}`]),
100    `${head}${context} of ${c.threshold}${SEP}`,
101    `${head}${context}${SEP}`,
102  ]
103  const text = candidates.find(fits) ?? `${head}${SEP}`
104  return { text: button === undefined ? `${text}${end}` : text, button }
105}
106
107// The key that presses "Not now": a single digit, which the host takes from an empty prompt for a band button. The band is shared: another
108// mod's button with the same key takes it from this one or loses it to it ("the later wins", by the host's types; which one wins in a live
109// session is not measured). The countdown still ends by typing, and the command `later` moves the handover back without the key.
110export const NOT_NOW_KEY = '1'
111
112// One edit in the prompt, as `prompt.edit` brings it: the draft before, the span it replaces, what goes in, and the key that made it.
113export type Edit = { text: string; start: number; end: number; inputText: string; key?: { key: string; ctrl?: true; shift?: true; meta?: true } }
114
115// Whether an edit is typing, which ends a countdown with the button: it leaves text in the prompt, read without white space. An edit
116// that leaves the prompt empty is none, and neither is a bare move of the cursor in an empty prompt.
117//
118// The one exception is the key of "Not now" in an empty prompt while the band shows the button: the host raises it as an edit first (the
119// digit as `inputText`, an empty draft) and as the press about 0.4 s later, and the prompt stays empty (docs/host-behaviour.md, Commands).
120// That edit is the press's echo, not typing; the press itself moves the handover back. The event alone cannot tell, since its result reads
121// as the digit. Where the digit does land in the prompt (the button out of sight), the prompt is no longer empty and the next edit is
122// typing; where it lands without an edit, the end of the countdown reads the prompt.
123export const typed = (edit: Edit, buttonShown: boolean): boolean => {
124  const after = edit.text.slice(0, edit.start) + edit.inputText + edit.text.slice(edit.end)
125  return after.trim() !== '' && !isDigitEcho(edit, buttonShown)
126}
127
128const isDigitEcho = ({ key, text }: Edit, buttonShown: boolean): boolean =>
129  buttonShown && text === '' && key !== undefined && key.key === NOT_NOW_KEY && !key.ctrl && !key.shift && !key.meta
130
hooks/standing.ts 501 lines
1// Which background tasks never end by themselves: a dev server, a watcher, `tail -f`. Such a task is not work whose result anyone waits for, so
2// it does not hold a handover back. Pure, no `$`.
3//
4// The test is the meaning of the command, read word by word, never a substring: `npm run build:dev` and `cd packages/vite && npm test` are
5// not dev servers. Only what surely never ends is standing. A command that is not known, or that cannot be read (a subshell, `$(…)`, a
6// heredoc), is waited for as before: a wrong "standing" lets a result arrive in the fresh session, a wrong "not standing" only waits.
7
8import type { TaskSummary } from './pairing'
9
10export type Flag = { name: string; group?: true }
11
12// One row per rule. `command`: the command word, or two words (`docker compose`). `sub`: one of these must follow the command at once, with
13// no flag between. `optionalSub`: the rule holds without a word after the command; one of these right after it joins the words shown.
14// `notSub`: such a word anywhere in the command, not a flag, makes it end. `needs`: one of these flags must be there. `endsWith`: one of these
15// makes it end. `noWordAfterSub`: a word right after the subcommand makes it end (`jupyter server list`). `part`: the words shown, from the
16// rule's own words; a hit flag is shown without its value.
17export type Rule = {
18  key: string
19  command: string[]
20  sub?: string[]
21  optionalSub?: string[]
22  notSub?: string[]
23  needs?: Flag[]
24  endsWith?: Flag[]
25  noWordAfterSub?: true
26  part: 'command' | 'command sub' | 'command flag' | 'command sub flag'
27}
28
29const f = (name: string): Flag => ({ name })
30const g = (name: string): Flag => ({ name, group: true })
31
32export const RULES: readonly Rule[] = [
33  { key: 'vite', command: ['vite'], optionalSub: ['dev', 'serve', 'preview'], notSub: ['build', 'optimize'], part: 'command sub' },
34  { key: 'parcel', command: ['parcel'], optionalSub: ['serve', 'watch'], notSub: ['build'], part: 'command sub' },
35  { key: 'next', command: ['next'], sub: ['dev', 'start'], part: 'command sub' },
36  { key: 'nuxt', command: ['nuxt', 'nuxi', 'astro'], sub: ['dev', 'preview'], part: 'command sub' },
37  { key: 'remix', command: ['remix', 'wrangler', 'netlify', 'vercel'], sub: ['dev'], part: 'command sub' },
38  { key: 'gatsby', command: ['gatsby'], sub: ['develop', 'serve'], part: 'command sub' },
39  { key: 'docusaurus', command: ['docusaurus'], sub: ['start', 'serve'], part: 'command sub' },
40  { key: 'ng', command: ['ng', 'vue-cli-service', 'jekyll', 'mkdocs'], sub: ['serve'], part: 'command sub' },
41  // `--smoke-test` starts it and ends.
42  { key: 'storybook', command: ['storybook'], sub: ['dev'], endsWith: [f('--smoke-test')], part: 'command sub' },
43  { key: 'start-storybook', command: ['start-storybook'], endsWith: [f('--smoke-test')], part: 'command' },
44  { key: 'hugo', command: ['hugo'], sub: ['server'], part: 'command sub' },
45  { key: 'expo', command: ['expo', 'react-native', 'react-scripts'], sub: ['start'], part: 'command sub' },
46  { key: 'webpack serve', command: ['webpack'], sub: ['serve'], part: 'command sub' },
47  { key: 'webpack watch', command: ['webpack'], needs: [f('-w'), f('--watch')], part: 'command flag' },
48  {
49    key: 'servers',
50    command: [
51      'webpack-dev-server',
52      'http-server',
53      'live-server',
54      'serve',
55      'uvicorn',
56      'hypercorn',
57      'puma',
58      'daphne',
59      'nodemon',
60      'ts-node-dev',
61      'watchexec',
62      'memcached',
63    ],
64    part: 'command',
65  },
66  { key: 'gunicorn', command: ['gunicorn'], endsWith: [f('--check-config')], part: 'command' },
67  { key: 'redis-server', command: ['redis-server'], endsWith: [f('--test-memory')], part: 'command' },
68  { key: 'mongod', command: ['mongod'], endsWith: [f('--repair'), f('--shutdown')], part: 'command' },
69  { key: 'python http.server', command: ['python', 'python3', 'python3.N'], sub: ['-m http.server'], part: 'command sub' },
70  { key: 'python runserver', command: ['python', 'python3', 'python3.N'], sub: ['manage.py runserver'], part: 'command sub' },
71  { key: 'flask', command: ['flask', 'streamlit'], sub: ['run'], part: 'command sub' },
72  { key: 'rails', command: ['rails'], sub: ['s', 'server'], part: 'command sub' },
73  { key: 'php -S', command: ['php'], sub: ['-S'], part: 'command sub' },
74  { key: 'php artisan', command: ['php'], sub: ['artisan serve'], part: 'command sub' },
75  { key: 'mix', command: ['mix'], sub: ['phx.server'], part: 'command sub' },
76  { key: 'browser-sync', command: ['browser-sync'], sub: ['start'], part: 'command sub' },
77  { key: 'mlflow', command: ['mlflow'], sub: ['ui', 'server'], part: 'command sub' },
78  { key: 'tensorboard', command: ['tensorboard'], needs: [f('--logdir')], part: 'command flag' },
79  {
80    key: 'jupyter',
81    command: ['jupyter'],
82    sub: ['lab', 'notebook', 'server'],
83    noWordAfterSub: true,
84    endsWith: [f('--generate-config')],
85    part: 'command sub',
86  },
87  { key: 'tsc', command: ['tsc'], needs: [f('-w'), f('--watch')], part: 'command flag' },
88  { key: 'vitest sub', command: ['vitest'], sub: ['watch', 'dev'], part: 'command sub' },
89  { key: 'vitest --watch', command: ['vitest'], needs: [f('--watch')], part: 'command flag' },
90  { key: 'jest', command: ['jest'], needs: [f('--watch'), f('--watchAll')], part: 'command flag' },
91  { key: 'node --watch', command: ['node', 'bun', 'deno'], needs: [f('--watch')], part: 'command flag' },
92  { key: 'tsx watch', command: ['tsx', 'cargo', 'dotnet'], sub: ['watch'], part: 'command sub' },
93  { key: 'compose watch', command: ['docker compose', 'docker-compose'], sub: ['watch'], part: 'command sub' },
94  {
95    key: 'compose up',
96    command: ['docker compose', 'docker-compose'],
97    sub: ['up'],
98    endsWith: [g('-d'), f('--detach'), f('--wait'), f('--abort-on-container-exit'), f('--exit-code-from'), f('--no-start')],
99    part: 'command sub',
100  },
101  { key: 'ngrok', command: ['ngrok'], sub: ['http', 'tcp', 'tls', 'start'], part: 'command sub' },
102  { key: 'cloudflared run', command: ['cloudflared'], sub: ['tunnel run'], part: 'command sub' },
103  { key: 'cloudflared --url', command: ['cloudflared'], sub: ['tunnel'], needs: [f('--url')], part: 'command sub flag' },
104  { key: 'kubectl', command: ['kubectl'], sub: ['port-forward', 'proxy'], part: 'command sub' },
105  { key: 'minikube', command: ['minikube'], sub: ['tunnel'], part: 'command sub' },
106  // `-f` sends ssh to the background by itself, and the task ends at once.
107  { key: 'ssh', command: ['ssh'], needs: [g('-N')], endsWith: [g('-f')], part: 'command flag' },
108  // With `--pid` it ends with that process.
109  { key: 'tail', command: ['tail'], needs: [g('-f'), g('-F'), f('--follow')], endsWith: [f('--pid')], part: 'command flag' },
110  { key: 'journalctl', command: ['journalctl'], needs: [g('-f'), f('--follow')], part: 'command flag' },
111  { key: 'minio', command: ['minio'], sub: ['server'], part: 'command sub' },
112  { key: 'ollama', command: ['ollama'], sub: ['serve'], part: 'command sub' },
113  { key: 'sleep', command: ['sleep'], sub: ['infinity'], part: 'command sub' },
114]
115
116// The script names and monorepo task names that start a server. Not `watch` nor `:watch`: such a script often runs a test runner without a
117// watch flag (`"test:watch": "vitest"`), and with no terminal that runs once and ends. No prefix either: `dev:seed` ends.
118const SCRIPTS = new Set(['dev', 'serve', 'preview', 'start', 'storybook'])
119
120// Package manager flags passed over before the script name. Any other flag there leaves the command unknown, and it is waited for.
121// `-w` takes a value for npm only (`--workspace`); for pnpm it is `--workspace-root`, with none.
122export const VALUE_FLAGS = ['--prefix', '-C', '--dir', '--cwd', '--filter', '-F', '--workspace', '-w', '--loglevel'] as const
123export const PLAIN_FLAGS = ['-r', '--recursive', '--parallel', '--stream', '-s', '--silent', '--workspaces', '-ws', '--if-present'] as const
124
125export const RUNNERS = ['turbo', 'nx', 'nx run', 'nx run-many', 'lerna'] as const
126
127export type Hit = { key: string; part: string }
128
129// A quoted text stands in its word between two of these marks: `PORT="3000"` stays an assignment, a word with a quote in it is never a
130// command word, and `plain` still finds a word that ends a command when it comes quoted (`vite "build"`).
131const QUOTED = '\u0000'
132
133type Token = { word: string } | { op: '&&' | '||' | '|' | '|&' | ';' | '&' | '\n' }
134
135// The words and operators of a command line, or `undefined` for one that cannot be read safely: `$(…)`, a backtick, a heredoc, a quote that
136// is escaped or never closed, a subshell or a group. Redirections and their targets are dropped, so `2>&1` and `&>` are no `&`, and so is a
137// comment.
138const tokens = (line: string): Token[] | undefined => {
139  const out: Token[] = []
140  let word = ''
141  let inWord = false
142  let target = false
143  const push = () => {
144    if (!inWord) return
145    if (target) target = false
146    else out.push({ word })
147    word = ''
148    inWord = false
149  }
150  const op = (o: Exclude<Token, { word: string }>['op']) => {
151    push()
152    const last = out[out.length - 1]
153    // A line break right after an operator goes on with the same line: after `|` or `&&` the command is not over, after `;` it already is.
154    if (o === '\n' && (last === undefined || 'op' in last)) return
155    out.push({ op: o })
156  }
157  for (let i = 0; i < line.length; i++) {
158    const c = line[i]
159    const next = line[i + 1]
160    if (c === ' ' || c === '\t') push()
161    else if (c === '\\') {
162      if (next === '\n') {
163        push()
164        i++
165      } else if (next === '"' || next === "'") return undefined
166      else {
167        word += c + (next ?? '')
168        inWord = true
169        i++
170      }
171    } else if (c === "'") {
172      const end = line.indexOf("'", i + 1)
173      if (end < 0) return undefined
174      word += QUOTED + line.slice(i + 1, end) + QUOTED
175      inWord = true
176      i = end
177    } else if (c === '"') {
178      let j = i + 1
179      for (; j < line.length && line[j] !== '"'; j++) {
180        if (line[j] === '\\') {
181          if (line[j + 1] === '"') return undefined
182          j++
183        } else if (line[j] === '`' || (line[j] === '$' && line[j + 1] === '(')) return undefined
184      }
185      if (j >= line.length) return undefined
186      word += QUOTED + line.slice(i + 1, j) + QUOTED
187      inWord = true
188      i = j
189    } else if (c === '`') return undefined
190    // A comment runs to the end of the line, and the shell does not read it.
191    else if (c === '#' && !inWord) {
192      const end = line.indexOf('\n', i)
193      i = (end < 0 ? line.length : end) - 1
194    } else if (c === '\n') op('\n')
195    // A subshell, and with it `$(…)`.
196    else if (c === '(' || c === ')') return undefined
197    else if ((c === '{' || c === '}') && !inWord) return undefined
198    else if (c === '>' || c === '<' || (c === '&' && next === '>')) {
199      if (c === '<' && next === '<') return undefined
200      // A file descriptor written against the operator (`2>`) belongs to it.
201      if (inWord && /^\d+$/.test(word)) {
202        word = ''
203        inWord = false
204      } else push()
205      let j = i + 1
206      if (c === '&') j++
207      if (line[j] === '>' || line[j] === '|') j++
208      if (line[j] === '&') {
209        j++
210        // `>&1`, `>&-`: a descriptor, no file follows. `>& file` sends both to a file.
211        if (/[\d-]/.test(line[j] ?? '')) {
212          while (/[\d-]/.test(line[j] ?? '')) j++
213          i = j - 1
214          continue
215        }
216      }
217      i = j - 1
218      target = true
219    } else if (c === '|') {
220      if (next === '|') {
221        op('||')
222        i++
223      } else if (next === '&') {
224        op('|&')
225        i++
226      } else op('|')
227    } else if (c === '&') {
228      if (next === '&') {
229        op('&&')
230        i++
231      } else op('&')
232    } else if (c === ';') op(';')
233    else {
234      word += c
235      inWord = true
236    }
237  }
238  push()
239  if (target) return undefined
240  return out
241}
242
243// A word as the shell gives it to the command, with its quotes taken off.
244const plain = (word: string): string => word.replaceAll(QUOTED, '')
245
246// A word that is a variable the shell splits (`$FLAGS`, `${OPTS}`) can be any words, a flag that ends the command too.
247const expanded = (word: string): boolean => word.startsWith('$')
248
249// Shell words that open a construct whose body the mod does not read.
250const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'fi', 'for', 'while', 'until', 'do', 'done', 'case', 'esac', 'select', 'function'])
251
252// The words of a command after the prefixes that only change how it runs, with a path taken off the command word; `undefined` when what is
253// left cannot be a command.
254const unprefixed = (words: readonly string[]): string[] | undefined => {
255  let w = [...words]
256  const assignment = (s: string) => /^[A-Za-z_][A-Za-z0-9_]*=/.test(s)
257  for (;;) {
258    const head = w[0]
259    if (head === undefined) return undefined
260    if (assignment(head)) w = w.slice(1)
261    else if (head === 'env' || head === 'cross-env') {
262      w = w.slice(1)
263      while (w[0] !== undefined && (assignment(w[0]) || (head === 'env' && w[0].startsWith('-')))) w = w.slice(w[0] === '-u' ? 2 : 1)
264    } else if (['nohup', 'exec', 'setsid', 'command', 'time', 'pnpx', 'bunx'].includes(head)) w = w.slice(1)
265    else if (head === 'sudo') {
266      w = w.slice(1)
267      while (w[0]?.startsWith('-')) w = w.slice(w[0] === '-u' || w[0] === '-g' ? 2 : 1)
268    } else if (head === 'nice') {
269      w = w.slice(1)
270      if (w[0] === '-n') w = w.slice(2)
271      else if (/^-\d+$/.test(w[0] ?? '')) w = w.slice(1)
272    } else if (head === 'caffeinate') {
273      w = w.slice(1)
274      while (w[0]?.startsWith('-')) w = w.slice(w[0] === '-t' || w[0] === '-w' ? 2 : 1)
275    } else if (head === 'npx') {
276      w = w.slice(1)
277      while (w[0] === '-y' || w[0] === '--yes') w = w.slice(1)
278    } else if ((head === 'pnpm' && (w[1] === 'exec' || w[1] === 'dlx')) || (head === 'yarn' && w[1] === 'dlx')) w = w.slice(2)
279    else break
280  }
281  const head = w[0]
282  if (head === undefined || head.includes(QUOTED)) return undefined
283  const command = head.slice(head.lastIndexOf('/') + 1)
284  return command === '' ? undefined : [command, ...w.slice(1)]
285}
286
287// A flag in a word: the word itself, the word with a value after `=`, or a letter in a group of short flags (`-fn`, `-NL`).
288const flagIn = (word: string, flag: Flag): string | undefined => {
289  if (word === flag.name || word.startsWith(`${flag.name}=`)) return flag.name
290  const letter = flag.name.length === 2 ? flag.name[1] : undefined
291  if (flag.group && letter !== undefined && /^-[A-Za-z]+$/.test(word) && word.slice(1).includes(letter)) return flag.name
292  return undefined
293}
294
295const firstFlag = (words: readonly string[], flags: readonly Flag[]): string | undefined => {
296  for (const word of words) {
297    for (const flag of flags) {
298      const hit = flagIn(word, flag)
299      if (hit !== undefined) return hit
300    }
301  }
302  return undefined
303}
304
305const named = (word: string, name: string) => word === name || (name === 'python3.N' && /^python3\.\d+$/.test(word))
306
307const ruleHit = (rule: Rule, words: readonly string[]): Hit | undefined => {
308  for (const name of rule.command) {
309    const parts = name.split(' ')
310    if (!parts.every((p, i) => words[i] !== undefined && named(words[i], p))) continue
311    const command = [words[0], ...parts.slice(1)].join(' ')
312    const rest = words.slice(parts.length)
313    let sub: string | undefined
314    let afterSub = rest
315    if (rule.sub !== undefined) {
316      sub = rule.sub.find(s => s.split(' ').every((p, i) => rest[i] === p))
317      if (sub === undefined) continue
318      afterSub = rest.slice(sub.split(' ').length)
319      if (rule.noWordAfterSub && afterSub[0] !== undefined && !afterSub[0].startsWith('-')) continue
320    } else if (rule.optionalSub !== undefined && rest[0] !== undefined && rule.optionalSub.includes(rest[0])) sub = rest[0]
321    if ((rule.notSub !== undefined || rule.endsWith !== undefined) && rest.some(expanded)) continue
322    if (rule.notSub?.some(s => rest.some(w => plain(w) === s))) continue
323    if (rule.endsWith !== undefined && firstFlag(rest.map(plain), rule.endsWith) !== undefined) continue
324    const flag = rule.needs === undefined ? undefined : firstFlag(afterSub, rule.needs)
325    if (rule.needs !== undefined && flag === undefined) continue
326    const part = [command, rule.part.includes('sub') ? sub : undefined, rule.part.includes('flag') ? flag : undefined]
327    return { key: rule.key, part: part.filter(p => p !== undefined).join(' ') }
328  }
329  return undefined
330}
331
332// The words after the package manager flags of the table, or `undefined` at a flag outside it. The key is the last flag passed over.
333const pastFlags = (tool: string, words: readonly string[]): { rest: string[]; flag: string | undefined } | undefined => {
334  let w = [...words]
335  let flag: string | undefined
336  while (w[0]?.startsWith('-')) {
337    const word = w[0]
338    if (word === '-w' && tool !== 'npm') {
339      if (tool !== 'pnpm') return undefined
340      flag = word
341      w = w.slice(1)
342      continue
343    }
344    const valued = VALUE_FLAGS.find(v => word === v || word.startsWith(`${v}=`))
345    if (valued !== undefined) {
346      flag = valued
347      w = w.slice(word === valued ? 2 : 1)
348    } else if ((PLAIN_FLAGS as readonly string[]).includes(word)) {
349      flag = word
350      w = w.slice(1)
351    } else return undefined
352  }
353  return { rest: w, flag }
354}
355
356// `npm run dev`, `pnpm --filter web dev`, `yarn workspace web run dev`: the package manager, `run` if it is there, the script name.
357const scriptHit = (words: readonly string[]): Hit | undefined => {
358  const manager = words[0]
359  let seen = pastFlags(manager ?? '', words.slice(1))
360  if (seen === undefined) return undefined
361  let key = seen.flag
362  let rest = seen.rest
363  if (manager === 'yarn' && rest[0] === 'workspace') rest = rest.slice(2)
364  let run = false
365  if (rest[0] === 'run') {
366    run = true
367    seen = pastFlags(manager ?? '', rest.slice(1))
368    if (seen === undefined) return undefined
369    key = seen.flag ?? key
370    rest = seen.rest
371  } else if (manager === 'npm' && rest[0] !== 'start') return undefined
372  else if (manager === 'bun') return undefined
373  const script = rest[0]
374  if (script === undefined || !SCRIPTS.has(script)) return undefined
375  return { key: key ?? 'script', part: [manager, run ? 'run' : undefined, script].filter(p => p !== undefined).join(' ') }
376}
377
378// `turbo [run] dev`, `nx serve web`, `nx run web:serve`, `nx run-many -t serve`, `lerna run dev`. Only the first task counts.
379const runnerHit = (words: readonly string[]): Hit | undefined => {
380  const [runner] = words
381  if (runner === 'turbo') {
382    const seen = pastFlags(runner, words.slice(1))
383    if (seen === undefined) return undefined
384    const run = seen.rest[0] === 'run'
385    const task = seen.rest[run ? 1 : 0]
386    return task !== undefined && SCRIPTS.has(task) ? { key: 'turbo', part: run ? `turbo run ${task}` : `turbo ${task}` } : undefined
387  }
388  if (runner === 'nx') {
389    if (words[1] === 'run') {
390      const task = words[2]?.split(':')[1]
391      return task !== undefined && SCRIPTS.has(task) ? { key: 'nx run', part: `nx run ${task}` } : undefined
392    }
393    if (words[1] === 'run-many') {
394      for (let i = 2; i < words.length; i++) {
395        const word = words[i] ?? ''
396        const inline = /^--targets?=(.*)$/.exec(word)
397        const list = inline !== null ? inline[1] : word === '-t' || word === '--target' || word === '--targets' ? words[i + 1] : undefined
398        if (list === undefined) continue
399        const task = list.split(',')[0] ?? ''
400        return SCRIPTS.has(task) ? { key: 'nx run-many', part: `nx run-many ${task}` } : undefined
401      }
402      return undefined
403    }
404    const task = words[1]
405    return task !== undefined && SCRIPTS.has(task) ? { key: 'nx', part: `nx ${task}` } : undefined
406  }
407  if (runner === 'lerna' && words[1] === 'run') {
408    const task = words[2]
409    return task !== undefined && SCRIPTS.has(task) ? { key: 'lerna', part: `lerna run ${task}` } : undefined
410  }
411  return undefined
412}
413
414// One command of a pipeline.
415const commandHit = (raw: readonly string[]): Hit | undefined => {
416  if (raw.some(w => ['--help', '-h', '--version'].includes(plain(w)))) return undefined
417  // A flag set to `false` is a flag not set.
418  const words = unprefixed(raw.filter(w => !/^--?[^=]+=false$/.test(plain(w))))
419  if (words === undefined) return undefined
420  const [command] = words
421  if (command === 'npm' || command === 'pnpm' || command === 'yarn' || command === 'bun') {
422    const hit = scriptHit(words)
423    // `bun --watch` is a watcher, not a script.
424    if (hit !== undefined || command !== 'bun') return hit
425  }
426  if (command === 'turbo' || command === 'nx' || command === 'lerna') return runnerHit(words)
427  for (const rule of RULES) {
428    const hit = ruleHit(rule, words)
429    if (hit !== undefined) return hit
430  }
431  return undefined
432}
433
434// A later stage of a pipeline that hands every line on and ends only when its input does. `grep` with a flag that stops early (`-m1`, `-q`)
435// ends the pipeline at the first match.
436const passesOn = (stage: readonly string[]): boolean => {
437  const command = stage[0]?.slice(stage[0].lastIndexOf('/') + 1)
438  if (command === 'tee' || command === 'cat' || command === 'ts') return true
439  if (command !== 'grep' && command !== 'rg') return false
440  return !stage.slice(1).some(word => {
441    if (expanded(word)) return true
442    const w = plain(word)
443    if (/^--(max-count|quiet|silent|files-with-matches|files-without-match)(=|$)/.test(w)) return true
444    const letters = /^-([A-Za-z]+)/.exec(w)
445    return letters !== null && !w.startsWith('--') && /[mqlL]/.test(letters[1] ?? '')
446  })
447}
448
449// The host cuts a long command and says so at its end. Only the part shown is read, and of that not the pipeline the cut ran through.
450const CUT = /\.\.\. \[\+\d+ chars\]$/
451
452// One shell around the whole command (`bash -c "…"`, `sh -lc '…'`) is read inside. A second one inside, or a shell behind a prefix or
453// before a redirection, is not.
454const SHELL = /^(?:bash|sh|zsh) +-l?c +(?:'([^']*)'|"((?:[^"\\]|\\.)*)") *$/
455
456export const standingHit = (command: string): Hit | undefined => {
457  const cut = CUT.test(command.trim())
458  let line = command.trim().replace(CUT, '')
459  const shell = SHELL.exec(line)
460  if (shell !== null) line = shell[1] ?? shell[2] ?? ''
461  const all = tokens(line)
462  if (all === undefined) return undefined
463  // Lists end at `;`, a line break or `&`; a list that ends in `&` runs in the background and holds nothing open.
464  const lists: { pipelines: string[][][]; background: boolean }[] = []
465  let stage: string[] = []
466  let pipeline: string[][] = [stage]
467  let pipelines: string[][][] = [pipeline]
468  for (const t of all) {
469    if ('word' in t) stage.push(t.word)
470    else if (t.op === '|' || t.op === '|&') pipeline.push((stage = []))
471    else if (t.op === '&&' || t.op === '||') pipelines.push((pipeline = [(stage = [])]))
472    else {
473      lists.push({ pipelines, background: t.op === '&' })
474      pipelines = [(pipeline = [(stage = [])])]
475    }
476  }
477  lists.push({ pipelines, background: false })
478  // What the cut took off belongs to the last pipeline, and can end it (`| grep -m1`, `-d`, `build`, `dev` of `dev:seed`): it is not read.
479  if (cut) pipelines.pop()
480  for (const pipeline of lists.flatMap(l => l.pipelines)) {
481    for (const stage of pipeline) if (stage[0] !== undefined && KEYWORDS.has(stage[0])) return undefined
482  }
483  for (const list of lists) {
484    if (list.background) continue
485    for (const pipeline of list.pipelines) {
486      for (const [i, stage] of pipeline.entries()) {
487        const hit = commandHit(stage)
488        if (hit !== undefined && pipeline.slice(i + 1).every(passesOn)) return hit
489      }
490    }
491  }
492  return undefined
493}
494
495// The words of the command that the rule hit, for the person to see: never a path, a prefix, a value or a redirection.
496export const standingPart = (command: string): string | undefined => standingHit(command)?.part
497
498export const standingCommand = (command: string): boolean => standingPart(command) !== undefined
499
500export const standing = (t: TaskSummary): boolean => t.type === 'shell' && t.command !== undefined && standingCommand(t.command)
501
hooks/countdown-flow.ts 234 lines
1// The countdown as it runs: it begins at a pause, ticks the band, and runs out into the handover, unless "Not now" moves the handover
2// back first. The countdown lives in the mod's state, not in the band, which only draws it.
3
4import { deadlineOf, isLate, secondsLeft, type Countdown, type Start } from './countdown'
5import type { Decision, Snapshot } from './decide'
6import type { Level } from './log'
7import { decidedOf } from './report'
8import type { State } from './state'
9
10// What the countdown asks of the session. As with `Io` in `relay.ts`, the host follows `$` only into functions of the file that declares
11// `register`, so the calls on `$` are made there and this module gets them as functions.
12export type CountdownIo = {
13  now: () => Promise<number>
14  after: (ms: number, fn: () => void) => { cancel: () => void }
15  // The tick that redraws the band; the deadline does not hang on it.
16  every: (ms: number, fn: () => void) => { cancel: () => void }
17  surfaces: () => Promise<readonly string[]>
18  // What the prompt holds.
19  prompt: () => Promise<string>
20  // Draws the band again.
21  redraw: () => void
22  toast: (text: string) => void
23  log: (level: Exclude<Level, 'off'>, text: string) => void
24}
25
26// What the command or a press of "Not now" answers, and the diagnostic lines about it, which the handler writes after its read of the log
27// level. A line never holds what was typed.
28export type Answer = { text: string; lines?: [Exclude<Level, 'off'>, string][] }
29
30// The band is drawn on these surfaces only; a session with none of them (VS Code, mobile, a headless run) would count down unseen.
31const DRAWN_ON = ['terminal', 'desktop']
32
33const TICK_MS = 1000
34
35// What the end of a countdown needs: the session read again for a fresh judgment (all of the snapshot but the time, which the end reads
36// last), the judgment, the handover it carries out, with the time and the turn count it was judged at, and the message for a handover
37// postponed, said as at a pause.
38export type Expiry = {
39  look: () => Promise<Omit<Snapshot, 'now'>>
40  judge: (snapshot: Snapshot) => Decision
41  carry: (decision: Countdown['decision'], now: number, turns: number) => void
42  postpone: (decision: Extract<Decision, { kind: 'defer' }>) => void
43}
44
45// Begins a countdown of `seconds` that ends in `expiry`. False where nobody would see the band: the caller hands over at once, as without a
46// countdown. Where the surfaces are is read at each start, not once per session.
47//
48// The countdown with the button does not begin over a draft in the prompt: the handover waits for the next pause. Such a pause counts as
49// deferred, and so does one whose countdown begins, until a handover begins; two of them give the countdown that typing does not stop
50// (`kindAt`), so that whoever types at every pause is not pushed to the emergency brake, which does not wait for running work. That one and
51// the countdown at the brake hand over with a draft, which stays in the prompt.
52//
53// A pause while a countdown runs (a second stop of the same answer, with no turn between) leaves it as it is: begun again, its deadline
54// would move back at each such stop, and its end judges afresh anyway.
55export const begin = async (io: CountdownIo, state: State, seconds: number, start: Start, expiry: Expiry): Promise<boolean> => {
56  if (state.countdown !== undefined) {
57    io.log('debug', 'countdown: runs already')
58    return true
59  }
60  const surfaces = await io.surfaces()
61  if (!surfaces.some(s => DRAWN_ON.includes(s))) {
62    io.log('debug', 'countdown: none, no screen draws the band')
63    return false
64  }
65  const draft = start.kind === 'button' && (await io.prompt()).trim() !== ''
66  const now = await io.now()
67  // Begun meanwhile by a second stop, which read the session after this one: that one stands.
68  if (state.countdown !== undefined) return true
69  const before = state.deferred?.pauses ?? 0
70  state.deferred = { pauses: before + 1, from: state.deferred?.from ?? start.decision.tokens }
71  if (draft) {
72    io.log('debug', `countdown: none, a draft waits in the prompt, deferred pauses ${before}`)
73    return true
74  }
75  const deadline = deadlineOf(now, seconds)
76  let timers: { cancel: () => void }[] = []
77  const countdown: Countdown = {
78    ...start,
79    deadline,
80    shown: secondsLeft(deadline, now),
81    survey: false,
82    remaining: undefined,
83    stop: () => {
84      timers.forEach(t => t.cancel())
85      timers = []
86    },
87    run: from => {
88      timers = [
89        io.after(Math.max(0, countdown.deadline - from), () => void runOut(io, state, countdown, expiry)),
90        io.every(TICK_MS, () => void tick(io, state, countdown)),
91      ]
92    },
93  }
94  state.countdown = countdown
95  countdown.run(now)
96  io.log('info', `countdown: starts, ${seconds} s, method ${countdown.method}, kind ${countdown.kind}, deferred pauses ${before}`)
97  // The announcement at the brake comes once: it spends the later handover as it begins, and if it ends without a handover the next pause
98  // at the brake hands over at once.
99  if (countdown.kind === 'brake' && state.later !== undefined) {
100    state.later = undefined
101    io.log('debug', 'later: spent by the countdown at the emergency brake')
102  }
103  io.redraw()
104  return true
105}
106
107// Why a countdown ended without a handover: typing (`edit`), a submit, a turn, the command `later` or `asap`, the end of the session, a
108// compact the mod did not start, text in the prompt when it ran out (`prompt`), or a clock that ran out long past the deadline (`late`).
109export type EndReason = 'edit' | 'submit' | 'turn' | 'command' | 'session' | 'compact' | 'prompt' | 'late'
110
111// The diagnostic line for it, which a handler writes after its read of the log level.
112export const endedLine = (reason: EndReason) => `countdown: ended, ${reason}`
113
114// Ends the running countdown without a handover and takes the band down; false when none runs. Synchronous, so that a handler ends it
115// before its first wait: the end of the countdown checks after each of its own waits that it still runs.
116export const end = (io: CountdownIo, state: State): boolean => {
117  const countdown = state.countdown
118  if (countdown === undefined) return false
119  countdown.stop()
120  state.countdown = undefined
121  io.redraw()
122  return true
123}
124
125// A survey came up in the band or went, which only the drawing sees (`hasSurvey`). Each draw reports it and only a change is taken up: a
126// change redraws, which a report that changes nothing must not do, and the band draws at every tick. It writes the mod's own state, not
127// `$.state`, which the host refuses while a render hook draws, and does not wait: the clock is read afterwards, in `settle`.
128//
129// A survey holds the countdown: no time counts while it shows, and when it goes the countdown goes on with the time it had left. The band
130// yields to it meanwhile, so the button is gone and its key no press: it is typed, as any key.
131export const surveyed = (io: CountdownIo, state: State, survey: boolean): void => {
132  const countdown = state.countdown
133  if (countdown === undefined || countdown.survey === survey) return
134  countdown.survey = survey
135  void settle(io, state, countdown)
136}
137
138// Brings the countdown in line with the survey, whatever else came first: a survey that went before its clock was read leaves the
139// countdown running as it was. A clock that cannot be read ends it, as at the end of a countdown, rather than leave one that counts beneath
140// a survey or one held for good.
141const settle = async (io: CountdownIo, state: State, countdown: Countdown) => {
142  let now: number
143  try {
144    now = await io.now()
145  } catch {
146    if (state.countdown !== countdown) return
147    end(io, state)
148    io.log('warn', 'countdown: could not read the clock at a survey')
149    return
150  }
151  if (state.countdown !== countdown) return
152  if (countdown.survey && countdown.remaining === undefined) {
153    countdown.stop()
154    countdown.remaining = Math.max(0, countdown.deadline - now)
155    io.log('debug', `countdown: held, survey, ${secondsLeft(countdown.deadline, now)} s left`)
156    io.redraw()
157  } else if (!countdown.survey && countdown.remaining !== undefined) {
158    countdown.deadline = now + countdown.remaining
159    countdown.remaining = undefined
160    countdown.shown = secondsLeft(countdown.deadline, now)
161    countdown.run(now)
162    io.log('debug', `countdown: goes on, survey gone, ${countdown.shown} s left`)
163    io.redraw()
164  }
165}
166
167// Each act checks after its wait that the countdown it belongs to still runs: one that ended or was replaced meanwhile is left alone.
168const tick = async (io: CountdownIo, state: State, countdown: Countdown) => {
169  const now = await io.now()
170  if (state.countdown !== countdown) return
171  countdown.shown = secondsLeft(countdown.deadline, now)
172  io.redraw()
173}
174
175// The end is not one step: it waits on the prompt, the session and the clock, and anything that ends the countdown meanwhile (typing, a
176// submit, a turn, `later`, `asap`) ends it synchronously, before its own first wait. So the check that this countdown still runs comes after the
177// last wait, and the handover is set going in the same step (`carry` sets `handingOver`); a countdown gone by then is left alone.
178//
179// A survey that came up meanwhile holds the countdown here as well: it is left as it is, and its deadline, by then reached, runs out again
180// when the survey goes.
181const runOut = async (io: CountdownIo, state: State, countdown: Countdown, expiry: Expiry) => {
182  const stands = () => state.countdown === countdown && !countdown.survey
183  let read: { draft: string; seen: Omit<Snapshot, 'now'>; now: number }
184  try {
185    // The countdown with the button began with an empty prompt: text there now came by a way that raises no edit (the history, Tab on a
186    // suggestion, another mod's `$.prompt.fill`). The other two hand over with a draft, which stays in the prompt.
187    const draft = countdown.kind === 'button' ? await io.prompt() : ''
188    const seen = await expiry.look()
189    read = { draft, seen, now: await io.now() }
190  } catch {
191    if (!stands()) return
192    end(io, state)
193    io.log('warn', 'countdown: could not read the session when it ran out')
194    return
195  }
196  if (!stands()) return
197  end(io, state)
198  const { draft, seen, now } = read
199  const reason = draft.trim() !== '' ? 'prompt' : isLate(countdown.deadline, now) ? 'late' : undefined
200  if (reason !== undefined) {
201    io.log('debug', endedLine(reason))
202    return
203  }
204  // Judged afresh: the context may no longer be past the threshold, or a subagent may run (one past the brake hands over all the same, as
205  // at a pause). Background tasks and one-shot timers are not read again: the stop that ended the answer reported them, and they change
206  // only in a turn, which ends the countdown. A turn holds the handover at any countdown, also the one at the brake: none can go in the
207  // middle of one. Its start ends the countdown, but a turn that started while the countdown began, before there was one to end, still runs.
208  const judged = expiry.judge({ ...seen, now })
209  const decision =
210    judged.kind !== 'none' && judged.kind !== 'defer' && state.answerRunning
211      ? { kind: 'defer' as const, reason: 'turn' as const, tokens: judged.tokens }
212      : judged
213  if (decision.kind === 'none' || decision.kind === 'defer') {
214    io.log('debug', `countdown: ran out, ${decidedOf(decision)}`)
215    if (decision.kind === 'defer') expiry.postpone(decision)
216    return
217  }
218  io.log('info', 'countdown: ran out')
219  expiry.carry(decision, now, seen.turns)
220}
221
222// "Not now": ends the countdown and moves the handover back as `later` with no number does, through `moveBack`, the command's own path,
223// and answers as it does, in a toast only: nothing goes to the transcript. A press with no countdown running counts for nothing, except
224// during a handover: the digit comes as an edit about 0.4 s before its press, and a countdown that ran out in between has started one. That
225// press is answered as `later` is then.
226export const press = async (io: CountdownIo, state: State, moveBack: () => Promise<Answer>): Promise<NonNullable<Answer['lines']>> => {
227  const ended = end(io, state)
228  if (!ended && !state.handingOver) return []
229  const answer = await moveBack()
230  io.toast(answer.text)
231  const lines = answer.lines ?? []
232  return ended ? [['debug', 'countdown: moved back by Not now'], ...lines] : lines
233}
234
hooks/log.ts 55 lines
1// The diagnostic output, for developers: one function, one level, and only the level decides which lines show. The level comes from an
2// environment variable, not from a setting, so it ships with nothing and shows in no menu. This module never sees the host and never names
3// the variable: what reads it and what writes a line are handed in, so all of it is tested without a host.
4
5// In rising order; each level shows its own lines and those of the levels before it.
6const LEVELS = ['off', 'warn', 'info', 'debug', 'trace'] as const
7
8export type Level = (typeof LEVELS)[number]
9
10// Unset or empty is off. There is no short form such as `1` or `true`: it would leave open which level it means. Anything that is no
11// level turns on `warn` rather than `off`, since `off` would hide the very line that names the typo, and `info` would add a line at every
12// pause to someone who meant `0` or `error`.
13export const levelOf = (raw: string | undefined): { level: Level; bad?: string } => {
14  const value = (raw ?? '').trim().toLowerCase()
15  if (value === '') return { level: 'off' }
16  return (LEVELS as readonly string[]).includes(value) ? { level: value as Level } : { level: 'warn', bad: value }
17}
18
19export const shows = (configured: Level, line: Level): boolean => line !== 'off' && LEVELS.indexOf(line) <= LEVELS.indexOf(configured)
20
21// The level is asked at each line, not once: a line written later, as from a timer, goes by the level of the latest read.
22export const logger =
23  (level: () => Level, out: (text: string) => void) =>
24  (line: Exclude<Level, 'off'>, text: string): void => {
25    if (shows(level(), line)) out(`${line}: ${text}`)
26  }
27
28// What the mod keeps of the variable: the level in force, and the bad value it last reported, so that a bad value is reported once and
29// not at every read. A valid read forgets it: the same typo after a correction is a new mistake.
30export type LevelMemo = { logLevel: Level; badLogLevel: string | undefined }
31
32// Each handler that logs reads the variable at its start, since a value set in a settings file reaches the host at the next turn and a
33// reload does not load the mod again. Everything after the read runs without a break, so two handlers reading at once write one line.
34// A read that throws keeps the level as it was, and says nothing: a hook that throws is skipped by the host, and a switch for diagnostics
35// must not stop the mod's work.
36// It answers with the level before the read, so that the caller can mark a change.
37export const refresh = async (read: () => Promise<string | undefined>, out: (text: string) => void, memo: LevelMemo): Promise<Level> => {
38  let raw: string | undefined
39  try {
40    raw = await read()
41  } catch {
42    return memo.logLevel
43  }
44  // Taken after the wait: of two reads at once, the second sees what the first set.
45  const before = memo.logLevel
46  const { level, bad } = levelOf(raw)
47  memo.logLevel = level
48  if (bad === undefined) memo.badLogLevel = undefined
49  else if (memo.badLogLevel !== bad) {
50    memo.badLogLevel = bad
51    logger(() => memo.logLevel, out)('warn', `log level "${bad}" is not one of ${LEVELS.join(', ')}, logging at warn`)
52  }
53  return before
54}
55