SLOPSHOPPER

autopilot

Run a session autonomously for a set time with a fixed role; hand off and restart itself at a context threshold

guardcommandtoaststatusprompttool
★ 2v0.5.0no licenseupdated 2026-10-23VladLeus/claude-mods/autopilot
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · autopilot
› fix the failing auth test and add an audit log call ╭────────────────────────────────────────────╮ │ autopilot │ ⏺ Read(src/auth.ts) │ Autopilot: Usage: /away for <duration> │ ⎿ Read 6 lines │ [--global] (90m, 2h, 1h30m) · /away until │ ⏺ Update(src/auth.ts) │ <clock> [--global] (15:00, 6pm, local │ ⎿ Added 2 lines, removed 1 line ╰────────────────────────────────────────────╯ ⏺ Bash(bun test) ╭────────────────────────────────────────────╮ ⎿ 3 pass, 1 fail │ autopilot │ │ Autopilot: Usage: /ask-user on|off │ ● Done. refresh now rejects expired claims and logs an audit event. │ [--global] │ ╰────────────────────────────────────────────╯ ✻ Worked for 42s · done 4:20 PM › /autopilot ⎿ autopilot: Autopilot is off. ⎿ autopilot: Away: not set ⎿ autopilot: Asks the person: off (not set) ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

claude-mods

Two Claude Code mods (plugins of function hooks) in one local marketplace, local-mods:

ModCommandWhat it does
agent-fleet/fleetA pane with every running session that has the mod: context fill, working/idle, subagents and workflow agents, who messages whom, cost, and an autopilot badge. /fleet toggles it.
autopilot/autopilot, /away, /back, /ask-userRuns a session on its own for a set time with a fixed role. At a context threshold it writes a handoff, clears itself and resumes from the handoff, instead of auto-compacting. Respects the permission mode, defers blocked actions, watches token limits, works with /goal. With asking on (--ask-user or /ask-user on), while you are away it queues its critical questions and asks them one by one when you are back.

Function-hook mods are early access: you need a recent Claude Code (built and tested on 2.1.295).

Install

Just use them

Install a signed release tag, not main: pick the latest tag from the releases and put it after #.

claude plugin marketplace add VladLeus/claude-mods#v0.5.0
claude plugin install autopilot@local-mods
claude plugin install agent-fleet@local-mods

Restart Claude Code. The marketplace stays on that tag, and third-party marketplaces do not auto-update unless you turn it on in /plugin → Marketplaces. To move to a newer release, check its notes and diff first, then remove the marketplace and add it again with the new tag.

Develop them (clone + local marketplace)

This mode is for developing the mods, not for everyday use. The marketplace is read live from your clone, so any commit you pull or check out runs with full access to your machine on the next reload. Review untrusted PRs in a separate worktree or clone that no marketplace points at. Never run claude plugin test (or reload plugins) on an untrusted PR checkout locally: spec files and hooks are code that runs with your full user access, so let the specs CI run them.

git clone https://github.com/VladLeus/claude-mods.git ~/code/claude-mods
claude plugin marketplace add ~/code/claude-mods
claude plugin install autopilot@local-mods --scope user
claude plugin install agent-fleet@local-mods --scope user

A marketplace added from a folder is read from that folder: edit the files, then run /reload-plugins in a session.

Skills autopilot needs

Autopilot hands off with two skills. Copy them unless you already have skills with these names:

cp -R extras/skills/create-handoff-doc extras/skills/resume-handoff-doc ~/.claude/skills/

Handoffs are written to thoughts/shared/handoffs/ of the project.

autopilot

/autopilot <time> <threshold%> [max restarts] "<role>" [--goal "<condition>"] [--5h 95] [--week 80] [--ask-user]
/autopilot until <clock> <threshold%> [max restarts] "<role>" [flags]   # same start, ending at a local time
/autopilot                 # status
/autopilot extend [<time>] [--restarts N]   # add time and/or restarts
/autopilot shorten [<time>] [--restarts N]  # take time and/or restarts off
/autopilot until HH:MM     # end at a local time
/autopilot 0 0 stop        # hand the wheel back (also clears the goal)

extend, shorten and until only work when you type them (in the prompt or over Remote Control), never from the session itself. Give a time, --restarts N (1–99), or both. With a limited run, --restarts raises or lowers the max restarts by N (lowering never goes below the restarts already used). With an unlimited run, extend --restarts N allows N more restarts from now, and shorten --restarts is ignored (the reply says so).

A run that ended on time is brought back by extending its time. A run that ended on restarts is brought back by raising the limit while there is time left. Anything else (goal met, weekly limit, work complete) is not revived. The change is refused when the new end would be in the past, less than 1 minute ahead, or more than 7 days ahead.

A run that finished on time or on restarts is kept for 15 minutes. In that time /autopilot says so, and extend, shorten --restarts or until bring it back: the session clears and resumes from the handoff it already wrote, through a restart that is not counted against the restarts. If the session does not restart after being asked once more, the run pauses and says so; the handoff it restarts from must be newer than the moment the run began finishing. After a goal, the weekly limit or a work-complete finish, or after /autopilot 0 0 stop, nothing is kept. <clock> (for until, as a start and as a change) is 24-hour 18:30 or 7:30, or 12-hour with am/pm and no space, any case: 6pm, 6:30pm, 12am (midnight), 12pm (noon). It is the next time the local clock reads that, always under 24 hours ahead. until <clock> alone changes the end of the running session; followed by a threshold and role it starts a run. until needs the machine's time zone; when it cannot be read, use extend or shorten.

Example, a night run:

/autopilot 10h 65 "You are the docs writer, responsible for … Use /explore for the map." --goal "issue #42 is closed and its docs are merged" --5h 95 --week 80
  • time: 90m, 2h, 1h30m, or minutes.
  • threshold: the context % at which it hands off and restarts. Under 50%, every handoff after the first fires 10 points later (a resume alone loads ~5–15%). It never waits past auto-compact minus 10 points; a higher value is lowered to that ceiling and the command says so. The ceiling depends on autoCompactWindow in ~/.claude/settings.json (800000 on a 1M window gives ~66%). Raise that setting to allow a higher threshold.
  • max restarts: leave out for as many as the time allows.
  • role: who the session is and what it is responsible for. It is pinned in the system prompt, survives /clear, and goes into every handoff with the session's /rename name and /color (the color is set again after each /clear). /skills named in the role are recognised and announced to the model as skills.
  • --goal: a /goal completion condition, set again after every /clear. When the evaluator marks it met, autopilot asks for a final handoff and stops. Phrase it in terms of files or repo state, not "in the chat": after /clear the chat is empty.
  • --5h: at this % of the 5-hour token window it parks and resumes 2 minutes after the window resets.
  • --week: at this % of the weekly window it stops for good: final handoff, summary, a phone notification from the session, autopilot off.
  • --ask-user: lets the session wait for you, for critical things only (an irreversible or outward-facing action, missing access, a decision outside its role): it sends a phone notification with the question, waits with wait_for, and is not nudged until you answer. Everything else it still decides itself. Without the flag it never waits for you unless you turn asking on with /ask-user on; /ask-user on|off works while the run goes or before it starts (see Away, back and ask-user).

While it runs:

  • Ordinary questions (AskUserQuestion) are answered with "decide yourself within your role"; the decision goes into the handoff. Only a question that truly cannot wait is sent to your phone (PushNotification).
  • Permissions stay as they are. Run the session in auto mode or with allow rules. An action the permission mode refuses (a push, a commit) is never retried another way: it is logged as deferred and left for you.
  • The session never ends or hands off on its own; autopilot decides. If the work is done it answers AUTOPILOT_DONE and autopilot wraps up.
  • Waiting: when the session hands work to someone else and has nothing useful left, it calls the wait_for tool and ends its turn. While it waits, autopilot does not nudge it, does not count idle turns and drops the goal's re-prompt. Any new turn (a message from another session, a subagent or workflow finishing, you) wakes it.
  • Reasons: session-answer, session-ping, subagent-result, workflow-end, background-task, other, and, while it may ask you (asking is on with --ask-user or /ask-user on, you are not away, and no ended away is still waiting for you to write), also user-answer and user-input (these need the question as note). from names who it waits for.
  • timeout (30m, 1h): past it, autopilot asks the session once to check whether the answer is stuck. It never runs past the run's time.
  • The status and the fleet badge show what it waits for, from whom and for how long: /autopilot prints Waiting: session-answer ← "BE-expert" · 12m, the fleet badge ⏸ session-answer ← BE-expert · 12m00s.
  • Log: ~/.claude/autopilot/<session id>.log (decisions, deferrals, restarts, limits).

Away, back and ask-user

/away for <duration> [--global]   # 90m, 2h, 1h30m
/away until <clock> [--global]    # 15:00, 6pm: the next time the local clock reads that
/back [--global]
/ask-user on|off [--global]

These tell the session whether it may ask you now. They only work when you type them (in the prompt or over Remote Control), never from the session itself. --global may stand anywhere in the line.

  • Scope. Without --global the setting is for this session. With --global it is for every session on this machine with the mod (~/.claude/autopilot/status/global.json; needs HOME). A session's own setting always beats the global one, field by field, even when it is older: /back in one session keeps it available while a global away holds for the rest.
  • No run needed. The setting is stored even when autopilot is off and applies to the next run (in this session, or in every session for --global). A session's setting follows autopilot's own restarts, but not your own /clear (that is a new session).
  • /away needs a time: a duration (at least 1 minute, at most 7 days) or until <clock> (same clock forms as /autopilot until, always under 24 hours ahead). Bare /away, an unknown word or a time out of range is an error and changes nothing.
  • While you are away (or asking is off), the session works as without --ask-user: it decides ordinary questions itself. A critical question (one it would have stopped and asked you about) goes into a queue with queue_question, with what it does meanwhile, and it keeps working on what that question does not block. The queue never drops a question; above 20 a toast warns. If the session was waiting for your answer when you went away, the wait ends and that question stays queued (at the head if it was not queued yet); if the wait did not carry the question, the session is told to queue it itself.
  • When the away ends with an empty queue, nothing happens. With questions queued, the session sends one phone notification ("N critical questions are queued") and keeps working without asking until you write in it. A message you write before the away ends does not count: use /back. A global away ends with one combined notification across sessions ("7 questions in 3 sessions"), sent by one of them. An away that ends while asking is off sends nothing.
  • /back, or your first message after the away ended, starts the questions: one at a time, as text, waiting with wait_for user-answer. Your answer, typed while the session waits for it, takes it off the queue and the next one follows. A message you send before a question is asked removes nothing. New critical questions join the end of the queue.
  • /ask-user off is an away without an end: critical questions are queued. /ask-user on turns asking on, also for a run started without --ask-user; when you are not away it starts the queued questions. During an active /away it only flips the switch: the away holds until its time.
  • A run started without --ask-user, with no /ask-user setting anywhere, never waits for you and queues nothing: /away is stored but changes nothing until /ask-user on.
  • Notifications and questions reach the session only while it works or waits for an answer. While it is parked on the 5-hour limit, paused or restarting, you get a toast; they are delivered when it works again. An away-end notification not delivered yet is dropped once it is no longer true: you are back and the questions start, you go away again, asking is turned off, or (for a global away) a day has passed since it ended.
  • Questions still open when the run ends go into the final handoff. A new run started in this session (for example after a pause) keeps them and asks them when asking is on; /autopilot 0 0 stop lists them in its reply.
  • /autopilot shows whether you are away and whether asking is on, each with where it comes from (session or global), also with no run; during a run it also shows the mode and how many questions are queued.

agent-fleet

/fleet toggles the pane (/fleet open, /fleet close). Every session with the mod writes a heartbeat to ~/.claude/fleet/<session id>.json every 15 s and on every turn, spawn and message; the pane reads that folder. Ended and cleared sessions are hidden at once (a resume brings them back), a silent one shows "no signal" after 3 minutes and is dropped after an hour, and files older than a day are deleted.

Contributing

main takes changes through pull requests only, and a PR merges after the owner (@VladLeus) approves it:

  • Work on a branch, open a PR against main.
  • A PR is required, with 1 code-owner approval (CODEOWNERS + the branch ruleset); new commits dismiss it.
  • Required checks: owner-approval, specs (each mod and the marketplace) and signed-commits. Commits must be signed.
  • protected-paths is a warning, not a requirement: it turns red when a PR touches .github/, CODEOWNERS or removes or shrinks tests, so the owner reviews those changes with extra care.
  • The owner-approval status is success only when the owner's latest review is an approval of the PR's current head; the owner-approved label mirrors it and a label set by hand is overwritten.
  • No direct pushes and no force pushes to main, not even for admins: an admin can bypass the rules only by merging a PR.

Collaborators push branches to this repository. A PR from a fork works too, but its label and status are then set by the owner by hand (a fork's workflow token cannot write to this repository).

Developing

  • Edit, then /reload-plugins in a session. Check with: ``bash claude plugin validate autopilot claude plugin test autopilot ``
  • Bump version in .claude-plugin/plugin.json and run claude plugin update <mod>@local-mods after a change. /reload-plugins reads the folder, but a restarted Claude Code (the desktop app especially) loads the copy cached at the last install or update.
  • The engine writes the API's types beside each mod at .claude-plugin/types/ (git-ignored); grep claude-code/index.d.ts there for events and $ methods.
  • Logic worth testing lives in a plain module (fleet.ts, autopilot.ts); register.tsx holds the hooks.
Source 3 files
hooks/register.tsx 1772 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import type { Avail, AvailCommand, BadgeAvail, Effective, FinalReason, FinishedRecord, LockOwner, Mode, Pending, Run, TokenWindow } from '../types'
4import {
5  CONTINUE_PROMPT,
6  DEFAULT_CEILING,
7  DEFERRED_NOTE,
8  FULL_QUEUE_TOOL,
9  FULL_WAIT_TOOL,
10  HEARTBEAT_MS,
11  NOT_RUNNING_TEXT,
12  QUEUE_TOOL,
13  QUEUE_WARN,
14  RESTART_TOOL,
15  RESUME_AFTER_WAIT_PROMPT,
16  WAIT_REASONS,
17  WAIT_TOOL,
18  addQuestion,
19  afterTurn,
20  answeredQuestion,
21  applyAvail,
22  applyMode,
23  askAnswer,
24  autoAnswersQuestions,
25  availMode,
26  availStatusLines,
27  awayUntil,
28  canDeliver,
29  combinedPingText,
30  criticalCount,
31  deliveredPending,
32  drainingQuestion,
33  effective,
34  effectiveTrigger,
35  eligibleForCombined,
36  endClock,
37  endsWait,
38  finalPrompt,
39  followsNewSessionId,
40  formatLeft,
41  globalFromText,
42  goalState,
43  goalVerdictsFromRows,
44  graceResumePrompt,
45  graceHandoffCheck,
46  graceStatusText,
47  graceTurnAction,
48  handoffArg,
49  humanSubmit,
50  identityFromRows,
51  isDoneAnswer,
52  isGraceEligible,
53  isGraceLive,
54  isLiveFinishedValue,
55  isValidHandoffPath,
56  kickoffPrompt,
57  limitAction,
58  lockStale,
59  namedSkills,
60  parseAskUser,
61  parseAway,
62  parseBack,
63  parseBadgeAvail,
64  parseCommand,
65  parseLockOwner,
66  parseQueueInput,
67  parseUtcOffset,
68  parseWaitInput,
69  pushPending,
70  questionIdFromNote,
71  questionsBlock,
72  queuedAcross,
73  queuedResult,
74  resolveHandoffPath,
75  restartsText,
76  retime,
77  revivePrompt,
78  roleSection,
79  shouldDropStopBlock,
80  sumQueued,
81  targetChange,
82  triggerCeiling,
83  untilFromClock,
84  validAvail,
85  waitPhaseRefusal,
86  waitPrompt,
87  waitRefusal,
88  waitText,
89  waitTimeoutPrompt,
90  wrapMidTurn,
91  wrapupPrompt,
92} from './autopilot'
93
94const FULL_RESTART_TOOL = 'mcp__autopilot__restart_session'
95/** With a goal, the goal loop starts the next turn; if none starts within this, autopilot looks why. */
96const GOAL_IDLE_MS = 20_000
97
98let run: Run | null = null
99let sessionId = ''
100// Empty when HOME is unset: then no state or log file is written at all.
101let home = ''
102let isTurnRunning = false
103let toolsThisTurn = 0
104// Counts main turns, so a delayed check can tell whether a new turn started meanwhile.
105let turnSeq = 0
106// Whether this run's /goal is set right now (/clear removes it; autopilot sets it again).
107let isGoalSet = false
108// The highest context % a handoff may wait for, below auto-compact.
109let ceiling = DEFAULT_CEILING
110// The text of a pending submit that is scheduled and not yet answered; a second one waits for it.
111let flushingText: string | null = null
112// Toasts already shown: held pings (`kind:key`) and global-away toasts (`global:<setAt>`), so each shows once, not every heartbeat.
113const heldToasts = new Set<string>()
114/** Global away `setAt`s whose combined ping this module handed to the model: never pushed again, even when writing `done` failed. */
115const deliveredCombined = new Set<number>()
116// Whether the prompt that starts the next turn is the person's answer during a drain.
117// A reload resets it: no question leaves the queue until this module sees the person write.
118let lastSubmitHuman = false
119// The availability records as last read: this session's ($.store) and the global one (global.json).
120let sessionAvail: Avail | null = null
121let globalAvail: Avail | null = null
122// global.json's mtime at the last read; the heartbeat re-reads it only when this changes.
123let globalMtime: number | null = null
124// When the badge last carried a heartbeat time.
125let lastBeat = 0
126
127/**
128 * Reads the session's auto-compact threshold and sets the ceiling below it.
129 * The trigger compares against `context.percent`, which is over the model's
130 * window, so the threshold is measured on that window too, never on the
131 * smaller compaction window (`autoCompactWindow`) the breakdown counts in.
132 */
133async function readCeiling($: EngineInterface): Promise<number> {
134  const usage = await $.session.usage({ breakdown: 'summary' }).catch(() => null)
135  const breakdown = usage?.context.breakdown
136  ceiling = triggerCeiling(
137    breakdown?.isAutoCompactEnabled ? breakdown.autoCompactThreshold : undefined,
138    usage?.context.window,
139  )
140
141  return ceiling
142}
143
144const storeKey = (id: string) => `run:${id}`
145const finishedKey = (id: string) => `finished:${id}`
146const availKey = (id: string) => `away:${id}`
147
148/** The record of a run that finished on time or restarts, while the grace period lasts; an expired one is deleted. */
149async function loadFinished($: EngineInterface, now: number): Promise<FinishedRecord | null> {
150  if (!sessionId) return null
151  const record = ((await $.store.get(finishedKey(sessionId))) as FinishedRecord | undefined) ?? null
152  if (!record) return null
153  if (isGraceLive(record, now)) return record
154  await $.store.delete(finishedKey(sessionId)).catch(() => undefined)
155
156  return null
157}
158
159/** A combined-ping lock lives this long; then the sweep removes it. */
160const LOCK_TTL_MS = 24 * 60 * 60_000
161
162/** Deletes every finished-run record, of any session, that is past its grace period or malformed, and old combined-ping locks. */
163async function sweepFinished($: EngineInterface): Promise<void> {
164  const now = await $.clock.now()
165  for (const key of await $.store.keys()) {
166    if (!key.startsWith('finished:')) continue
167    const value = await $.store.get(key)
168    if (!isLiveFinishedValue(value, now)) await $.store.delete(key)
169  }
170  if (!home) return
171  const entries = await $.fs.list(statusDir()).catch(() => [])
172  for (const entry of entries) {
173    if (!/^ping-\d+\.lock$/.test(entry.name)) continue
174    const path = `${statusDir()}/${entry.name}`
175    if (entry.kind !== 'dir') {
176      // A file or a link under a lock's name is not ours and blocks the combined ping for good.
177      await $.process.run(['/bin/rm', '-f', '--', path]).catch(() => undefined)
178      continue
179    }
180    // A list entry's mtimeMs is 0 for a directory, so stat it; a failed stat or a missing mtime keeps the lock.
181    const stat = await $.fs.stat(path).catch(() => null)
182    if (!stat || !(now - stat.mtimeMs >= LOCK_TTL_MS)) continue
183    await $.process.run(['/bin/rm', '-rf', '--', path]).catch(() => undefined)
184  }
185}
186
187const autopilotDir =() => `${home}/.claude/autopilot`
188const statusDir = () => `${autopilotDir()}/status`
189const globalFile = () => `${statusDir()}/global.json`
190
191/** The machine's UTC offset in minutes east of UTC (`date +%z`); null when it cannot be read. */
192async function utcOffset($: EngineInterface): Promise<number | null> {
193  try {
194    const result = await $.process.run(['/bin/date', '+%z'])
195
196    return parseUtcOffset(result.stdout)
197  } catch {
198    return null
199  }
200}
201
202/** This session's availability record, read again from the store; null when none or malformed. */
203async function readSessionAvail($: EngineInterface): Promise<Avail | null> {
204  if (!sessionId) {
205    sessionAvail = null
206    return null
207  }
208  const value = await $.store.get(availKey(sessionId)).catch(() => undefined)
209  sessionAvail = validAvail(value, await $.clock.now())
210
211  return sessionAvail
212}
213
214async function writeSessionAvail($: EngineInterface, rec: Avail): Promise<void> {
215  if (!sessionId) return
216  await $.store.set(availKey(sessionId), rec)
217  sessionAvail = rec
218}
219
220/**
221 * The global record. Re-read only when global.json changed (or `force`); a
222 * missing, empty, half-written or future-dated file keeps the last good value.
223 * Never throws.
224 */
225async function readGlobalAvail($: EngineInterface, force = false): Promise<Avail | null> {
226  if (!home) return globalAvail
227  const stat = await $.fs.stat(globalFile()).catch(() => null)
228  if (!stat) return globalAvail
229  if (!force && stat.mtimeMs === globalMtime) return globalAvail
230  const isFirstRead = globalMtime === null
231  const text = await $.fs.read(globalFile()).catch(() => null)
232  const previous = globalAvail
233  globalAvail = globalFromText(text, await $.clock.now(), globalAvail)
234  globalMtime = stat.mtimeMs
235  // A change this session did not write (another session's --global, or anything else that
236  // wrote the file): the person sees it, not only the log.
237  if (!isFirstRead && JSON.stringify(previous) !== JSON.stringify(globalAvail)) {
238    $.ui.toast(`Autopilot: the global away/ask-user status changed outside this session (${globalFile()}); /autopilot shows it.`)
239    await log($, `global status changed outside this session: ${JSON.stringify(globalAvail)}`)
240  }
241
242  return globalAvail
243}
244
245/** Writes global.json for every session: a temp file of this session, then an atomic rename. */
246async function writeGlobalAvail($: EngineInterface, rec: Avail): Promise<void> {
247  if (!home) throw new Error('HOME is not set')
248  const target = await $.fs.stat(globalFile()).catch(() => null)
249  if (target && (target.kind !== 'file' || target.isLink)) throw new Error(`${globalFile()} is not a regular file`)
250  const tmp = `${globalFile()}.tmp-${sessionId}`
251  const stale = await $.fs.stat(tmp).catch(() => null)
252  if (stale) await $.process.run(['/bin/rm', '-f', '--', tmp])
253  await $.fs.write(tmp, JSON.stringify(rec))
254  const moved = await $.process.run(['/bin/mv', '-f', '--', tmp, globalFile()])
255  if (moved.exitCode !== 0) throw new Error(`could not write ${globalFile()}: ${moved.stderr.trim()}`)
256  const written = await $.fs.stat(globalFile()).catch(() => null)
257  if (!written || written.kind !== 'file') throw new Error(`${globalFile()} is not a file after the write`)
258  globalAvail = rec
259  globalMtime = written.mtimeMs
260}
261
262/** The effective status: session record over global record per field, else the run's --ask-user flag. */
263async function currentEffective($: EngineInterface): Promise<Effective> {
264  await readSessionAvail($)
265  await readGlobalAvail($)
266
267  return effective(run, sessionAvail, globalAvail)
268}
269
270/** Whether questions go to the person now, from the records as last read (no I/O). */
271function askOnNow(): boolean {
272  return effective(run, sessionAvail, globalAvail).askOn
273}
274
275async function save($: EngineInterface): Promise<void> {
276  if (!sessionId) return
277  const now = await $.clock.now()
278  if (!run) {
279    await $.store.delete(storeKey(sessionId))
280    if (home) await $.fs.write(`${autopilotDir()}/${sessionId}.json`, JSON.stringify({ isOn: false }))
281    return
282  }
283  await $.store.set(storeKey(sessionId), run)
284  if (!home) return
285  const eff = effective(run, sessionAvail, globalAvail)
286  // Read by the fleet dashboard for its badge; the last four fields only by the combined ping,
287  // which counts only questions that will be asked: none while asking is off (D4).
288  await $.fs.write(
289    `${autopilotDir()}/${sessionId}.json`,
290    JSON.stringify({
291      isOn: true,
292      phase: run.phase,
293      until: run.until,
294      threshold: run.threshold,
295      restarts: run.restarts,
296      maxRestarts: run.maxRestarts,
297      waitUntil: run.waitUntil,
298      hasGoal: run.goal !== null,
299      waitingFor: run.awaiting?.reason ?? null,
300      waitingFrom: run.awaiting?.from ?? null,
301      waitingSince: run.awaiting?.since ?? null,
302      queued: eff.askOn ? (run.questions?.length ?? 0) : 0,
303      awaySource: eff.awaySource,
304      awaySetAt: eff.away?.setAt ?? null,
305      beat: now,
306    }),
307  )
308  lastBeat = now
309}
310
311/** Appends one line to this session's autopilot log: decisions, deferrals, restarts. */
312async function log($: EngineInterface, line: string): Promise<void> {
313  if (!home) return
314  const path = `${autopilotDir()}/${sessionId}.log`
315  // Free text may carry line breaks; flattened, it cannot forge a log line.
316  // Every other control, format and separator character goes too (same class as autopilot.ts).
317  const flat = line
318    .replace(/[\r\n\u{85}\u{2028}\u{2029}]/gu, ' ')
319    .replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, '')
320  const stamp = new Date(await $.clock.now()).toISOString()
321  let before = ''
322  try {
323    before = await $.fs.read(path)
324  } catch {
325    before = ''
326  }
327  await $.fs.write(path, `${before}${stamp}  ${flat}\n`).catch(() => undefined)
328}
329
330/**
331 * Submits a prompt once the session is idle, outside the hook that decided
332 * it. A submit lands as an interruption when a turn runs, so when one has
333 * started meanwhile (the goal loop, the person), something else is driving:
334 * the prompt is dropped.
335 */
336function queue($: EngineInterface, text: string): void {
337  $.clock.after(300, () => {
338    if (isTurnRunning) return
339    void $.prompt.submit({ text }).catch(() => undefined)
340  })
341}
342
343async function setGoal($: EngineInterface): Promise<void> {
344  if (!run?.goal) return
345  const goal = run.goal
346  await $.command
347    .run({ command: 'goal', args: goal })
348    .then(() => {
349      isGoalSet = true
350    })
351    .catch(async error => log($, `could not set the goal: ${String(error)}`))
352}
353
354async function clearGoal($: EngineInterface): Promise<void> {
355  if (!isGoalSet) return
356  isGoalSet = false
357  await $.command
358    .run({ command: 'goal', args: 'clear' })
359    .catch(async error => log($, `could not clear the goal: ${String(error)}`).catch(() => undefined))
360}
361
362/**
363 * The transcript lives under the project root's folder. Never the current
364 * directory: a shell `cd` in the session moves that, not the root.
365 */
366async function transcriptOf($: EngineInterface, id: string): Promise<string> {
367  const root = await $.session.root()
368
369  return `${home}/.claude/projects/${root.replace(/[^a-zA-Z0-9]/g, '-')}/${id}.jsonl`
370}
371
372/**
373 * The whole transcript lines grep matches; empty when nothing or on failure.
374 * Whole lines, so each is parsed as a row and judged by where a value sits.
375 */
376async function grepTranscript($: EngineInterface, pattern: string): Promise<string[]> {
377  if (!home) return []
378  let out = ''
379  try {
380    const grep = $.process.spawn({ argv: ['/usr/bin/grep', '-E', '-e', pattern, '--', await transcriptOf($, sessionId)] })
381    for await (const chunk of grep) if (chunk.stream === 'stdout') out += chunk.text
382  } catch {
383    return []
384  }
385
386  return out.split('\n').filter(Boolean)
387}
388
389/** Reads the session's /rename name and /color from its own transcript's top-level identity rows. */
390async function readIdentity($: EngineInterface): Promise<{ name: string | null; color: string | null }> {
391  return identityFromRows(await grepTranscript($, '^\\{"type":"(custom-title|agent-name|agent-color)"'))
392}
393
394/**
395 * Whether the goal evaluator has judged this run's goal met, from the
396 * `goal_status` verdicts the engine keeps as top-level attachment rows.
397 */
398async function isGoalMet($: EngineInterface): Promise<boolean> {
399  if (!run?.goal) return false
400  const rows = await grepTranscript($, '"goal_status"')
401
402  return goalState(goalVerdictsFromRows(rows), run.goal) === 'achieved'
403}
404
405/**
406 * Keeps the run's name and color current. A transcript after /clear carries
407 * the name but no color, so a value missing there never erases a known one.
408 */
409async function refreshIdentity($: EngineInterface): Promise<void> {
410  if (!run) return
411  const identity = await readIdentity($)
412  const name = identity.name ?? run.name
413  const color = identity.color ?? run.color
414  if (name === run.name && color === run.color) return
415  run.name = name
416  run.color = color
417  await save($)
418}
419
420/**
421 * /clear and /resume change the session id under a running module. Only the
422 * run's own /clear (phase restarting) moves it to the new id, with this
423 * session's availability record; any other new id is another conversation,
424 * which the run does not drive: it stays stored under its old id, and the new
425 * id's own run and record, if any, are loaded.
426 */
427async function syncId($: EngineInterface): Promise<void> {
428  const id = await $.session.id()
429  if (id === sessionId) return
430  const previous = sessionId
431  sessionId = id
432  if (run && followsNewSessionId(run.phase)) {
433    if (previous) {
434      await $.store.delete(storeKey(previous))
435      const away = await $.store.get(availKey(previous))
436      if (away !== undefined) {
437        await $.store.set(availKey(id), away)
438        await $.store.delete(availKey(previous))
439      }
440    }
441    await save($)
442    return
443  }
444  run = ((await $.store.get(storeKey(id))) as Run | undefined) ?? null
445  await readSessionAvail($)
446}
447
448/**
449 * The mode rule, one place for every trigger (spec §5.1): recomputes the
450 * mode from the records, applies its effects to the run and saves. Saves
451 * at least every half heartbeat, so the badge's `beat` stays fresh. Null
452 * when no run.
453 */
454async function refreshMode($: EngineInterface): Promise<Mode | null> {
455  await currentEffective($)
456  const now = await $.clock.now()
457  if (!run) return null
458  // Decided and applied with no await in between: a parallel trigger acts on the result.
459  const eff = effective(run, sessionAvail, globalAvail)
460  const prev = run.lastMode ?? null
461  const before = JSON.stringify(run)
462  const next = availMode(run, eff, now)
463  const applied = applyMode(run, next, eff, now)
464  run = applied.run
465  const isChanged = JSON.stringify(run) !== before
466  if (isChanged || now - lastBeat >= HEARTBEAT_MS / 2) await save($)
467  if (prev !== next) await log($, `availability mode ${prev ?? 'none'} -> ${next}`)
468  // Informational: the combined ping itself comes from the heartbeat's combinedTick (task 10).
469  if (applied.combined) await log($, 'global away over here: the combined ping is decided by the heartbeat')
470
471  return next
472}
473
474/** Moves the run to its final phase; the goal loop stops so it cannot outrun the handoff. */
475async function enterFinal($: EngineInterface, reason: FinalReason): Promise<string | null> {
476  if (!run) return null
477  run.phase = 'final'
478  run.finalReason = reason
479  // A declared wait ends with the run's last stage (the time running out while awaiting).
480  run.awaiting = null
481  // The final handoff is written after this moment; a grace resume asks for a handoff newer than it.
482  run.finalAt = await $.clock.now()
483  await clearGoal($)
484  await save($)
485  await log($, `final handoff requested (${reason})`)
486  if (reason === 'week') {
487    $.ui.toast(`Autopilot: ABSOLUTE STOP, the weekly token limit is at ${run.weekStop}%. Writing a handoff, then waiting for you.`)
488  }
489
490  return finalPrompt(run, reason)
491}
492
493/** Ends a 5-hour wait: back to work, the goal set again. */
494async function wake($: EngineInterface): Promise<void> {
495  if (!run || run.phase !== 'waiting' || isTurnRunning) return
496  run.phase = 'running'
497  run.waitUntil = null
498  run.idleTurns = 0
499  await save($)
500  await log($, 'the 5-hour token window reset: resuming')
501  // Setting the goal again starts the next turn itself.
502  if (run.goal) await setGoal($)
503  else queue($, RESUME_AFTER_WAIT_PROMPT)
504}
505
506function scheduleWake($: EngineInterface, now: number): void {
507  if (!run?.waitUntil) return
508  $.clock.after(Math.max(1_000, run.waitUntil - now), () => void wake($))
509}
510
511/**
512 * Applies the token windows: the weekly stop ends the run, the 5-hour stop
513 * parks it until the reset. Returns the instruction for the model, if any.
514 * The phase flips before the first await, so parallel calls act once.
515 */
516async function applyLimits($: EngineInterface, windows: readonly TokenWindow[], now: number): Promise<string | null> {
517  if (!run || (run.phase !== 'running' && run.phase !== 'resuming' && run.phase !== 'waiting')) return null
518  const action = limitAction(run, windows, now)
519  if (!action) return null
520
521  if (action.kind === 'week') return enterFinal($, 'week')
522  if (run.phase === 'waiting') return null
523
524  run.phase = 'waiting'
525  run.waitUntil = action.waitUntil
526  await clearGoal($)
527  await save($)
528  await log($, `5-hour token window at ${run.fiveHourStop}%+: parked until ${endClock(action.waitUntil, null)}`)
529  scheduleWake($, now)
530
531  return waitPrompt(run, action.waitUntil)
532}
533
534/** The goal met: the last handoff, then the wheel goes back to the person. */
535async function finishOnGoal($: EngineInterface): Promise<void> {
536  await log($, 'goal met (evaluator verdict in the transcript)')
537  // The evaluator already cleared the goal; nothing to clear.
538  isGoalSet = false
539  const instruction = await enterFinal($, 'goal')
540  if (instruction) queue($, instruction)
541}
542
543/**
544 * With a goal, no new turn after GOAL_IDLE_MS means the goal loop stopped.
545 * Met ends the run; otherwise the goal is gone (cleared, impossible) and the
546 * continuing goes back to autopilot.
547 */
548function watchGoal($: EngineInterface): void {
549  const seq = turnSeq
550  $.clock.after(GOAL_IDLE_MS, () => {
551    void (async () => {
552      if (!run || run.phase !== 'running' || isTurnRunning || turnSeq !== seq) return
553      if (await isGoalMet($)) {
554        await finishOnGoal($)
555        return
556      }
557      await log($, 'goal loop stopped without a met verdict: autopilot continues the work')
558      isGoalSet = false
559      queue($, CONTINUE_PROMPT)
560    })()
561  })
562}
563
564/** The wait as a status line, with the time of its one check if it has a timeout. */
565function waitingLines(now: number): string[] {
566  const awaiting = run?.awaiting ?? null
567  if (run?.phase !== 'awaiting' || !awaiting) return []
568  const check = awaiting.timeoutAt ? ` · checks at ${endClock(awaiting.timeoutAt, null)}` : ''
569
570  return [`Waiting: ${waitText(awaiting, now)}${check}`]
571}
572
573/**
574 * Ends a declared wait, back to running: a new turn started (something
575 * arrived), or the session went on working (`tool` names the call).
576 */
577async function endWait($: EngineInterface, tool: string | null = null): Promise<void> {
578  if (run?.phase !== 'awaiting') return
579  const awaiting = run.awaiting ?? null
580  // Flipped before the first await, so parallel tool calls end the wait once.
581  run.phase = 'running'
582  run.awaiting = null
583  run.idleTurns = 0
584  const now = await $.clock.now()
585  await save($)
586  if (tool) {
587    await log($, `wait ended: the session went on working (${tool})`)
588    return
589  }
590  await log($, awaiting ? `woke after ${formatLeft(now - awaiting.since)} waiting for ${awaiting.reason}` : 'woke from a wait')
591}
592
593/** Once a declared wait passes its timeout, autopilot asks the session to check on it. */
594async function checkWaitTimeout($: EngineInterface, now: number): Promise<void> {
595  const awaiting = run?.awaiting ?? null
596  if (!run || run.phase !== 'awaiting' || !awaiting?.timeoutAt) return
597  if (now < awaiting.timeoutAt || awaiting.pinged) return
598  awaiting.pinged = true
599  await save($)
600  await log($, `wait timed out after ${formatLeft(now - awaiting.since)} (${awaiting.reason}): asking the session to check`)
601  queue($, waitTimeoutPrompt(awaiting, now))
602}
603
604/** The combined-ping lock of the global away set at `setAt` (a directory: mkdir is atomic). */
605const lockDir = (setAt: number) => `${statusDir()}/ping-${setAt}.lock`
606
607async function readLockOwner($: EngineInterface, dir: string): Promise<LockOwner | null> {
608  try {
609    return parseLockOwner(JSON.parse(await $.fs.read(`${dir}/owner.json`)))
610  } catch {
611    return null
612  }
613}
614
615/** The away fields of every session's badge; a missing, half-written or old badge is skipped. */
616async function readBadges($: EngineInterface): Promise<BadgeAvail[]> {
617  const entries = await $.fs.list(autopilotDir()).catch(() => [])
618  const badges: BadgeAvail[] = []
619  for (const entry of entries) {
620    if (entry.kind !== 'file' || !entry.name.endsWith('.json')) continue
621    try {
622      const badge = parseBadgeAvail(JSON.parse(await $.fs.read(`${autopilotDir()}/${entry.name}`)))
623      if (badge) badges.push(badge)
624    } catch {
625      continue
626    }
627  }
628
629  return badges
630}
631
632/**
633 * Makes the lock (mkdir fails when it exists) or takes over one whose owner
634 * stopped refreshing it. Either way this session acts as owner from the next
635 * heartbeat on, if `owner.json` still names it then.
636 */
637async function claimLock($: EngineInterface, dir: string, owner: LockOwner | null, now: number): Promise<void> {
638  const made = await $.process.run(['/bin/mkdir', dir]).catch(() => null)
639  const isNew = made?.exitCode === 0
640  if (!isNew) {
641    const stat = await $.fs.stat(dir).catch(() => null)
642    if (!stat || stat.kind !== 'dir' || stat.isLink) {
643      await log($, `combined ping: ${dir} is not a directory; left alone`)
644      return
645    }
646    if (!lockStale(owner, false, now)) return
647  }
648  await $.fs.write(`${dir}/owner.json`, JSON.stringify({ sid: sessionId, at: now }))
649  await log($, isNew ? `combined ping: took the lock ${dir}` : `combined ping: took over a stale lock ${dir} (owner ${owner?.sid.slice(0, 64) ?? 'unknown'})`)
650}
651
652/**
653 * A session on the global away that sends no combined ping ("others only
654 * toast", §7.3): one toast per away, one heartbeat after the expiry, only
655 * when questions are queued somewhere (R7).
656 */
657async function toastGlobal($: EngineInterface, away: { until: number; setAt: number }, now: number, tail: string): Promise<void> {
658  const id = `global:${away.setAt}`
659  if (heldToasts.has(id)) return
660  // One heartbeat after the expiry every live badge is fresh, as for the owner's sum.
661  if (now < away.until + HEARTBEAT_MS) return
662  heldToasts.add(id)
663  const { total, sessions } = sumQueued(await readBadges($), away.setAt, now)
664  if (total === 0) return
665  $.ui.toast(`Autopilot: the global away time is over; ${queuedAcross(total, sessions)}. ${tail}`)
666}
667
668/**
669 * One heartbeat of the combined ping (§7.3, R9). Only an eligible session
670 * (a live run on that global away, asking on, away over) touches the lock, so
671 * a session with no run never gets a prompt. The owner waits one heartbeat
672 * after the expiry, sums the live badges and queues one `combined-ping`;
673 * `done` is written when that ping is handed to the model. Every other run on
674 * the same away only toasts, once.
675 */
676async function combinedTick($: EngineInterface): Promise<void> {
677  if (!home || !run) return
678  const global = await readGlobalAvail($)
679  const away = global?.away ?? null
680  if (!away || !('until' in away)) return
681  const now = await $.clock.now()
682  // A day after the expiry the ping is moot and the sweep may have removed its lock: never a late or second one.
683  const isLate = now - away.until >= LOCK_TTL_MS
684  const isHeld = (run?.pending ?? []).some(p => p.kind === 'combined-ping' && p.key === away.setAt)
685  if (isLate && isHeld && run) {
686    // One held since (a parked run) goes too: a day late it would only mislead.
687    run = { ...run, pending: (run.pending ?? []).filter(p => !(p.kind === 'combined-ping' && p.key === away.setAt)) }
688    await save($)
689  }
690  if (isLate) return
691  // This module already handed it to the model (writing `done` may have failed).
692  if (deliveredCombined.has(away.setAt)) return
693  const eff = await currentEffective($)
694  // Stopped while the files were read.
695  if (!run) return
696  const dir = lockDir(away.setAt)
697  // The owner holding its undelivered combined ping keeps the lock alive, eligible or not
698  // (parked, or its own away changed): nobody takes over and sends a second ping (R9).
699  if ((run.pending ?? []).some(p => p.kind === 'combined-ping' && p.key === away.setAt)) {
700    await $.fs.write(`${dir}/owner.json`, JSON.stringify({ sid: sessionId, at: now }))
701    return
702  }
703  // A session record beats the global one (R5), or asking is off (D4): this away is not ours.
704  const isOnThisAway = eff.awaySource === 'global' && !!eff.away && 'until' in eff.away && eff.away.setAt === away.setAt && eff.askOn
705  if (!isOnThisAway) return
706  const mode = availMode(run, eff, now)
707  // The person is back here: this session neither sends nor keeps the lock; after two beats
708  // another session with questions takes it over and sends the one ping (editor's decision 2026-10-14).
709  if (mode === 'draining') return
710  if (!eligibleForCombined(run, eff, mode, away.setAt)) {
711    // Parked, paused or wrapping: no prompt now, the person learns of it from a toast.
712    if (run.phase !== 'running' && run.phase !== 'awaiting') {
713      await toastGlobal($, away, now, `This session asks once it is back to work (now ${run.phase}).`)
714    }
715    return
716  }
717
718  const owner = await readLockOwner($, dir)
719  if (await $.fs.exists(`${dir}/done`)) {
720    // Another session sent the notification; the owner toasted when it delivered.
721    if (owner?.sid !== sessionId) await toastGlobal($, away, now, 'Another session sent the notification; write here to answer this one.')
722    return
723  }
724  if (owner?.sid !== sessionId) {
725    await claimLock($, dir, owner, now)
726    return
727  }
728  // Still alive: no one takes over while the owner waits for the sum.
729  await $.fs.write(`${dir}/owner.json`, JSON.stringify({ sid: sessionId, at: now }))
730  // One heartbeat after the expiry every live session has refreshed its badge.
731  if (now < away.until + HEARTBEAT_MS) return
732
733  const { total, sessions } = sumQueued(await readBadges($), away.setAt, now)
734  if (total === 0) {
735    // Nothing queued anywhere: silently over (R7).
736    await $.fs.write(`${dir}/done`, String(now))
737    await log($, 'combined ping: global away over, no questions queued in any session')
738    return
739  }
740  if (!run) return
741  run = pushPending(run, { kind: 'combined-ping', text: combinedPingText(total, sessions), key: away.setAt })
742  await save($)
743  await log($, `combined ping: ${total} questions in ${sessions} sessions, pending delivery`)
744}
745
746/** A run that cannot take a prompt now (parked, paused, wrapping…): the person still learns of a ping, once. */
747function toastHeld($: EngineInterface, items: readonly Pending[], phase: string): void {
748  for (const pending of items) {
749    if (pending.kind !== 'ping' && pending.kind !== 'combined-ping') continue
750    const id = `${pending.kind}:${pending.key}`
751    if (heldToasts.has(id)) continue
752    heldToasts.add(id)
753    const when = phase === 'final' ? 'the run is finishing, so they go into its handoff' : `the session tells you once it is back to work (now ${phase})`
754    $.ui.toast(`Autopilot: away time is over and questions are queued; ${when}.`)
755  }
756}
757
758/** Records entries handed to the model: saved, logged, pings toasted, a combined ping's lock marked done. */
759async function markDelivered($: EngineInterface, items: readonly Pending[], via: 'tool' | 'turn' | 'idle'): Promise<void> {
760  // First, before any await that can fail: a combined ping handed over is never pushed again.
761  for (const pending of items) if (pending.kind === 'combined-ping') deliveredCombined.add(pending.key)
762  await save($)
763  for (const pending of items) {
764    heldToasts.delete(`${pending.kind}:${pending.key}`)
765    await log($, `delivered ${pending.kind} (${via})`)
766    if (pending.kind === 'ping') {
767      $.ui.toast(`Autopilot: away time is over; ${criticalCount(run?.questions?.length ?? 0)} queued.`)
768    }
769    if (pending.kind !== 'combined-ping') continue
770    $.ui.toast('Autopilot: away time is over; critical questions are queued in your sessions.')
771    if (!home) continue
772    await $.fs
773      .write(`${lockDir(pending.key)}/done`, String(await $.clock.now()))
774      .catch(async error => log($, `combined ping: could not mark the lock done: ${String(error)}`))
775  }
776}
777
778/**
779 * Submits pending entries once the session is idle. They leave the queue
780 * before the submit, so a tool call of the turn it starts cannot hand them
781 * over again; a dropped or failed submit puts them back.
782 */
783async function submitPending($: EngineInterface, items: readonly Pending[], via: 'turn' | 'idle'): Promise<void> {
784  try {
785    // A turn started meanwhile (the person, the goal loop) or the run moved on: they stay pending.
786    if (isTurnRunning || !run || !canDeliver(run.phase)) return
787    const pending = run.pending ?? []
788    // A tool call may have taken some already.
789    const taken = items.filter(item => pending.some(p => p.kind === item.kind && p.key === item.key))
790    if (taken.length === 0) return
791    run = taken.reduce((acc, item) => deliveredPending(acc, item), run)
792    const answer = await $.prompt.submit({ text: taken.map(item => item.text).join('\n\n') }).catch(() => null)
793    if (answer && answer.drop === undefined) {
794      await markDelivered($, taken, via).catch(error => log($, `could not record a delivery: ${String(error)}`).catch(() => undefined))
795      return
796    }
797    if (run) run = taken.reduce((acc, item) => pushPending(acc, item), run)
798    await save($)
799    await log($, `pending prompt not delivered (${via}): ${answer?.drop ?? 'the submit failed'}`)
800  } finally {
801    flushingText = null
802  }
803}
804
805/**
806 * Hands `run.pending` to the model (§7.1). `tool`: taken now, the text goes
807 * into the tool result's context. `turn` / `idle`: one submit once idle; the
808 * text returned means a prompt is on its way, so the caller queues nothing
809 * else. Null when nothing is pending or the phase cannot take a prompt.
810 */
811async function flushPending($: EngineInterface, via: 'tool' | 'turn' | 'idle'): Promise<string | null> {
812  if (!run) return null
813  const items = run.pending ?? []
814  if (items.length === 0) return null
815  if (!canDeliver(run.phase)) {
816    toastHeld($, items, run.phase)
817    return null
818  }
819  const text = items.map(item => item.text).join('\n\n')
820  if (via === 'tool') {
821    // Taken before the first await: a parallel tool call finds nothing left.
822    run = items.reduce((acc, item) => deliveredPending(acc, item), run)
823    // Taken: the text goes to the model whatever the bookkeeping does.
824    await markDelivered($, items, via).catch(error => log($, `could not record a delivery: ${String(error)}`).catch(() => undefined))
825
826    return text
827  }
828  if (flushingText !== null) return flushingText
829  flushingText = text
830  const submitVia: 'turn' | 'idle' = via
831  $.clock.after(300, () => void submitPending($, items, submitVia).catch(error => log($, `pending submit failed: ${String(error)}`).catch(() => undefined)))
832
833  return text
834}
835
836/** `isAskShown` false when the caller appends availStatusLines, which has its own ask-user line. */
837function statusText(now: number, isAskShown = true): string {
838  if (!run) return 'Autopilot is off.'
839
840  return [
841    `Autopilot: ${run.phase}${run.waitUntil ? ` until ${endClock(run.waitUntil, null)}` : ''} · ${formatLeft(run.until - now)} left · handoff at ${effectiveTrigger(run, ceiling)}% (asked ${run.threshold}%, ceiling ${ceiling}% below auto-compact) · restarts ${restartsText(run)}`,
842    ...waitingLines(now),
843    `Token limits: park at ${run.fiveHourStop}% of the 5-hour window, stop at ${run.weekStop}% of the week`,
844    ...(isAskShown && askOnNow() ? ['Asks the person: critical only'] : []),
845    `Role: ${run.role}`,
846    ...(run.skills.length ? [`Skills recognised in the role: ${run.skills.map(name => `/${name}`).join(', ')}`] : []),
847    ...(run.goal ? [`Goal: ${run.goal}${isGoalSet ? '' : ' (not set right now)'}`] : []),
848    home ? `Log: ${autopilotDir()}/${sessionId}.log` : 'Log: none (HOME is not set)',
849  ].join('\n')
850}
851
852const AVAIL_FAILED_TEXT = 'Autopilot: the command failed; nothing changed. Try again.'
853
854/** The first line of an /away, /back or /ask-user reply: what was recorded, and for whom. */
855function availHeadline(cmd: Exclude<AvailCommand, { kind: 'error' }>, until: number | null, offset: number | null): string {
856  const scope = cmd.global ? 'all sessions' : 'this session'
857  if (cmd.kind === 'away') return `Away until ${endClock(until ?? 0, offset)} (${scope}).`
858  if (cmd.kind === 'back') return `Back (${scope}).`
859
860  return `Ask-user ${cmd.on ? 'on' : 'off'} (${scope}).`
861}
862
863/**
864 * /away, /back and /ask-user: the person's own availability. Stored even with
865 * no run, so it applies to a later one (R4). Errors write nothing; a record
866 * written at its scope goes through the mode rule, which may release a wait,
867 * start a drain or queue a ping.
868 */
869async function setAvail($: EngineInterface, isPerson: boolean, cmd: AvailCommand, typed: string): Promise<{ text: string }> {
870  await syncId($)
871  if (!isPerson) {
872    await log($, `${typed} refused: not typed by the person`)
873
874    return { text: 'Only the person can say they are away or back, or turn asking on or off (type it in the prompt or over Remote Control).' }
875  }
876  if (cmd.kind === 'error') {
877    $.ui.toast(`Autopilot: ${cmd.message}`)
878
879    return { text: cmd.message }
880  }
881  if (cmd.global && !home) {
882    const text = 'Cannot use --global: HOME is not set, so there is no shared status file. Leave out --global to set it for this session.'
883    $.ui.toast(`Autopilot: ${text}`)
884
885    return { text }
886  }
887  // A clock end needs the offset; every reply shows times in it.
888  const offset = await utcOffset($)
889  // The process call took time: decide on the clock as it is now.
890  const now = await $.clock.now()
891  let until: number | null = null
892  if (cmd.kind === 'away') {
893    if (cmd.end.kind === 'clock' && offset === null) {
894      const text = 'Cannot read the local time zone; use a duration such as /away for 2h instead.'
895      $.ui.toast(`Autopilot: ${text}`)
896
897      return { text }
898    }
899    const end = awayUntil(cmd.end, now, offset ?? 0)
900    if (typeof end === 'string') {
901      $.ui.toast(`Autopilot: ${end}`)
902
903      return { text: end }
904    }
905    until = end
906  }
907
908  const session = await readSessionAvail($)
909  // The global file may have changed in another session since the last heartbeat.
910  const before = cmd.global ? await readGlobalAvail($, true) : session
911  const next = applyAvail(before, cmd, until, now)
912  try {
913    if (cmd.global) await writeGlobalAvail($, next)
914    else await writeSessionAvail($, next)
915  } catch (error) {
916    await log($, `could not record ${typed}: ${String(error)}`).catch(() => undefined)
917
918    return { text: 'Autopilot could not record the change; nothing changed.' }
919  }
920  const headline = availHeadline(cmd, until, offset)
921  await log($, `set by the person: ${headline}`).catch(() => undefined)
922
923  // The record is written: a failure from here on must not claim that nothing changed.
924  const mode = await refreshMode($).catch(async (error: unknown) => {
925    await log($, `recorded ${typed}, but applying it failed: ${String(error)}`).catch(() => undefined)
926
927    return undefined
928  })
929  if (mode === undefined) return { text: `${headline} Recorded; applying it to the run failed, so it takes effect at the next turn.` }
930  // refreshMode just read both records: the cached ones are current, no second read.
931  const eff = effective(run, sessionAvail, globalAvail)
932  // A session record beats the global one per field, even when older (R5).
933  const shadowed = cmd.global && (cmd.kind === 'ask-user' ? session?.askUser : session?.away)
934  const notes = [
935    ...(shadowed ? [`Note: this session has its own ${cmd.kind === 'ask-user' ? 'ask-user' : 'away'} setting, which wins over the global one here.`] : []),
936    ...(cmd.kind === 'away' && mode === 'plain'
937      ? ['Note: this run does not ask you (no --ask-user), so being away changes nothing until /ask-user on.']
938      : []),
939  ]
940
941  return { text: [headline, ...notes, ...availStatusLines(eff, mode, run, now, offset)].join('\n') }
942}
943
944const QUEUE_FAILED_TEXT =
945  'Autopilot could not queue the question. Decide it yourself within your role, record the decision for the handoff, and continue.'
946const NO_QUEUE_TEXT = 'Autopilot is not driving right now: no queue.'
947
948/** Why queue_question is refused in this mode, or null when it is accepted. */
949function queueRefusal(mode: Mode | null): string | null {
950  if (mode === 'queueing' || mode === 'overdue' || mode === 'draining') return null
951  if (mode === 'asking') {
952    return `The person can be asked right now: do not queue. If they are truly required, send one PushNotification with the question, call ${WAIT_TOOL} with reason user-answer (or user-input) and the question as note, and end your turn.`
953  }
954  if (mode === 'plain') return 'This run does not ask the person (no --ask-user): decide yourself within your role, record the decision for the handoff, and continue.'
955
956  return NO_QUEUE_TEXT
957}
958
959/**
960 * The person answered during a drain: their question leaves the queue (the
961 * tagged wait's, else the one the role section named). Runs before endWait,
962 * which drops the wait and its tag. Nothing removed (no id, or the id is no
963 * longer queued): nothing saved, nothing logged.
964 */
965async function removeAnswered($: EngineInterface): Promise<void> {
966  if (!run) return
967  const id = run.awaiting?.questionId ?? run.askingId ?? null
968  if (id === null) return
969  const before = run.questions?.length ?? 0
970  run = answeredQuestion(run)
971  if ((run.questions?.length ?? 0) === before) return
972  await save($)
973  await log($, `the person answered #${id}: ${run?.questions?.length ?? 0} questions left`)
974  await refreshMode($)
975}
976
977export const register: Register = on => {
978  on('session.start', async ($, e, next) => {
979    const rawHome = (await $.env.get('HOME')) ?? ''
980    home = rawHome.startsWith('/') ? rawHome : ''
981    // State and logs are the person's alone: the folders are closed to other users.
982    if (home) {
983      await $.process.run(['/bin/mkdir', '-p', autopilotDir(), statusDir()]).catch(() => undefined)
984      await $.process.run(['/bin/chmod', '700', autopilotDir(), statusDir()]).catch(() => undefined)
985    }
986    sessionId = await $.session.id()
987    run = ((await $.store.get(storeKey(sessionId))) as Run | undefined) ?? null
988    // The status applies even before a run starts (R4); a reload re-reads both records.
989    await readSessionAvail($)
990    await readGlobalAvail($, true)
991    await readCeiling($)
992    // Records of runs that finished long ago go; best effort, off the start's path.
993    void sweepFinished($).catch(() => undefined)
994
995    await $.command.register({
996      name: 'autopilot',
997      description: 'Run this session on autopilot with a fixed role; no args shows status, "extend|shorten [<time>] [--restarts N]" and "until 18:30|6:30pm" change the end, "0 0 stop" hands back',
998      argumentHint: '<time | until 18:30|6:30pm> <threshold%> [max restarts] "<role>" [--goal "…"] [--5h 95] [--week 80] [--ask-user] | extend|shorten [<time>] [--restarts N] | until 18:30|6:30pm | 0 0 stop',
999    })
1000    // Immediate: typed mid-turn they run at once, so stepping away never waits for a long turn.
1001    await $.command.register({
1002      name: 'away',
1003      description: 'Autopilot: you are away; critical questions are queued instead of asked, then asked one by one when you are back',
1004      argumentHint: 'for <90m|2h|1h30m> | until <15:00|6pm> [--global]',
1005      immediate: true,
1006    })
1007    await $.command.register({
1008      name: 'back',
1009      description: 'Autopilot: you are back; the queued questions are asked one by one',
1010      argumentHint: '[--global]',
1011      immediate: true,
1012    })
1013    await $.command.register({
1014      name: 'ask-user',
1015      description: 'Autopilot: turn asking you critical questions on or off (off queues them until you turn it on)',
1016      argumentHint: 'on|off [--global]',
1017      immediate: true,
1018    })
1019    await $.tool.register({
1020      name: RESTART_TOOL,
1021      description:
1022        'Autopilot only: after writing a handoff with /create-handoff-doc at the context threshold, call this with the handoff path. It clears the session and resumes from the handoff. Refused when autopilot is not wrapping up.',
1023      inputSchema: {
1024        type: 'object',
1025        properties: {
1026          handoffPath: {
1027            type: 'string',
1028            description: 'Path to the handoff .md under thoughts/shared/handoffs/ (absolute or relative to the project root)',
1029          },
1030        },
1031        required: ['handoffPath'],
1032      },
1033    })
1034    await $.tool.register({
1035      name: WAIT_TOOL,
1036      description:
1037        'Autopilot only: declares that this session is waiting for something (another session, a subagent, a workflow, a background task, the person), so autopilot stops nudging it. End your turn right after calling it; any new message wakes the session.',
1038      inputSchema: {
1039        type: 'object',
1040        properties: {
1041          reason: { type: 'string', enum: [...WAIT_REASONS], description: 'What the session waits for' },
1042          from: { type: 'string', description: 'Who the answer comes from: a session name, a subagent, a workflow' },
1043          note: { type: 'string', description: 'What is awaited, in one line (for the person: the question or the action)' },
1044          timeout: { type: 'string', description: 'When autopilot checks once whether the wait is stuck, e.g. "30m", "1h"' },
1045        },
1046        required: ['reason'],
1047      },
1048    })
1049    await $.tool.register({
1050      name: QUEUE_TOOL,
1051      description: `Autopilot only: while the person is away or has asking turned off, parks a critical question (one you would otherwise stop for with ${WAIT_TOOL} user-answer) for them to answer later, one by one. Keep working on what is not blocked by it. Refused when the person can be asked directly.`,
1052      inputSchema: {
1053        type: 'object',
1054        properties: {
1055          question: { type: 'string', description: 'The question or the action for the person, in one line, as they will read it' },
1056          kind: { type: 'string', enum: ['answer', 'action'], description: 'answer: a decision only the person can make; action: something the person must do' },
1057          provisional: { type: 'string', description: 'What you do meanwhile, if anything (prefer a reversible default)' },
1058        },
1059        required: ['question', 'kind'],
1060      },
1061    })
1062
1063    // Time and the 5-hour reset can come while the session sits idle (or after a reload lost the timers).
1064    $.clock.every(HEARTBEAT_MS, () => {
1065      void (async () => {
1066        await syncId($)
1067        // Before the idle guard: an away running out or a global change by another
1068        // session (R2) changes the mode mid-turn too. No run: nothing is ever queued.
1069        // refreshMode also saves at least every half heartbeat, which keeps the badge's
1070        // beat fresh for the combined ping (live sessions only); no second save here.
1071        await refreshMode($).catch(error => log($, `mode refresh failed: ${String(error)}`).catch(() => undefined))
1072        await combinedTick($).catch(async error => log($, `combined ping failed: ${String(error)}`))
1073        if (!run || isTurnRunning) return
1074        const now = await $.clock.now()
1075        // The clock read is an await: the run may have ended meanwhile.
1076        if (!run) return
1077        if ((run.phase === 'running' || run.phase === 'waiting' || run.phase === 'awaiting') && now >= run.until) {
1078          const instruction = await enterFinal($, 'time')
1079          if (instruction) queue($, instruction)
1080          return
1081        }
1082        if (run.phase === 'waiting' && run.waitUntil && now >= run.waitUntil) {
1083          // The resumed turn's first tool call, or its end, carries what is pending.
1084          await wake($)
1085          return
1086        }
1087        // A delivered prompt wakes a wait too: its timeout check can wait a beat.
1088        if (await flushPending($, 'idle')) return
1089        await checkWaitTimeout($, now)
1090      })().catch(error => log($, `heartbeat failed: ${String(error)}`).catch(() => undefined))
1091    })
1092
1093    return next(e)
1094  })
1095
1096  on('command.run', { command: 'autopilot' }, async ($, e) => {
1097    await syncId($)
1098    let now = await $.clock.now()
1099    const command = parseCommand(e.args)
1100
1101    if (command.kind === 'status') {
1102      const finished = run ? null : await loadFinished($, now)
1103      // The records first, so the status reads them fresh, not as of the last heartbeat.
1104      // A failed refresh must not hide the status: show it from the cached records.
1105      const mode = await refreshMode($).catch(() => null)
1106      // availStatusLines carries the one ask-user line, so statusText leaves its own out.
1107      const text = finished ? graceStatusText(finished, now) : statusText(now, false)
1108      // Away and ask-user show with or without a run, with their source (session or global).
1109      const offset = await utcOffset($)
1110      // refreshMode read both records (also with no run): the cached ones are current.
1111      const lines = availStatusLines(effective(run, sessionAvail, globalAvail), mode, run, now, offset)
1112
1113      return { text: [text, ...lines].join('\n') }
1114    }
1115    if (command.kind === 'error') return { text: command.message }
1116    if (command.kind === 'extend' || command.kind === 'shorten' || command.kind === 'until') {
1117      if (e.origin.kind !== 'composer' && e.origin.kind !== 'bridge') {
1118        await log($, `retime refused: origin ${e.origin.kind}`)
1119
1120        return { text: 'Only the person can change the autopilot end time (type it in the prompt or over Remote Control).' }
1121      }
1122      // No run, but one that finished on time or restarts a moment ago: it is judged as a run in its final phase.
1123      const finished = run ? null : await loadFinished($, now)
1124      const subject = run ?? finished?.run ?? null
1125      if (!subject) return { text: NOT_RUNNING_TEXT }
1126      const offset = await utcOffset($)
1127      // The process call took time: decide on the clock as it is now.
1128      now = await $.clock.now()
1129      // The token windows only matter for a revive: a weekly stop at its limit refuses, a 5-hour stop parks.
1130      const usage = subject.phase === 'final' ? await $.session.usage().catch(() => null) : null
1131      const target = targetChange(command, subject, now, offset)
1132      if ('refuse' in target) return { text: target.refuse }
1133      const action = retime(subject, target, now, usage ? limitAction(subject, usage.rateLimits, now) : null)
1134      if (action.kind === 'refuse') return { text: action.message }
1135
1136      const limit = (maxRestarts: number | null) => maxRestarts ?? 'unlimited'
1137      const restartsChange = action.maxRestarts === subject.maxRestarts ? '' : `, restart limit ${limit(subject.maxRestarts)} -> ${limit(action.maxRestarts)}`
1138      const note = target.note ? ` ${target.note}` : ''
1139      if (finished) {
1140        // A finished record is final/time or final/restarts, so retime can only revive it.
1141        if (action.kind !== 'revive') return { text: NOT_RUNNING_TEXT }
1142        // Back through the restart flow: the handoff is already written, so wrapping asks for the restart;
1143        // that restart is not counted. The wait is dropped: the limit checks after the resume park it again if needed.
1144        run = {
1145          ...finished.run,
1146          until: action.until,
1147          maxRestarts: action.maxRestarts,
1148          phase: 'wrapping',
1149          finalReason: null,
1150          idleTurns: 0,
1151          waitUntil: null,
1152          isGraceResume: true,
1153          graceSince: finished.run.finalAt,
1154          graceAsks: 0,
1155        }
1156        try {
1157          await save($)
1158        } catch (error) {
1159          run = null
1160          await save($).catch(() => undefined)
1161          await log($, `could not record the change: ${String(error)}`).catch(() => undefined)
1162
1163          return { text: 'Autopilot could not record the change; nothing changed.' }
1164        }
1165        await $.store.delete(finishedKey(sessionId)).catch(() => undefined)
1166        await log($, `revived after finishing (${finished.run.finalReason}) by ${command.kind}: to ${endClock(run.until, null)}${restartsChange}`)
1167        queue($, graceResumePrompt(run.until, offset))
1168
1169        return {
1170          text: `Autopilot end: ${endClock(run.until, offset)}, ${formatLeft(run.until - now)} left, restarts ${run.restarts}/${limit(run.maxRestarts)}.${note} Bringing the run back: the session will clear and resume from its handoff.`,
1171        }
1172      }
1173      // Stopped while the clock and usage were read.
1174      if (!run) return { text: NOT_RUNNING_TEXT }
1175      const wasReason = run.finalReason
1176      const previous = {
1177        until: run.until,
1178        maxRestarts: run.maxRestarts,
1179        phase: run.phase,
1180        finalReason: run.finalReason,
1181        idleTurns: run.idleTurns,
1182        waitUntil: run.waitUntil,
1183      }
1184      run.until = action.until
1185      run.maxRestarts = action.maxRestarts
1186      if (action.kind === 'revive') {
1187        run.phase = action.phase
1188        run.finalReason = null
1189        run.idleTurns = 0
1190        run.waitUntil = action.waitUntil
1191      }
1192      try {
1193        await save($)
1194      } catch (error) {
1195        // Not recorded: back to where it was, or the run would differ from what is stored.
1196        Object.assign(run, previous)
1197        await save($).catch(() => undefined)
1198        await log($, `could not record the change: ${String(error)}`).catch(() => undefined)
1199
1200        return { text: 'Autopilot could not record the change; nothing changed.' }
hooks/autopilot.ts 1705 lines
1import type {
2  Avail,
3  AvailCommand,
4  Awaiting,
5  AwayField,
6  BadgeAvail,
7  Command,
8  Effective,
9  FinalReason,
10  FinishedRecord,
11  LockOwner,
12  Mode,
13  Pending,
14  Phase,
15  Question,
16  QueueInput,
17  Run,
18  StartCommand,
19  TokenWindow,
20  WaitReason,
21} from '../types'
22
23export const RESTART_TOOL = 'restart_session'
24export const WAIT_TOOL = 'wait_for'
25/** The wait tool as the engine names it in a tool call. */
26export const FULL_WAIT_TOOL = `mcp__autopilot__${WAIT_TOOL}`
27export const WAIT_REASONS: readonly WaitReason[] = [
28  'user-input',
29  'user-answer',
30  'session-answer',
31  'session-ping',
32  'workflow-end',
33  'subagent-result',
34  'background-task',
35  'other',
36]
37const MAX_WAIT_FROM = 64
38const MAX_WAIT_NOTE = 200
39export const MAX_IDLE_TURNS = 2
40/**
41 * A threshold below this sits close to what a resume alone loads, so every
42 * handoff after the first fires RESUME_BUMP points later. At or above it the
43 * threshold stands as given.
44 */
45export const LOW_THRESHOLD = 50
46export const RESUME_BUMP = 10
47/**
48 * The trigger always fires this many points before auto-compact would: room
49 * for the handoff itself (reading state, writing the document).
50 */
51export const COMPACT_MARGIN = 10
52/** The ceiling when auto-compact is off or its threshold is unknown. */
53export const DEFAULT_CEILING = 90
54export const DEFAULT_FIVE_HOUR_STOP = 95
55export const DEFAULT_WEEK_STOP = 80
56/** Resume this long after the 5-hour window resets, and wait this long when the reset time is unknown. */
57export const RESET_MARGIN_MS = 2 * 60_000
58export const UNKNOWN_RESET_WAIT_MS = 30 * 60_000
59
60/**
61 * The highest context % a handoff may wait for: COMPACT_MARGIN below the
62 * session's auto-compact threshold, so a handoff always comes first.
63 */
64export function triggerCeiling(autoCompactTokens: number | undefined, windowTokens: number | undefined): number {
65  if (!autoCompactTokens || !windowTokens) return DEFAULT_CEILING
66
67  return Math.max(1, Math.floor((autoCompactTokens / windowTokens) * 100) - COMPACT_MARGIN)
68}
69
70/**
71 * The context % that triggers the handoff now: the person's threshold; under
72 * LOW_THRESHOLD, every handoff after the first RESUME_BUMP points later so a
73 * resumed session cannot loop; never above the ceiling below auto-compact.
74 */
75export function effectiveTrigger(run: Run, ceiling: number): number {
76  const isBumped = run.threshold < LOW_THRESHOLD && run.restarts > 0
77
78  return Math.min(isBumped ? run.threshold + RESUME_BUMP : run.threshold, ceiling)
79}
80
81/** "90m", "2h", "1h30m", "45" (minutes), units in any case ("2H") → milliseconds; null when unreadable. */
82export function parseDuration(text: string): number | null {
83  const ms = durationMs(text)
84  if (ms === null || !Number.isFinite(ms)) return null
85
86  return ms
87}
88
89function durationMs(text: string): number | null {
90  if (/^\d+$/.test(text)) return Number(text) * 60_000
91  const match = /^(?:(\d+)h)?(?:(\d+)m)?$/i.exec(text)
92  if (!match || (!match[1] && !match[2])) return null
93
94  return (Number(match[1] ?? 0) * 60 + Number(match[2] ?? 0)) * 60_000
95}
96
97/** A moved end must stay at least this far ahead of now. */
98const MIN_LEAD_MS = 60_000
99
100/** How long after finishing on time or restarts the person can still bring a run back. */
101export const GRACE_MS = 15 * 60_000
102
103/** Whether a run that finished for this reason can be brought back (a time-out or used-up restarts only). */
104export function isGraceEligible(reason: FinalReason | null): boolean {
105  return reason === 'time' || reason === 'restarts'
106}
107
108export function isGraceLive(record: FinishedRecord, now: number): boolean {
109  return now - record.finishedAt <= GRACE_MS
110}
111
112/** Whether a stored `finished:` value is a record still inside its grace period; anything malformed is not. */
113export function isLiveFinishedValue(value: unknown, now: number): boolean {
114  if (typeof value !== 'object' || value === null) return false
115  const finishedAt = (value as { finishedAt?: unknown }).finishedAt
116  if (typeof finishedAt !== 'number' || !Number.isFinite(finishedAt)) return false
117
118  return isGraceLive(value as FinishedRecord, now)
119}
120
121/** What `/autopilot` says when there is no run but a finished one can still be brought back. */
122export function graceStatusText(record: FinishedRecord, now: number): string {
123  const minutesLeft = Math.max(0, Math.ceil((GRACE_MS - (now - record.finishedAt)) / 60_000))
124
125  const ask = record.run.finalReason === 'restarts' ? 'extend --restarts N' : 'extend <time>'
126
127  return `Autopilot finished (${record.run.finalReason}) at ${endClock(record.finishedAt, null)}; /autopilot ${ask} within ${minutesLeft}m brings it back from its handoff.`
128}
129
130/** How many times a grace resume asks the session to restart before it gives up. */
131const MAX_GRACE_ASKS = 1
132
133/**
134 * What a finished main-loop turn means for a grace resume that is still
135 * waiting for its restart: ask once more, or pause. Any
136 * other run (an ordinary wrap-up included) is none of its business.
137 */
138export function graceTurnAction(run: Run): 'none' | 'ask' | 'pause' {
139  if (run.phase !== 'wrapping' || !run.isGraceResume) return 'none'
140
141  return (run.graceAsks ?? 0) < MAX_GRACE_ASKS ? 'ask' : 'pause'
142}
143
144/**
145 * Whether a grace resume's handoff is the current one: written at or after the
146 * final phase began (`ok`), older or unreadable (`stale`), or no start time to
147 * compare with (`unknown`, which fails closed).
148 */
149export function graceHandoffCheck(mtimeMs: number | null, since: number | undefined): 'ok' | 'stale' | 'unknown' {
150  if (since === undefined) return 'unknown'
151
152  return mtimeMs !== null && mtimeMs >= since ? 'ok' : 'stale'
153}
154
155/** The handoff path a restart call carries: `handoffPath`, or `handoff_path` when the model guessed that name; "" when neither. */
156export function handoffArg(input: unknown): string {
157  const fields = (typeof input === 'object' && input !== null ? input : {}) as { handoffPath?: unknown; handoff_path?: unknown }
158
159  return String(fields.handoffPath ?? fields.handoff_path ?? '')
160}
161
162/** The prompt that makes a finished run restart from the handoff it already wrote. */
163export function graceResumePrompt(until: number, offsetMinutes: number | null): string {
164  return `Autopilot: the person brought this run back until ${endClock(until, offsetMinutes)}. Call ${RESTART_TOOL} with {"handoffPath": "<path to the handoff .md>"}, the handoff you just wrote under thoughts/shared/handoffs/; autopilot will clear the session and resume from it. Do not start other work first.`
165}
166
167/** The most restarts a limit may reach. */
168const MAX_RESTARTS = 99
169
170/** The furthest the end of a run may be moved ahead of now. */
171export const MAX_AHEAD_MS = 7 * 24 * 60 * 60_000
172
173/** "18:30", "7:30" (24-hour) or "6pm", "6:30pm", "12am" (12-hour, no space, any case) → hours and minutes; null when unreadable. */
174export function parseClock(text: string): { hours: number; minutes: number } | null {
175  const match = /^(\d{1,2})(?::(\d{2}))?(am|pm)?$/i.exec(text)
176  if (!match) return null
177  const hours = Number(match[1])
178  const minutes = Number(match[2] ?? 0)
179  const suffix = match[3]?.toLowerCase()
180  if (minutes > 59) return null
181  if (!suffix) return match[2] === undefined || hours > 23 ? null : { hours, minutes }
182  if (hours < 1 || hours > 12) return null
183
184  return { hours: (hours % 12) + (suffix === 'pm' ? 12 : 0), minutes }
185}
186
187/** `date +%z` output ("+0300", "-0530") → minutes east of UTC; null when unreadable. */
188export function parseUtcOffset(text: string): number | null {
189  const match = /^([+-])(\d{2})(\d{2})$/.exec(text.trim())
190  if (!match) return null
191  const minutes = Number(match[2]) * 60 + Number(match[3])
192
193  return match[1] === '-' ? -minutes : minutes
194}
195
196/**
197 * The next instant strictly after `now` whose local clock (UTC + offset) reads hours:minutes.
198 * Today's offset is applied: a DST switch before the target shifts it by an hour.
199 */
200export function untilFromClock(hours: number, minutes: number, now: number, offsetMinutes: number): number {
201  const DAY_MS = 24 * 60 * 60_000
202  const localNow = now + offsetMinutes * 60_000
203  const localMidnight = localNow - (((localNow % DAY_MS) + DAY_MS) % DAY_MS)
204  const today = localMidnight + (hours * 60 + minutes) * 60_000 - offsetMinutes * 60_000
205
206  return today > now ? today : today + DAY_MS
207}
208
209export const NOT_RUNNING_TEXT = 'Autopilot is not running. Start a new run: /autopilot <time> <threshold%> "<role>".'
210
211/** Where a change to the run's end and restart limit lands. */
212export type RetimeTarget = { until: number; maxRestarts: number | null }
213
214export type RetimeAction =
215  | ({ kind: 'set' } & RetimeTarget)
216  | ({ kind: 'revive'; phase: 'running' | 'waiting'; waitUntil: number | null } & RetimeTarget)
217  | { kind: 'refuse'; message: string }
218
219type RetimeCommand = Extract<Command, { kind: 'extend' | 'shorten' | 'until' }>
220
221/**
222 * The end and restart limit a retime command asks for, with a note for the
223 * reply when the restarts part changed nothing or hit zero left.
224 */
225export function targetChange(
226  command: RetimeCommand,
227  run: Run,
228  now: number,
229  offset: number | null,
230): (RetimeTarget & { note: string | null }) | { refuse: string } {
231  if (command.kind === 'until') {
232    if (offset === null) return { refuse: 'Cannot read the local time zone; use /autopilot extend or shorten instead.' }
233
234    return { until: untilFromClock(command.hours, command.minutes, now, offset), maxRestarts: run.maxRestarts, note: null }
235  }
236
237  const isExtend = command.kind === 'extend'
238  const isRestartsOnly = command.deltaMs === 0
239  if (isRestartsOnly && run.until <= now && !endsForGood(run)) {
240    return {
241      refuse: isExtend
242        ? "The run's time is over; add time too, e.g. /autopilot extend 1h --restarts N."
243        : "The run's time is over; restarts cannot be changed on a finished time, add time with /autopilot extend.",
244    }
245  }
246  // A restarts-only change leaves the end alone (its past end is refused above); an extend counts from now when the end already passed.
247  const until = isExtend && !isRestartsOnly ? Math.max(run.until, now) + command.deltaMs : run.until - command.deltaMs
248  if (command.restarts === 0) return { until, maxRestarts: run.maxRestarts, note: null }
249
250  if (isExtend) {
251    const raised = (run.maxRestarts ?? run.restarts) + command.restarts
252
253    return { until, maxRestarts: Math.max(run.restarts, Math.min(raised, MAX_RESTARTS)), note: raised > MAX_RESTARTS ? `Restart limit capped at ${MAX_RESTARTS}.` : null }
254  }
255  if (run.maxRestarts === null) {
256    return { until, maxRestarts: null, note: 'Restarts are unlimited in this run; --restarts on shorten was ignored.' }
257  }
258  const lowered = run.maxRestarts - command.restarts
259  const note = lowered <= run.restarts ? `No restarts left after this change (${run.restarts} used).` : null
260
261  return { until, maxRestarts: Math.max(run.restarts, lowered), note }
262}
263
264const FINAL_REASON_TEXT: Record<string, string> = {
265  goal: 'its goal is met',
266  week: 'the weekly token limit was reached',
267  restarts: 'it used all its restarts',
268  done: 'the session reported its work complete',
269}
270
271/**
272 * What moving the run to `target` does: set it, bring a finished run back
273 * (a time-out, or an exhausted restart limit that was raised, with time left),
274 * or refuse. `limit` is what the token windows call for now (limitAction): a
275 * revive is refused at the weekly stop, and lands in `waiting` while a 5-hour
276 * wait is pending or the 5-hour window is at its stop.
277 */
278export function retime(run: Run | null, target: RetimeTarget, now: number, limit: LimitAction = null): RetimeAction {
279  if (!run) return { kind: 'refuse', message: NOT_RUNNING_TEXT }
280  if (!Number.isFinite(target.until) || target.until - now > MAX_AHEAD_MS) {
281    return { kind: 'refuse', message: 'The end can be at most 7 days from now.' }
282  }
283  const isFinal = run.phase === 'final'
284  if (endsForGood(run)) return { kind: 'refuse', message: finishingText(run.finalReason) }
285  if (target.until <= now) {
286    return { kind: 'refuse', message: 'The new end would be in the past. To hand back now: /autopilot 0 0 stop.' }
287  }
288  if (target.until - now < MIN_LEAD_MS) {
289    return { kind: 'refuse', message: 'The new end must be at least 1 minute ahead. To hand back now: /autopilot 0 0 stop.' }
290  }
291  const { until, maxRestarts } = target
292  if (!isFinal) return { kind: 'set', until, maxRestarts }
293  const isRestartsRaised = target.maxRestarts === null || target.maxRestarts > run.restarts
294  if (run.finalReason === 'restarts' && !isRestartsRaised) return { kind: 'refuse', message: finishingText('restarts') }
295
296  if (limit?.kind === 'week') {
297    return { kind: 'refuse', message: `The weekly token limit is at its stop (${run.weekStop}%); the run cannot continue.` }
298  }
299  if (limit?.kind === 'five-hour') return { kind: 'revive', phase: 'waiting', waitUntil: limit.waitUntil, until, maxRestarts }
300  if (run.waitUntil && run.waitUntil > now) return { kind: 'revive', phase: 'waiting', waitUntil: run.waitUntil, until, maxRestarts }
301
302  return { kind: 'revive', phase: 'running', waitUntil: null, until, maxRestarts }
303}
304
305/** A final handoff that more time or restarts cannot undo (anything but a time-out or used-up restarts). */
306function endsForGood(run: Run): boolean {
307  return run.phase === 'final' && run.finalReason !== 'time' && run.finalReason !== 'restarts'
308}
309
310function finishingText(reason: FinalReason | null): string {
311  const reasonText = (reason && FINAL_REASON_TEXT[reason]) || 'it is wrapping up'
312
313  return `Autopilot is finishing because ${reasonText}; more time does not change that. Start a new run after it hands back.`
314}
315
316/** The furthest instant a Date can print; a value past it is broken or forged. */
317const MAX_DATE_MS = 8_640_000_000_000_000
318
319/** `HH:MM (HH:MM UTC)` on the clock `offsetMinutes` east of UTC, or `HH:MM UTC` when the offset is unknown. */
320export function endClock(until: number, offsetMinutes: number | null): string {
321  if (!Number.isFinite(until) || Math.abs(until) > MAX_DATE_MS) return 'an unreadable time'
322  const utc = new Date(until).toISOString().slice(11, 16)
323  if (offsetMinutes === null) return `${utc} UTC`
324
325  return `${new Date(until + offsetMinutes * 60_000).toISOString().slice(11, 16)} (${utc} UTC)`
326}
327
328/**
329 * The prompt that brings a finished run back to work. `restarts` is given when
330 * the run was revived from used-up restarts: the text then names them, not the time.
331 */
332export function revivePrompt(until: number, offsetMinutes: number | null, restarts?: { used: number; limit: number | null }): string {
333  const tail = 'The final handoff is cancelled: do not write it now. Keep working within your role.'
334  const when = endClock(until, offsetMinutes)
335  if (restarts) {
336    return `Autopilot: the person added restarts (now ${restarts.used}/${restarts.limit ?? 'unlimited'}); the run continues until ${when}. ${tail}`
337  }
338
339  return `Autopilot: the person extended this run until ${when}. ${tail}`
340}
341
342/** Takes `--name value` out of the arguments; a quoted value may hold spaces. */
343function takeFlag(text: string, name: string): { value: string | null; rest: string } {
344  const pattern = new RegExp(`\\s--${name}\\s+(?:"([^"]*)"|“([^”]*)”|«([^»]*)»|'([^']*)'|(\\S+))`)
345  const match = pattern.exec(` ${text}`)
346  if (!match) return { value: null, rest: text }
347  const value = match[1] ?? match[2] ?? match[3] ?? match[4] ?? match[5] ?? ''
348
349  return { value, rest: ` ${text}`.replace(match[0], '').trim() }
350}
351
352/** Takes every `--name` switch (no value) out of the arguments; whether there was one. */
353function takeSwitch(text: string, name: string): { isOn: boolean; rest: string } {
354  const pattern = new RegExp(`\\s--${name}(?=\\s|$)`, 'g')
355  const rest = ` ${text}`.replace(pattern, '')
356
357  return { isOn: rest.length !== text.length + 1, rest: rest.trim() }
358}
359
360function percentFlag(value: string | null, fallback: number, label: string): number | string {
361  if (value === null) return fallback
362  const number = Number(value)
363  if (!Number.isFinite(number) || number < 1 || number > 100) return `${label} must be a percentage between 1 and 100.`
364
365  return number
366}
367
368const ROLE_QUOTES: Record<string, string> = { '"': '"', '“': '”', '«': '»', "'": "'" }
369
370const FLAG_NAMES = ['--goal', '--5h', '--week']
371/** Flags that take no value. */
372const SWITCH_NAMES = ['--ask-user']
373const isSpace = (char: string | undefined): boolean => char !== undefined && /\s/.test(char)
374
375/**
376 * For each position, whether the text from there to the end is only flag
377 * syntax, the same as `^(\s+--(goal|5h|week)\s+(<quoted value>|\S+)|\s+--ask-user(?=\s|$))*\s*$`
378 * with the value quoted in any supported style. Read in one pass from the end,
379 * each position's answer from one further on, so it stays linear: a regex
380 * tried at every closing quote would rescan the tail for each of them.
381 */
382function flagsOnlyFrom(text: string): Uint8Array {
383  const size = text.length
384  const isFlagsOnly = new Uint8Array(size + 1)
385  const nextSpace = new Int32Array(size + 1)
386  const nextNonSpace = new Int32Array(size + 1)
387  const nextCloser: Record<string, Int32Array> = {}
388  for (const closer of Object.values(ROLE_QUOTES)) nextCloser[closer] = new Int32Array(size + 1).fill(-1)
389  isFlagsOnly[size] = 1
390  nextSpace[size] = size
391  nextNonSpace[size] = size
392
393  for (let at = size - 1; at >= 0; at -= 1) {
394    const char = text.charAt(at)
395    const isWhitespace = isSpace(char)
396    nextSpace[at] = isWhitespace ? at : (nextSpace[at + 1] ?? size)
397    nextNonSpace[at] = isWhitespace ? (nextNonSpace[at + 1] ?? size) : at
398    for (const [closer, next] of Object.entries(nextCloser)) next[at] = char === closer ? at : (next[at + 1] ?? -1)
399    if (!isWhitespace) continue
400
401    const flagAt = nextNonSpace[at] ?? size
402    if (flagAt === size) {
403      isFlagsOnly[at] = 1
404      continue
405    }
406    // A switch ends at the next space or the end; what follows it decides.
407    const switchName = SWITCH_NAMES.find(flag => text.startsWith(flag, flagAt))
408    const switchEnd = flagAt + (switchName?.length ?? 0)
409    if (switchName && (switchEnd === size || isSpace(text[switchEnd]))) {
410      isFlagsOnly[at] = isFlagsOnly[switchEnd] ?? 0
411      continue
412    }
413    const name = FLAG_NAMES.find(flag => text.startsWith(flag, flagAt))
414    if (!name || !isSpace(text[flagAt + name.length])) continue
415    const valueAt = nextNonSpace[flagAt + name.length] ?? size
416    if (valueAt === size) continue
417
418    // A bare word runs to the next space; a quoted value to its closing quote.
419    if (isFlagsOnly[nextSpace[valueAt] ?? size]) {
420      isFlagsOnly[at] = 1
421      continue
422    }
423    const closer = ROLE_QUOTES[text.charAt(valueAt)]
424    const closeAt = closer ? (nextCloser[closer]?.[valueAt + 1] ?? -1) : -1
425    if (closeAt !== -1 && isFlagsOnly[closeAt + 1]) isFlagsOnly[at] = 1
426  }
427
428  return isFlagsOnly
429}
430
431/**
432 * Splits a quoted role off the arguments: `head` runs through the role's
433 * closing quote, `rest` is what follows, the only place flags are read from.
434 * The role closes at the first closing quote after which only flags follow,
435 * so a quote or apostrophe inside the role stays in it. null when the role
436 * is not quoted.
437 */
438function splitQuotedRole(text: string): { head: string; rest: string } | null {
439  const match = /^(?:until\s+)?\S+\s+\d{1,3}%?\s+(?:\d{1,2}\s+)?(["“«'])/i.exec(text)
440  if (!match) return null
441  const opener = match[1] ?? ''
442  const closer = ROLE_QUOTES[opener] ?? opener
443  const isFlagsOnly = flagsOnlyFrom(text)
444  for (let closeAt = text.indexOf(closer, match[0].length); closeAt !== -1; closeAt = text.indexOf(closer, closeAt + 1)) {
445    if (isFlagsOnly[closeAt + 1]) return { head: text.slice(0, closeAt + 1), rest: text.slice(closeAt + 1) }
446  }
447
448  // Unclosed, or no closing quote is followed by flags alone: everything after the opening quote is the role.
449  return { head: text, rest: '' }
450}
451
452const USAGE =
453  'Usage: /autopilot <time | until <clock>> <threshold%> [max restarts] "<role>" [--goal "<condition>"] [--5h 95] [--week 80] [--ask-user]  ·  /autopilot extend [<time>] [--restarts N]  ·  /autopilot shorten [<time>] [--restarts N]  ·  /autopilot until HH:MM  ·  /autopilot 0 0 stop'
454const MAX_ECHOED = 40
455
456/** The person's raw text as an error reply shows it: invisible characters out, capped at 40 characters. */
457function echoed(raw: string): string {
458  const text = raw.replace(INVISIBLE_ALL, '')
459
460  return text.length > MAX_ECHOED ? `${text.slice(0, MAX_ECHOED)}…` : text
461}
462
463const CLOCK_TEXT ='Give the end as HH:MM (24-hour) or with am/pm, e.g. until 18:30 or until 6:30pm (local time).'
464const RESTARTS_FLAG_TEXT = '--restarts needs a whole number from 1 to 99.'
465
466/**
467 * `/autopilot` arguments: nothing (status), `stop` or `0 0 stop`, or
468 * `<duration> <threshold%> [max restarts] "<role>"` with optional flags
469 * `--goal "<condition>"`, `--5h <%>`, `--week <%>`, `--ask-user`. No max means as many
470 * restarts as the time allows.
471 */
472export function parseCommand(args: string): Command {
473  const text = args.trim()
474  if (!text) return { kind: 'status' }
475  if (/^(0\s+0\s+)?stop$/i.test(text)) return { kind: 'stop' }
476
477  const dashed = /^--(extend|shorten|until)\b\s*(.*)$/i.exec(text)
478  if (dashed) {
479    const rest = echoed((dashed[2] ?? '').trim())
480
481    return { kind: 'error', message: `Did you mean /autopilot ${dashed[1]?.toLowerCase()}${rest ? ` ${rest}` : ''}?` }
482  }
483  const retimeMatch = /^(extend|shorten)(?:\s+([\s\S]*))?$/i.exec(text)
484  if (retimeMatch) {
485    const kind = retimeMatch[1]?.toLowerCase() === 'extend' ? 'extend' : 'shorten'
486    const usage = { kind: 'error', message: `Usage: /autopilot ${kind} [<time>] [--restarts N]` } as const
487    const restartsFlag = takeFlag(retimeMatch[2] ?? '', 'restarts')
488    const rawTime = restartsFlag.rest
489    const restarts = restartsFlag.value === null ? 0 : Number(restartsFlag.value)
490    if (restartsFlag.value !== null && (!/^\d{1,2}$/.test(restartsFlag.value) || restarts < 1)) {
491      return { kind: 'error', message: RESTARTS_FLAG_TEXT }
492    }
493    if (/\s|^--/.test(rawTime)) return usage
494    if (!rawTime && restarts === 0) return usage
495    if (!rawTime) return { kind, deltaMs: 0, restarts }
496
497    const deltaMs = parseDuration(rawTime)
498    if (deltaMs === null || deltaMs <= 0) {
499      return { kind: 'error', message: `Cannot read the time "${echoed(rawTime)}" (try 90m, 2h, 1h30m).` }
500    }
501
502    return { kind, deltaMs, restarts }
503  }
504  if (/^until$/i.test(text)) return { kind: 'error', message: 'Usage: /autopilot until HH:MM' }
505  if (/^until\s/i.test(text) && /\s--restarts(?=\s|$)/i.test(text)) {
506    return { kind: 'error', message: 'until takes no --restarts; use /autopilot extend --restarts N.' }
507  }
508  // `until <clock>` alone moves the end; with more after it, it is a start with an end time.
509  const untilMatch = /^until\s+(\S+)$/i.exec(text)
510  if (untilMatch) {
511    const clock = parseClock(untilMatch[1] ?? '')
512    if (!clock) return { kind: 'error', message: CLOCK_TEXT }
513
514    return { kind: 'until', ...clock }
515  }
516
517  return parseStart(text)
518}
519
520/** A start: `<time | until <clock>> <threshold%> [max restarts] "<role>"` with the flags anywhere outside the role. */
521function parseStart(args: string): Command {
522  let text = args
523  // Flags are read only outside a quoted role: a role may not carry its own --goal.
524  const quoted = splitQuotedRole(text)
525  let flagText = quoted ? quoted.rest : text
526  const goalFlag = takeFlag(flagText, 'goal')
527  flagText = goalFlag.rest
528  const fiveHourFlag = takeFlag(flagText, '5h')
529  flagText = fiveHourFlag.rest
530  const weekFlag = takeFlag(flagText, 'week')
531  flagText = weekFlag.rest
532  // After the valued flags, so a quoted --goal holding the word keeps it.
533  const askUserFlag = takeSwitch(flagText, 'ask-user')
534  flagText = askUserFlag.rest
535  text = quoted ? `${quoted.head}${flagText}`.trim() : flagText
536
537  const fiveHourStop = percentFlag(fiveHourFlag.value, DEFAULT_FIVE_HOUR_STOP, '--5h')
538  if (typeof fiveHourStop === 'string') return { kind: 'error', message: fiveHourStop }
539  const weekStop = percentFlag(weekFlag.value, DEFAULT_WEEK_STOP, '--week')
540  if (typeof weekStop === 'string') return { kind: 'error', message: weekStop }
541  const goal = goalFlag.value?.trim() || null
542  if (goalFlag.value !== null && !goal) return { kind: 'error', message: '--goal needs a condition in quotes.' }
543
544  const match = /^(?:until\s+(\S+)|(?!until\s)(\S+))\s+(\d{1,3})%?\s+(?:(\d{1,2})\s+)?(["'“«][\s\S]+|[^\d\s][\s\S]*)$/i.exec(text)
545  if (!match) return { kind: 'error', message: USAGE }
546  const [, rawClock, rawDuration = '', rawThreshold = '', rawRestarts, rawRole = ''] = match
547  const clock = rawClock === undefined ? null : parseClock(rawClock)
548  if (rawClock !== undefined && !clock) return { kind: 'error', message: CLOCK_TEXT }
549  const ms = parseDuration(rawDuration)
550  if (!clock && (ms === null || ms <= 0)) {
551    return { kind: 'error', message: `Cannot read the time "${echoed(rawDuration)}" (try 90m, 2h, 1h30m).` }
552  }
553  const end: StartCommand['end'] = clock ? { kind: 'clock', ...clock } : { kind: 'duration', ms: ms ?? 0 }
554  const threshold = Number(rawThreshold)
555  if (threshold < 1 || threshold > 95) return { kind: 'error', message: 'The context threshold must be between 1 and 95 (%).' }
556  const role = rawRole.trim().replace(/^["'“«]|["'”»]$/g, '').trim()
557  if (role.length < 10) {
558    return { kind: 'error', message: 'Give the role in a sentence or more: who the session is and what it is responsible for.' }
559  }
560
561  return {
562    kind: 'start',
563    end,
564    threshold,
565    maxRestarts: rawRestarts === undefined ? null : Number(rawRestarts),
566    role,
567    goal,
568    fiveHourStop,
569    weekStop,
570    askUser: askUserFlag.isOn,
571  }
572}
573
574/**
575 * The skills a role names as `/name`, kept only when the session has a
576 * command of that name that is not built in (a skill, a plugin's command).
577 */
578export function namedSkills(role: string, skillNames: readonly string[]): string[] {
579  const known = new Set(skillNames)
580  const found: string[] = []
581  for (const match of role.matchAll(/(?:^|[\s("'“«`])\/([a-z0-9][\w:.-]*)/gi)) {
582    const name = trimTrailingPunctuation(match[1] ?? '')
583    if (name && known.has(name) && !found.includes(name)) found.push(name)
584  }
585
586  return found
587}
588
589const TRAILING_PUNCTUATION = '.,;:!?)'
590
591/** Drops trailing `.,;:!?)` in one linear pass (a regex here backtracks on long runs). */
592function trimTrailingPunctuation(text: string): string {
593  let end = text.length
594  while (end > 0 && TRAILING_PUNCTUATION.includes(text.charAt(end - 1))) end -= 1
595
596  return text.slice(0, end)
597}
598
599/** Whether another handoff restart is allowed; time alone limits a run with no max. */
600export function canRestart(run: Run): boolean {
601  return run.maxRestarts === null || run.restarts < run.maxRestarts
602}
603
604export function restartsText(run: Run): string {
605  return `${run.restarts}/${run.maxRestarts ?? '∞'}`
606}
607
608export type LimitAction = { kind: 'week' } | { kind: 'five-hour'; waitUntil: number } | null
609
610/**
611 * What the token windows call for: the weekly one past its stop ends the run
612 * for good; the 5-hour one past its stop parks it until the window resets.
613 */
614export function limitAction(run: Run, windows: readonly TokenWindow[], now: number): LimitAction {
615  const week = windows.find(window => window.kind === 'seven_day')
616  if (week && week.percentUsed >= run.weekStop) return { kind: 'week' }
617
618  const fiveHour = windows.find(window => window.kind === 'five_hour')
619  if (!fiveHour || fiveHour.percentUsed < run.fiveHourStop) return null
620  const resetsAt = fiveHour.resetsAt ? Date.parse(fiveHour.resetsAt) : Number.NaN
621
622  return {
623    kind: 'five-hour',
624    waitUntil: Number.isFinite(resetsAt) && resetsAt > now ? resetsAt + RESET_MARGIN_MS : now + UNKNOWN_RESET_WAIT_MS,
625  }
626}
627
628export type TurnAction = 'continue' | 'wrapup' | 'final' | 'pause' | 'finish' | 'resume-done' | 'none'
629
630/**
631 * What to do when a main-loop turn ends, from the run, the context fill, the
632 * time, whether the turn called any tool, and the ceiling below auto-compact.
633 * The token windows are judged apart (limitAction), before this.
634 */
635export function afterTurn(
636  run: Run,
637  now: number,
638  percent: number | null,
639  calledTools: boolean,
640  ceiling = DEFAULT_CEILING,
641): TurnAction {
642  // The turn that called the restart tool ends before /clear runs: queue nothing,
643  // or a prompt could reach the fresh conversation ahead of the resume.
644  if (run.phase === 'paused' || run.phase === 'restarting' || run.phase === 'waiting') return 'none'
645  // The session declared a wait: no nudge; the next turn that starts wakes it.
646  // The context trigger and the limits are checked again on that turn; time is the 30 s clock's.
647  if (run.phase === 'awaiting') return 'none'
648  // The turn /resume-handoff-doc started: the resume ran; back to work.
649  if (run.phase === 'resuming') return 'resume-done'
650  // A wrap-up turn ended; the model either called the restart tool or not.
651  if (run.phase === 'wrapping') return 'none'
652  if (run.phase === 'final') return 'finish'
653
654  if (now >= run.until) return 'final'
655  if (percent !== null && percent >= effectiveTrigger(run, ceiling)) return canRestart(run) ? 'wrapup' : 'final'
656  if (!calledTools && run.idleTurns + 1 >= MAX_IDLE_TURNS) return 'pause'
657
658  return 'continue'
659}
660
661/** Whether a tool result mid-turn should carry the wrap-up instruction now. */
662export function wrapMidTurn(
663  run: Run,
664  now: number,
665  percent: number | null,
666  ceiling = DEFAULT_CEILING,
667): 'wrapup' | 'final' | null {
668  // A resume turn often does real work right away: it is watched as well.
669  if (run.phase !== 'running' && run.phase !== 'resuming') return null
670  if (now >= run.until) return 'final'
671  if (percent !== null && percent >= effectiveTrigger(run, ceiling)) return canRestart(run) ? 'wrapup' : 'final'
672
673  return null
674}
675
676/** Phases in which the session must be able to end its turn: a goal's Stop hook may not hold it. */
677export function shouldDropStopBlock(phase: Phase): boolean {
678  return phase === 'wrapping' || phase === 'restarting' || phase === 'final' || phase === 'awaiting'
679}
680
681/**
682 * Whether autopilot answers AskUserQuestion and marks refused actions as
683 * deferred: not while paused or waiting, when the person is in control.
684 * A declared wait (awaiting) still counts as away.
685 */
686export function autoAnswersQuestions(phase: Phase): boolean {
687  return phase !== 'paused' && phase !== 'waiting'
688}
689
690/** A free-text field: line breaks to a space, other invisible characters out, trimmed, capped; empty is null. `cut` says the cap shortened it. */
691function waitField(value: unknown, name: string, max: number): { value: string | null; cut: boolean } | { error: string } {
692  if (value === undefined) return { value: null, cut: false }
693  if (typeof value !== 'string') return { error: `${name} must be a string.` }
694  const whole = value.replace(LINE_BREAKS, ' ').replace(INVISIBLE_ALL, '').trim()
695  const text = whole.slice(0, max).trim()
696
697  return { value: text || null, cut: whole.length > max }
698}
699
700/**
701 * The wait_for tool's input as a wait starting now: a known reason, optional
702 * `from` and `note`, and an optional `timeout` ("30m", "1h") after which
703 * autopilot checks once, never later than the run's end.
704 */
705export function parseWaitInput(
706  input: unknown,
707  now: number,
708  until: number,
709): { kind: 'ok'; awaiting: Awaiting } | { kind: 'error'; message: string } {
710  if (!input || typeof input !== 'object') return { kind: 'error', message: 'wait_for needs an input object.' }
711  const fields = input as Record<string, unknown>
712  const reason = WAIT_REASONS.find(known => known === fields.reason)
713  if (!reason) return { kind: 'error', message: `reason must be one of: ${WAIT_REASONS.join(', ')}.` }
714  const from = waitField(fields.from, 'from', MAX_WAIT_FROM)
715  if ('error' in from) return { kind: 'error', message: from.error }
716  const note = waitField(fields.note, 'note', MAX_WAIT_NOTE)
717  if ('error' in note) return { kind: 'error', message: note.error }
718
719  let timeoutAt: number | null = null
720  if (fields.timeout !== undefined) {
721    if (typeof fields.timeout !== 'string') return { kind: 'error', message: 'timeout must be a string such as "30m" or "1h".' }
722    const ms = parseDuration(fields.timeout.trim())
723    if (ms === null || ms <= 0) return { kind: 'error', message: `Cannot read the timeout ${quoteValue(fields.timeout)} (try 30m, 1h, 1h30m).` }
724    timeoutAt = Math.min(now + ms, until)
725  }
726
727  return { kind: 'ok', awaiting: { reason, from: from.value, note: note.value, since: now, timeoutAt, pinged: false } }
728}
729
730/** Whether a main-loop tool call ends a declared wait: any tool but the wait tool itself means the session went on working. */
731export function endsWait(phase: Phase, tool: string): boolean {
732  return phase === 'awaiting' && tool !== FULL_WAIT_TOOL
733}
734
735/**
736 * Why wait_for is refused in this phase, or null when allowed: while running,
737 * and again while awaiting (a repeat replaces the wait).
738 */
739export function waitPhaseRefusal(phase: Phase): string | null {
740  if (phase === 'running' || phase === 'awaiting') return null
741  if (phase === 'resuming') {
742    return `Autopilot is finishing the resume from the handoff: end this turn normally; you can call ${WAIT_TOOL} in the next turn.`
743  }
744
745  return 'Autopilot is not driving right now: no wait needed.'
746}
747
748const PERSON_REASONS: readonly WaitReason[] = ['user-answer', 'user-input']
749
750/**
751 * Why a wait is refused, or null when allowed. Waiting for the person needs a
752 * mode that asks them (asking, draining), and then the question or action as
753 * its note; while they cannot answer, the question goes to the queue instead.
754 */
755export function waitRefusal(awaiting: Awaiting, mode: Mode): string | null {
756  if (!PERSON_REASONS.includes(awaiting.reason)) return null
757  if (mode === 'plain') {
758    return 'This run does not wait for the person (no --ask-user): decide yourself, or send one PushNotification and continue with other work.'
759  }
760  if (mode === 'queueing') {
761    return `The person cannot answer right now (away, or asking is off): do not wait for them. Call ${QUEUE_TOOL} with the question instead, then keep working on what is not blocked by it.`
762  }
763  if (mode === 'overdue') {
764    return `The person's away time is over, but they have not written in this session yet, so they are not asked now: do not wait for them. Call ${QUEUE_TOOL} with the question instead; autopilot asks the queued questions one by one once they write. Keep working on what is not blocked by it.`
765  }
766  if (!awaiting.note) return `A wait for ${awaiting.reason} needs the question or the action for the person as its note.`
767
768  return null
769}
770
771/** The wait as one short line: reason, who from, how long, the note. */
772export function waitText(awaiting: Awaiting, now: number): string {
773  return [
774    awaiting.reason,
775    ...(awaiting.from ? [` ← ${quoteValue(awaiting.from)}`] : []),
776    ` · ${formatLeft(now - awaiting.since)}`,
777    ...(awaiting.note ? [` — ${quoteValue(awaiting.note)}`] : []),
778  ].join('')
779}
780
781/** The one check autopilot sends when a declared wait runs past its timeout. */
782export function waitTimeoutPrompt(awaiting: Awaiting, now: number): string {
783  const from = awaiting.from ? ` from ${quoteValue(awaiting.from)}` : ''
784  const note = awaiting.note ? ` (${quoteValue(awaiting.note)})` : ''
785
786  return `Autopilot: you have waited ${formatLeft(now - awaiting.since)} for ${awaiting.reason}${from}${note}. Check whether it arrived or is stuck; escalate within your role if needed (PushNotification for the person), then continue or call ${WAIT_TOOL} again.`
787}
788
789/** Above this many queued questions queue_question still accepts, with a warning. */
790export const QUEUE_WARN = 20
791export const QUEUE_TOOL = 'queue_question'
792/** The queue tool as the engine names it in a tool call. */
793export const FULL_QUEUE_TOOL = `mcp__autopilot__${QUEUE_TOOL}`
794const MAX_QUESTION = 500
795const MAX_PROVISIONAL = 200
796const QUESTION_KINDS: readonly Question['kind'][] = ['answer', 'action']
797
798/** A leading `#k` tag: digits not run on into a word, then any separator. */
799const LEADING_TAG = /^\s*#(\d+)(?!\w)[\s:.)–—-]*/
800
801/** The text without a leading `#k` tag the model may have copied from a wait note. */
802export function stripTag(text: string): string {
803  return text.replace(LEADING_TAG, '').trim()
804}
805
806/**
807 * The queue_question tool's input: the question (tag stripped), its kind and
808 * an optional provisional decision; a string is the error the model reads.
809 */
810export function parseQueueInput(input: unknown): QueueInput | string {
811  if (!input || typeof input !== 'object') return `${QUEUE_TOOL} needs an input object.`
812  const fields = input as Record<string, unknown>
813  const question = waitField(fields.question, 'question', MAX_QUESTION)
814  if ('error' in question) return question.error
815  const text = stripTag(question.value ?? '')
816  if (!text) return 'question must be the question or the action for the person, in a sentence or two.'
817  const kind = QUESTION_KINDS.find(known => known === fields.kind)
818  if (!kind) return 'kind must be answer (the person decides) or action (the person must do something).'
819  const provisional = fields.provisional === null ? { value: null, cut: false } : waitField(fields.provisional, 'provisional', MAX_PROVISIONAL)
820  if ('error' in provisional) return provisional.error
821  const base = { question: text, kind, provisional: provisional.value }
822
823  return question.cut || provisional.cut ? { ...base, cut: true } : base
824}
825
826/**
827 * The next question id, never reused within the run: the stored counter, and
828 * never at or below an id in the queue or the one being asked or waited on
829 * (an older run has no counter).
830 */
831function nextQuestionId(run: Run): number {
832  const ids = (run.questions ?? []).map(question => question.id)
833  const inUse = Math.max(0, ...ids, run.askingId ?? 0, run.awaiting?.questionId ?? 0) + 1
834
835  return Math.max(run.nextQuestionId ?? 1, inUse)
836}
837
838/** Appends a question as parseQueueInput returned it (tag already stripped); the same text again keeps the queued one. Nothing is ever dropped. */
839export function addQuestion(run: Run, input: QueueInput, now: number): { run: Run; id: number; isNew: boolean; warn: boolean } {
840  const questions = run.questions ?? []
841  const text = input.question.trim()
842  const same = questions.find(question => question.text === text)
843  if (same) return { run, id: same.id, isNew: false, warn: questions.length > QUEUE_WARN }
844
845  const id = nextQuestionId(run)
846  const next = [...questions, { id, text, kind: input.kind, provisional: input.provisional, at: now }]
847
848  return { run: { ...run, questions: next, nextQuestionId: id + 1 }, id, isNew: true, warn: next.length > QUEUE_WARN }
849}
850
851/** The queued question a wait note names with a leading `#k`; null when untagged or not queued. */
852export function questionIdFromNote(note: string | null, questions: readonly Question[]): number | null {
853  const match = note ? LEADING_TAG.exec(note) : null
854  if (!match) return null
855  const id = Number(match[1])
856
857  return questions.some(question => question.id === id) ? id : null
858}
859
860/**
861 * The run after the person answered during a drain: the wait's tagged
862 * question goes, else the one the drain asked. No id, nothing removed. A
863 * drain prompt still pending goes too: it names a question now answered.
864 */
865export function answeredQuestion(run: Run): Run {
866  const id = run.awaiting?.questionId ?? run.askingId
867  const questions = run.questions ?? []
868  const left = questions.filter(question => question.id !== id)
869  if (left.length === questions.length) return run
870  const pending = run.pending ? { pending: run.pending.filter(entry => entry.kind !== 'drain') } : {}
871  if (left.length === 0) return { ...run, ...pending, questions: left, drain: false, askingId: undefined }
872
873  return { ...run, ...pending, questions: left, askingId: run.askingId === id ? undefined : run.askingId }
874}
875
876/** What the model reads when its wait for the person ends because the person is away or asking is off. */
877export const RELEASE_PROMPT = `Autopilot: the person is not available now, so your wait for them has ended. The question is queued and will be asked when they are back; do not ask it again. Keep working on what is not blocked by it; new critical questions go through ${QUEUE_TOOL}.`
878
879/** The `continue` text when a released wait had no note: nothing was queued, so the model queues the question itself. */
880export const RELEASE_UNQUEUED_PROMPT = `Autopilot: the person is not available now, so your wait for them has ended. Your question was NOT queued because the wait had no note. Call ${QUEUE_TOOL} with it now so it is asked when they are back; do not ask it directly. Keep working on what is not blocked by it.`
881
882/** "1 critical question is" / "N critical questions are": the count every ping and toast uses. */
883export function criticalCount(n: number): string {
884  return n === 1 ? '1 critical question is' : `${n} critical questions are`
885}
886
887/**
888 * How to ask one queued question: as text, then a wait whose note starts with
889 * its #k tag. Shared by drainPrompt and the draining role section (task 05).
890 */
891export function askQuestionText(q: Question): string {
892  const meanwhile = q.provisional ? ` (meanwhile you went with: ${quoteValue(q.provisional, MAX_PROVISIONAL)})` : ''
893  const reason = q.kind === 'action' ? 'user-input' : 'user-answer'
894
895  return `Ask question #${q.id} now, and only it: ${quoteValue(q.text, MAX_QUESTION)}${meanwhile}. Write it to the person as text, call ${WAIT_TOOL} with reason ${reason} and a note that starts with "#${q.id}", then end your turn.`
896}
897
898/** The prompt for the one ping when a session's away time ends with questions queued (spec §7.2). */
899export function expiryPingText(n: number): string {
900  return `Autopilot: the away time is over; ${criticalCount(n)} queued. Send one PushNotification saying so (under 200 characters), then keep working without asking until the person writes in this session.`
901}
902
903/** The prompt that starts asking the queue: how many wait, then the head question. */
904export function drainPrompt(q: Question, left: number): string {
905  const count = left === 1 ? '1 queued question' : `${left} queued questions`
906
907  return `Autopilot: the person is available again; ${count} to ask, one at a time. ${askQuestionText(q)} New critical questions still go through ${QUEUE_TOOL}.`
908}
909
910/** Adds a prompt to deliver; one of the same kind and key is replaced, so a burst of changes leaves one. */
911export function pushPending(run: Run, p: Pending): Run {
912  const pending = run.pending ?? []
913  const at = pending.findIndex(entry => entry.kind === p.kind && entry.key === p.key)
914  if (at === -1) return { ...run, pending: [...pending, p] }
915
916  return { ...run, pending: pending.map((entry, index) => (index === at ? p : entry)) }
917}
918
919/** The run after a prompt reached the model: it leaves the queue; a delivered ping is remembered. */
920export function deliveredPending(run: Run, p: Pending): Run {
921  const pending = (run.pending ?? []).filter(entry => entry.kind !== p.kind || entry.key !== p.key)
922  if (p.kind !== 'ping') return { ...run, pending }
923
924  return { ...run, pending, pingedFor: p.key }
925}
926
927/** Whether a pending prompt may go to the model in this phase; otherwise it waits (toast only). */
928export function canDeliver(phase: Phase): boolean {
929  return phase === 'running' || phase === 'awaiting'
930}
931
932/** A person's own prompt: after an expired away it starts the drain (R10); before expiry it changes nothing. */
933export function humanSubmit(run: Run, mode: Mode): Run {
934  if (mode !== 'overdue') return run
935
936  return { ...run, drain: true }
937}
938
939/** Puts a released wait's question at the queue head, unless the same text is already queued. */
940function queueAtHead(run: Run, awaiting: Awaiting, now: number): Run {
941  const text = stripTag(awaiting.note ?? '')
942  const questions = run.questions ?? []
943  if (!text || questions.some(question => question.text === text)) return run
944  const kind: Question['kind'] = awaiting.reason === 'user-input' ? 'action' : 'answer'
945
946  const id = nextQuestionId(run)
947
948  return { ...run, nextQuestionId: id + 1, questions: [{ id, text, kind, provisional: null, at: now }, ...questions] }
949}
950
951/** No asking now: the drain stops, a stale drain prompt goes, and a wait for the person is released into the queue. */
952function stopAsking(run: Run, now: number): Run {
953  const pending = (run.pending ?? []).filter(entry => entry.kind !== 'drain')
954  const stopped: Run = { ...run, drain: false, askingId: undefined, pending }
955  const awaiting = run.awaiting ?? null
956  if (run.phase !== 'awaiting' || !awaiting || !PERSON_REASONS.includes(awaiting.reason)) return stopped
957
958  const released: Run = { ...stopped, phase: 'running', awaiting: null, idleTurns: 0 }
959  const queued = awaiting.questionId === undefined ? queueAtHead(released, awaiting, now) : released
960  const isQueued = awaiting.questionId !== undefined || stripTag(awaiting.note ?? '') !== ''
961
962  return pushPending(queued, { kind: 'continue', text: isQueued ? RELEASE_PROMPT : RELEASE_UNQUEUED_PROMPT, key: 0 })
963}
964
965/** Away again or asking off: an undelivered "the away is over" ping is no longer true (D4, R8). */
966function dropPings(run: Run): Run {
967  return { ...run, pending: (run.pending ?? []).filter(entry => entry.kind !== 'ping' && entry.kind !== 'combined-ping') }
968}
969
970/** Starts asking the queue from its head; undelivered expiry pings (session or combined) are moot once the person is back. */
971function startDrain(run: Run, head: Question): Run {
972  const draining: Run = { ...dropPings(run), drain: true, askingId: head.id }
973
974  return pushPending(draining, { kind: 'drain', text: drainPrompt(head, (run.questions ?? []).length), key: 0 })
975}
976
977/** The one ping for a session's own away that expired with questions queued (R8, D4). */
978function pingOnExpiry(run: Run, eff: Effective, now: number): Run {
979  const away = eff.away
980  if (!eff.askOn || eff.awaySource !== 'session' || !away || !isAwayExpired(away, now)) return run
981  if (run.pingedFor === away.setAt) return run
982
983  return pushPending(run, { kind: 'ping', text: expiryPingText((run.questions ?? []).length), key: away.setAt })
984}
985
986/** Whether a global away just expired for this session: it joins the combined ping (§7.3). */
987function isGlobalExpiry(prev: Mode | undefined, next: Mode, eff: Effective, now: number): boolean {
988  if (prev !== 'queueing' || (next !== 'overdue' && next !== 'asking')) return false
989
990  return eff.askOn && eff.awaySource === 'global' && isAwayExpired(eff.away, now)
991}
992
993/**
994 * The run after its mode became `next` (spec §5.1), judged against the mode
995 * the last trigger acted on. `combined` says a global away just ended here
996 * (informational: the combined ping itself is task 10's combinedTick).
997 */
998export function applyMode(run: Run, next: Mode, eff: Effective, now: number): { run: Run; combined: boolean } {
999  const prev = run.lastMode
1000  let out: Run = { ...run, lastMode: next }
1001  if (next === 'queueing' || next === 'overdue') out = stopAsking(out, now)
1002  if (next === 'queueing') out = dropPings(out)
1003
1004  const head = (out.questions ?? [])[0]
1005  const isDrainStart = next === 'asking' || (next === 'draining' && prev !== 'asking' && prev !== 'draining')
1006  if (head && isDrainStart) out = startDrain(out, head)
1007  if (next === 'overdue' && prev !== 'overdue') out = pingOnExpiry(out, eff, now)
1008
1009  return { run: out, combined: isGlobalExpiry(prev, next, eff, now) }
1010}
1011
1012function parseRow(line: string): Record<string, unknown> | null {
1013  try {
1014    const row: unknown = JSON.parse(line)
1015    if (!row || typeof row !== 'object' || Array.isArray(row)) return null
1016
1017    return row as Record<string, unknown>
1018  } catch {
1019    // A malformed line: skip it.
1020    return null
1021  }
1022}
1023
1024export type GoalVerdict = { met: boolean; condition: string }
1025
1026/**
1027 * The goal evaluator's verdicts from whole transcript lines. The engine writes
1028 * each as a top-level attachment row (`{"type":"attachment","attachment":
1029 * {"type":"goal_status","met":…,"condition":…}}`); a verdict anywhere else (a
1030 * tool input, message text) is not the engine's and is ignored. A row with
1031 * `"sentinel":true` only marks the goal set (`met:false`) or cleared without a
1032 * verdict (`met:true`, e.g. `/goal clear`): it never counts as met.
1033 */
1034export function goalVerdictsFromRows(lines: readonly string[]): GoalVerdict[] {
1035  const verdicts: GoalVerdict[] = []
1036  for (const line of lines) {
1037    const row = parseRow(line)
1038    if (!row || row.type !== 'attachment') continue
1039    const attachment = row.attachment as Record<string, unknown> | null | undefined
1040    if (!attachment || typeof attachment !== 'object' || attachment.type !== 'goal_status') continue
1041    if (typeof attachment.met !== 'boolean' || typeof attachment.condition !== 'string') continue
1042    verdicts.push({ met: attachment.met && attachment.sentinel !== true, condition: attachment.condition })
1043  }
1044
1045  return verdicts
1046}
1047
1048/** The last verdict for this condition decides. None yet, or not met, is still active. */
1049export function goalState(verdicts: readonly GoalVerdict[], condition: string): 'achieved' | 'active' {
1050  const matching = verdicts.filter(verdict => verdict.condition === condition)
1051  const last = matching[matching.length - 1]
1052
1053  return last?.met === true ? 'achieved' : 'active'
1054}
1055
1056const IDENTITY_KEYS: Record<string, string> = {
1057  'custom-title': 'customTitle',
1058  'agent-name': 'agentName',
1059  'agent-color': 'agentColor',
1060}
1061
1062/** The color names a session can carry (the same keys as agent-fleet's SESSION_COLORS; not imported across mods). */
1063const SESSION_COLOR_NAMES: Record<string, true> = {
1064  red: true,
1065  blue: true,
1066  green: true,
1067  yellow: true,
1068  purple: true,
1069  orange: true,
1070  pink: true,
1071  cyan: true,
1072}
1073
1074/** Whether a phase is the one where the run follows the session to its new id: only its own /clear restart. */
1075export function followsNewSessionId(phase: Phase): boolean {
1076  return phase === 'restarting'
1077}
1078
1079/**
1080 * The session's name and color from whole transcript lines, only from
1081 * top-level identity rows, the last of each kind winning: /rename's title,
1082 * else the agent name.
1083 */
1084export function identityFromRows(lines: readonly string[]): { name: string | null; color: string | null } {
1085  const last: Record<string, string> = {}
1086  for (const line of lines) {
1087    const row = parseRow(line)
1088    const kind = typeof row?.type === 'string' ? row.type : ''
1089    const key = IDENTITY_KEYS[kind]
1090    if (!row || !key) continue
1091    const value = row[key]
1092    if (typeof value !== 'string' || !value) continue
1093    if (kind === 'agent-color' && !Object.hasOwn(SESSION_COLOR_NAMES, value)) continue
1094    last[kind] = value
1095  }
1096
1097  return { name: last['custom-title'] ?? last['agent-name'] ?? null, color: last['agent-color'] ?? null }
1098}
1099
1100const MAX_SHOWN_VALUE = 80
1101
1102/**
1103 * Control and invisible characters: every control (Cc), format (Cf: bidi
1104 * marks, zero-width, soft hyphen, tag characters) and the line and paragraph
1105 * separators (Zl, Zp).
1106 */
1107const INVISIBLE = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u
1108const INVISIBLE_ALL = /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu
1109/** Line breaks and tabs: read as one space, so the words on either side stay apart. */
1110const LINE_BREAKS = /[\t\n\v\f\r\u{85}\u{2028}\u{2029}]+/gu
1111
1112/** Trailing slashes off a path, in one linear pass (a regex backtracks on a long run). */
1113function trimTrailingSlashes(path: string): string {
1114  let end = path.length
1115  while (end > 0 && path[end - 1] === '/') end--
1116
1117  return path.slice(0, end)
1118}
1119
1120/** A value shown to the model as data: control and invisible characters out, capped at `max` (a transcript value: MAX_SHOWN_VALUE), JSON-quoted. */
1121function quoteValue(value: string, max = MAX_SHOWN_VALUE): string {
1122  return JSON.stringify(value.replace(INVISIBLE_ALL, '').slice(0, max))
1123}
1124
1125/**
1126 * Whether a handoff path the model gave is one autopilot may resume from: a
1127 * `.md` file under `<root>/thoughts/shared/handoffs/`, relative paths taken
1128 * against the root, no control characters, no `..` segment.
1129 */
1130export function isValidHandoffPath(root: string, path: string): boolean {
1131  if (!path || INVISIBLE.test(path)) return false
1132  if (path.split('/').includes('..')) return false
1133  if (!path.endsWith('.md')) return false
1134  const handoffs = `${trimTrailingSlashes(root)}/thoughts/shared/handoffs/`
1135  const absolute = resolveHandoffPath(root, path)
1136
1137  return absolute.startsWith(handoffs) && absolute.length > handoffs.length
1138}
1139
1140/** A handoff path as an absolute one: relative paths are taken against the root. */
1141export function resolveHandoffPath(root: string, path: string): string {
1142  if (path.startsWith('/')) return path
1143
1144  return `${trimTrailingSlashes(root)}/${path}`
1145}
1146
1147export function formatLeft(ms: number): string {
1148  if (ms < 60_000) return `${Math.max(0, Math.round(ms / 1000))}s`
1149  const minutes = Math.max(0, Math.round(ms / 60_000))
1150  if (minutes < 60) return `${minutes}m`
1151
1152  return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}m`
1153}
1154
1155function skillsLine(run: Run): string[] {
1156  if (run.skills.length === 0) return []
1157
1158  return [
1159    `- Skills named in your role: ${run.skills.map(name => `/${name}`).join(', ')}. These are skills, not plain text: invoke them with the Skill tool wherever your role calls for them.`,
1160  ]
1161}
1162
1163function identityLines(run: Run): string {
1164  return [
1165    `- Role and responsibilities: ${run.role}`,
1166    ...skillsLine(run),
1167    ...(run.goal ? [`- Goal (completion condition): ${run.goal}`] : []),
1168    `- Session name: ${run.name ? quoteValue(run.name) : '(none set)'}`,
1169    `- Session color: ${run.color ? quoteValue(run.color) : '(none set)'}`,
1170  ].join('\n')
1171}
1172
1173const PAUSED_SECTION =
1174  '# Autopilot is paused\nThe person is in control. Follow their messages as usual; the autopilot rules do not apply until it resumes.'
1175
1176const WAITING_SECTION =
1177  '# Autopilot is waiting\nAutopilot is parked until the 5-hour token window resets, and the person is in control meanwhile. Follow their messages as usual; the autopilot rules do not apply until it resumes.'
1178
1179/** When the person is truly required: the same test for asking now and for queueing. */
1180const CRITICAL_WHEN =
1181  'an irreversible or outward-facing action, missing access or credentials, a decision outside your role, or something that blocks all useful work and that autopilot cannot decide'
1182
1183const PLAIN_PERSON_LINE =
1184  '- Only when a question truly cannot wait for the person and blocks all useful work, call the PushNotification tool with a one-line question (under 200 characters), then continue with whatever else you can do.'
1185
1186const ASK_PERSON_LINE = `- Only when the person is truly required — ${CRITICAL_WHEN} — call PushNotification with the one-line question, then call ${WAIT_TOOL} with reason user-answer (or user-input for an action the person must take) and the question as note, and end your turn. Everything else you decide yourself.`
1187
1188/** The paused section, with the questions still queued for the person when there are any. */
1189function pausedSection(run: Run): string {
1190  const queued = questionsBlock(run)
1191  if (!queued) return PAUSED_SECTION
1192
1193  return [PAUSED_SECTION, queued, 'Mention them to the person when it fits. An answer given here does not take a question off the queue; a run started again in this session keeps them and asks them one by one.'].join('\n')
1194}
1195
1196/** The rule for questions that need the person, by mode. */
1197function personLines(run: Run, mode: Mode): string[] {
1198  if (mode === 'plain') return [PLAIN_PERSON_LINE]
1199  if (mode === 'asking') return [ASK_PERSON_LINE]
1200  if (mode === 'queueing' || mode === 'overdue') {
types/index.d.ts 175 lines
1/**
2 * Where an autopilot run stands:
3 * - running: working toward the goal, nudged on after every turn
4 * - wrapping: past the context threshold, writing a handoff before a restart
5 * - restarting: the restart tool was called; /clear is queued behind the turn
6 * - resuming: /resume-handoff-doc was issued; its turn ending means resumed
7 * - waiting: the 5-hour token window is nearly used up; parked until it resets
8 * - final: time, restarts, the weekly limit or the goal: a last handoff, no restart
9 * - paused: stalled twice in a row; waits for the person
10 * - awaiting: the session declared it waits for something (wait_for); not nudged until a new turn starts
11 */
12export type Phase = 'running' | 'wrapping' | 'restarting' | 'resuming' | 'waiting' | 'final' | 'paused' | 'awaiting'
13
14/** What a session waits for when it calls wait_for. */
15export type WaitReason =
16  | 'user-input'
17  | 'user-answer'
18  | 'session-answer'
19  | 'session-ping'
20  | 'workflow-end'
21  | 'subagent-result'
22  | 'background-task'
23  | 'other'
24
25/** A wait the session declared: what for, from whom, since when, and when autopilot checks on it. */
26export type Awaiting = {
27  reason: WaitReason
28  /** Who the answer comes from (a session name, a subagent); null when not given. */
29  from: string | null
30  note: string | null
31  since: number
32  /** When autopilot asks once whether the wait is stuck; null for never. */
33  timeoutAt: number | null
34  /** Whether that check was already sent. */
35  pinged: boolean
36  /** In draining: the queued question this wait asks (its note carried `#k` and k was queued). Missing when untagged and in older runs. */
37  questionId?: number
38}
39
40export type FinalReason = 'time' | 'restarts' | 'week' | 'goal' | 'done'
41
42/** One autopilot run, kept in $.store under `run:<session id>`. */
43export type Run = {
44  role: string
45  /** The session's /rename name and /color at the start, so a handoff keeps them. */
46  name: string | null
47  color: string | null
48  startedAt: number
49  until: number
50  threshold: number
51  /** null: as many restarts as the time allows. */
52  maxRestarts: number | null
53  restarts: number
54  phase: Phase
55  /** The handoff a queued restart resumes from. */
56  handoffPath: string | null
57  /** Turns in a row that called no tool. */
58  idleTurns: number
59  /** The /goal condition the run sets and keeps set across /clear; null for none. */
60  goal: string | null
61  /** Skills the role names (`/explore`), confirmed against the session's commands. */
62  skills: string[]
63  /** Park at this % of the 5-hour token window and resume after it resets. */
64  fiveHourStop: number
65  /** Stop for good at this % of the weekly token window. */
66  weekStop: number
67  /** While waiting: when the 5-hour window resets (plus a margin). */
68  waitUntil: number | null
69  /** Why the run is in its final phase. */
70  finalReason: FinalReason | null
71  /** The wait the session declared; null when not waiting. Missing in runs stored by older versions. */
72  awaiting: Awaiting | null
73  /** Whether questions go to the person (--ask-user) instead of being answered by autopilot. Missing in older runs. */
74  askUser: boolean
75  /** Set when the person brought a finished run back: the next restart does not count against the restarts. */
76  isGraceResume?: boolean
77  /** When the run entered its final phase: the handoff of a grace resume must be newer than this. */
78  finalAt?: number
79  /** For a grace resume: the final phase's start, copied from the finished run's `finalAt`. */
80  graceSince?: number
81  /** For a grace resume: how many times the session was asked again to restart. */
82  graceAsks?: number
83  /** Critical questions parked while the person cannot answer (/away, /ask-user off), oldest first. Missing in older runs. */
84  questions?: Question[]
85  /** Whether the queue is being asked one question at a time. */
86  drain?: boolean
87  /** The question the current drain role section names. */
88  askingId?: number
89  /** The id the next queued question gets; only grows, so an id is never reused within the run (spec §3.1). Missing in older runs. */
90  nextQuestionId?: number
91  /** The session away `setAt` whose expiry ping was handed to the model. */
92  pingedFor?: number
93  /** Prompts that must reach the model, kept until delivered (only while running or awaiting). */
94  pending?: Pending[]
95  /** The mode the last heartbeat or command acted on. */
96  lastMode?: Mode
97}
98
99/** A run that finished on time or restarts, kept for a grace period so the person can bring it back. */
100export type FinishedRecord = { run: Run; finishedAt: number }
101
102export type StartCommand = {
103  kind: 'start'
104  /** How long to run, or the next local time reading `hours:minutes`. */
105  end: { kind: 'duration'; ms: number } | { kind: 'clock'; hours: number; minutes: number }
106  threshold: number
107  maxRestarts: number | null
108  role: string
109  goal: string | null
110  fiveHourStop: number
111  weekStop: number
112  askUser: boolean
113}
114
115export type Command =
116  | { kind: 'status' }
117  | { kind: 'stop' }
118  | StartCommand
119  /** deltaMs is 0 when no time was given, restarts 0 when no --restarts. */
120  | { kind: 'extend' | 'shorten'; deltaMs: number; restarts: number }
121  | { kind: 'until'; hours: number; minutes: number }
122  | { kind: 'error'; message: string }
123
124/** A token window as `$.session.usage().rateLimits` reports it. */
125export type TokenWindow = { kind: string; percentUsed: number; resetsAt?: string }
126
127/**
128 * How a run treats questions for the person, decided by availMode in order:
129 * - plain: no --ask-user and no askUser record anywhere; today's no-ask behaviour, no queue
130 * - queueing: asking is off, or the person is away; critical questions go to the queue
131 * - draining: the queue is asked one question at a time
132 * - overdue: the away ended with questions queued; no asking until the person writes
133 * - asking: today's --ask-user behaviour
134 */
135export type Mode = 'plain' | 'queueing' | 'overdue' | 'draining' | 'asking'
136
137export type AwayField = { until: number; setAt: number } | { back: true; setAt: number }
138export type AskField = { on: boolean; setAt: number }
139/** Availability record, session ($.store `away:<sid>`) or global (~/.claude/autopilot/status/global.json). */
140export type Avail = { v: 1; away: AwayField | null; askUser: AskField | null }
141
142export type Effective = {
143  away: AwayField | null
144  awaySource: 'session' | 'global' | null
145  /** Effective ask-user: the record if any, else the run's --ask-user flag. */
146  askOn: boolean
147  /** Whether any level holds an askUser record (D5: no record + flag off = plain). */
148  askRecorded: boolean
149  /** When the effective askUser record was set (session over global); null without one. */
150  askSetAt: number | null
151}
152
153/** A critical question parked for the person; ids run 1..n within the run and are never reused (`Run.nextQuestionId`). */
154export type Question = { id: number; text: string; kind: 'answer' | 'action'; provisional: string | null; at: number }
155export type QueueInput = {
156  question: string
157  kind: 'answer' | 'action'
158  provisional: string | null
159  /** Set when the question or the provisional was longer than its cap and was cut. */
160  cut?: true
161}
162
163/** A prompt that must reach the model; `key` is the away `setAt` for pings, 0 otherwise. */
164export type Pending = { kind: 'ping' | 'combined-ping' | 'drain' | 'continue'; text: string; key: number }
165
166export type AvailCommand =
167  | { kind: 'away'; end: { kind: 'duration'; ms: number } | { kind: 'clock'; hours: number; minutes: number }; global: boolean }
168  | { kind: 'back'; global: boolean }
169  | { kind: 'ask-user'; on: boolean; global: boolean }
170  | { kind: 'error'; message: string }
171
172/** What the combined ping reads from other sessions' badge files. */
173export type BadgeAvail = { queued: number; awaySource: 'session' | 'global' | null; awaySetAt: number | null; beat: number }
174export type LockOwner = { sid: string; at: number }
175