SLOPSHOPPER

vaken

Mission control for Claude Code Desktop: what needs you, plan limits, context, agents and a safety stop.

★ 2v1.170.0MITupdated 2026-10-26johanmatsgard/vaken/mods/cockpit
A shopper browsing a rack in a slop shop
Preview could not run: harness produced no result (3 | import { GIT_TIMEOUT_MS as COUNT_GIT_MS, parseStatusCount } from '../core/crew3git' ^ error: No matching export in "slop-empty:/home/runner/work/slopshoppe
README

vaken

vaken is mission control for the Claude Code DESKTOP app. It needs the pane of the desktop app (macOS and Windows 11). It does not work in claude.ai chat, in Cowork or in the terminal program alone.

Not affiliated with Anthropic.

What it shows

The pane sits to the right of your chat. It shows what needs you, your plan limits, how full the context is, your agents and sessions, pull requests and checks, and the cost per day. It also keeps short notes for your next session.

The safety stop

vaken looks at each step Claude is about to take, before it runs. It warns, asks or stops risky steps: bulk deletes, forced pushes, secrets, outside actions such as posts and payments, and very young or look-alike packages. A destructive command or a secret stops the step when Claude Code would not ask you first. It is a seat belt, not a sandbox. /vaken-pause pauses every change step.

What vaken does by itself

vaken never answers "yes" for you, and it never writes permission rules into your settings. It only says "no" to a step, or acts when you press, unless you turn a feature on.

Steps it can say no to

  • Risky steps (the safety check). Before each step it looks for destructive commands, edits outside your folders, odd packages, outside actions, secrets and migrations. New install: it warns. In auto or bypass mode, where Claude Code would not ask you, a destructive command or a secret stops and waits for you. To only warn there too, press the choice "Warn (stops in auto mode)" yourself, once, in Settings > Safety > Risky commands and Secrets; it then reads "Warn only".
  • Pause and Allow once. /vaken-pause stops every step that changes things. /vaken-guard allow once lets one stopped step through. Both only when you type them.
  • While away. Careful stops risky steps while you are away. Off by default. Settings > Safety > While away.
  • Budget. On Stop it says no to costly calls once the session or day budget is used up. Off by default. Settings > Money and plan > Budget.
  • Agent cap. On Stop it says no to a new agent over your limit. New install: Warn, which never says no. Settings > Agents > Agent cap.
  • Loop breaker. On Stop it says no to a step that keeps failing, until your next message. New install: Warn. Settings > Safety > Loop breaker.
  • Agent models. It tells you when a lookup agent could use a cheaper model. It never changes the agent. Settings > Agents > Agent models.

Output it makes shorter

  • Lean session. On by default. Long install and test logs are cut short, and an unchanged file read again becomes one line. Errors and the last 40 lines are always kept. Settings > Money and plan > Lean session.

Files it writes only on your press

  • Set up agents writes agent files under .claude/agents/ or a block in CLAUDE.md. Off by default: Settings > Prompts and memory > Set up agents.
  • Learn from you offers to save a correction you repeat as one rule in the project's CLAUDE.md. It writes only when you press. /vaken-settings teach.mode off stops the offers.

Things it runs

  • Compacting. New install: Watch only. The This session card shows a good moment, and Compact now does it. Auto compacts by itself at a break or at 60% full, never while you type or work runs. The first-start question "Long chats" offers Auto, or set it in Settings > Money and plan > Compact by itself.
  • Task runner. Nothing runs until you press Start. The four agent types (Researcher, Builder, Reviewer, Fixer) are agent files in the plugin. When a run starts, vaken asks Claude in a message to start the agents for your task list, with each one's task, type, model and folder. To stop one, vaken asks Claude in a message. A stop is a request: the task shows as stopped at once, but the agent ends only when Claude stops it, so a time or cost limit is no longer a hard stop. After a plan limit it waits: press Go on on the Agents card. A run set to "After a plan limit: Go on" goes on by itself. Stop all on the Agents card, or /vaken-tasks stop, stops a run.
  • Night run. Off by default. /vaken-tasks night runs the list unattended on mains power, keeps the Mac awake and turns on While away: Careful, then puts them back. It goes on after a limit by itself. Turn it on with /vaken-settings night.mode on.
  • After a limit. New install: Remind, a note when the limit resets. Resume also sends "continue" for you, a few times a day at most. Settings > Money and plan > After a limit.
  • Keep session cheap. Off by default. In a break it sends a short model call to keep the cache warm. Settings > Money and plan > Keep session cheap.
  • Keep Mac awake. Off by default. Settings > Agents > Keep Mac awake.
  • Buttons. Next steps, Ask, Compact now, Nudge, Remove copy and the others act only when you press them.

Programs, web calls and automatic writes

Everything vaken does on its own, besides what is listed above. Programs run on your computer. vaken's only network code of its own is one read of the public Claude status page, to say when Claude is down, and nothing here sends your files or your words anywhere.

Background programs (they only read, on timers or after an event; nothing is pushed or changed):

  • git: branch, status, diff and worktree facts. It never fetches or pushes.
  • gh (GitHub CLI): pull requests and checks, only if you installed it and signed in. It merges only when you press Merge.
  • ps, lsof, top, sysctl, vm_stat, pmset: the load of your computer, the battery and the processes and ports of your sessions. During a night run, pmset -g batt at most once a minute.
  • On Windows: netstat, tasklist and fixed PowerShell lines read the same facts.
  • curl to http://localhost:<port>: to see if your dev server answers.
  • osascript (Mac): a short fixed notice while you are away, when the app's own notice did not reach you. No prompt, file or session name goes in it.
  • which or where, sleep and test: to find a tool and wait a second.
  • caffeinate (PowerShell on Windows): only while Keep Mac awake is on, or during a night run.
  • kill or taskkill: stops a program by its exact number, only one vaken started itself (the keep-awake holder) or one you pressed Stop on.
  • find, rm, mkdir, chmod, du: keep vaken's own folder tidy (see below).

Web calls (the only two):

  • The Claude status page, https://status.claude.com, every 5 minutes while a session is active, to show "Is Claude down?". It reads one public page and sends nothing of yours. It follows your organization's web policy.
  • npm view <package name> (or the same command of pnpm, yarn or bun), when the safety check looks at an install. It asks the public npm registry and sends only the package name.

Automatic writes (all on your computer):

  • Undo copies: before a file changes, a copy goes under ~/.claude/cockpit/checkpoints/. Copies older than 7 days that no Undo list uses are removed, and so are hand-over notes older than 14 days.
  • A hand-over note: written under ~/.claude/cockpit/ just before Auto compacts the chat, so the next step can find what was open.
  • Task run folders: when you press Start on a task run, a task that writes code gets its own git worktree under .claude/worktrees/. vaken removes one only when you press Remove this copy.

What vaken does on your computer

A short list of everything vaken does by itself, per kind. Facts read from the code. The sections below give more detail.

  • Files it writes. Only on your computer. Under ~/.claude/cockpit/: Undo copies of a file just before it changes, hand-over notes, pictures and browser profiles. In your project, only when you press or type a command: .claude/cockpit-* files, .claude/cockpit-eyes/ and .claude/worktrees/. Agent files under .claude/agents/ or ~/.claude/agents/ and a CLAUDE.md block only when you accept them in Set up agents (a .bak copy first). It never writes settings.json or a hook file. The write in agentcap.ts is the shared file block every feature file holds; agentcap.ts itself writes no file.
  • Programs it starts, and why. Each is a fixed program name with fixed arguments: git and gh (branch, checks and pull request facts; gh merges only when you press Merge), ps, lsof, top, sysctl, vm_stat, pmset (the load of the computer and the battery; on Windows tasklist, netstat and fixed PowerShell lines), curl to http://localhost:<port> (does your dev server answer), headless Google Chrome (a picture of a localhost page), osascript (a fixed notice while you are away), caffeinate (only with Keep Mac awake on), npm view (the package check), kill or taskkill (only a program vaken started, or one you pressed Stop on), find, rm, mkdir, mv, chmod, du (only inside ~/.claude/cockpit/), git worktree add and remove and git branch -D (only for a task run's own copy, the remove only when you press Keep, which keeps its branch, or Throw away), gh run view --log-failed (why a check failed), and sh -c with the check command you set for a task run, or a fixed line that starts caffeinate or Chrome. The run call in agentcap.ts is the shared block; agentcap.ts itself starts no program.
  • Hosts it contacts, and what it sends. Two only. https://status.claude.com/api/v2/summary.json (a fixed address), every 5 minutes while a session is active: a plain read that sends nothing of yours. https://registry.npmjs.org/ through npm view before an install: only the package name. vaken has no server and no telemetry.
  • Slash commands it runs itself. /compact, only when the app refuses a direct compaction (compaction.ts; see "/compact" below for when). And the skill or command you press Start on in the Skills card (home/actions.ts), only on that press.
  • Prompts it submits, and what is in them. Fixed text, almost always after a press, or your own words: a quick action you saved yourself, sent when you type /vaken quick <name>. The fixed ones: Nudge (continue), Send the better one, a fix button, the task runner's plan and start requests, and Finish safely (cost.ts: "<check> failed 3 times in a row. Do not try the same fix again. Start one agent with model ... to find why and fix it ... Keep this session's model as it is."), sent when the turn ends if you pressed it while Claude worked. With Resume on (default Remind) it submits "The plan limit has reset. Continue where you stopped." after a limit, with a daily cap.
  • Messages to other sessions ($.session.send). Only after a press or a yes: your typed answer or a Nudge (continue) to another session from the pane (home/talk.ts), a message you wrote to another session after you say yes (inbox.ts), and a line you type for one helper of your task run (/vaken-tasks say, orchestra.ts).
  • The prompt box and sound. It puts text in your prompt box for you to send or edit, never sends it ($.prompt.fill: ship.ts, phonedo.ts, crew3.ts, notes.ts). It shows a dim hint you take with Tab ($.prompt.suggest: nextsteps.ts, inbox.ts). With Tell me set to Speak, it reads a short notice aloud on your computer ($.audio.speak, tellme.ts).
  • Agents it starts. None by itself. For a task run you started (home.tsx, orchestra.ts), it asks Claude in a message to start them, and Claude starts them. Its four agents (vaken:researcher, vaken:builder, vaken:reviewer, vaken:fixer) set no permissionMode and no hooks, so they keep Claude Code's own permission mode.
  • Tools it calls itself. None of Claude Code's own tools. It only reads two things: the list of tools each plugin adds, for the plugin card ($.tool.list, trust.ts), and what Claude Code would decide for a step, for the guard ($.tool.check, guard.ts, guardworld.ts); it changes neither. When you press Stop or a task passes your time or cost limit, it asks Claude in a message to stop that agent. The app's session and window tools listed below. Its own vaken_status tool is answered by vaken from its store (steer.ts); it does not answer any other tool. tellme.ts calls the app's own notice ($.ui.notify), not another plugin.
  • Permission decisions. vaken never says "yes" for you and has no hook on Claude Code's permission check or its "Allow?" question. Two hooks only watch: classic.Notification (home.tsx, attention.ts) notes that Claude Code asked you, for the pane and the step timer, and classic.PermissionDenied (allowrules.ts) shows why Claude Code stopped a step. Both pass on with next(e) unchanged. The only answers vaken gives are a deny from the guard, /vaken-pause or a cap you set. The hooks on agent.spawn and command.run pass on unchanged except where "For reviewers" says why. vaken never changes Remote Control, your permission mode or your settings.

Install

Run these lines in a terminal, then open a NEW session in Claude Code Desktop and type /vaken.

claude plugin marketplace add johanmatsgard/vaken
claude plugin install vaken@vaken

What vaken runs, sends and stores

vaken has no server and no telemetry. It sends nothing to its authors. It never changes your settings.json.

Programs it starts on your computer. vaken's only network code of its own reads the public Claude status page (https://status.claude.com), at most every 5 minutes while you use a session, to say when Claude is down. It sends nothing about you. Each program below uses the network only as it normally does.

  • git: branch, status, diff and worktree facts. It never fetches or pushes.
  • gh (GitHub CLI): pull requests, checks and merge. Only if you installed it and signed in.
  • curl: to http://localhost:<port>, to see if your dev server answers. To another address only if you type it.
  • Google Chrome (headless): takes a picture of a page. The tool that Claude can call takes only localhost addresses and html files in your project.
  • ps, lsof, top, sysctl, vm_stat, pmset: read the load of your computer and the processes of your sessions. On Windows: tasklist, netstat and PowerShell.
  • osascript (Mac only): a short fixed notice while you are away.
  • caffeinate (PowerShell on Windows): only when you turn on keep-awake.

The two network requests vaken starts itself. Before an install, the package check runs npm view <package name> (or the same command of pnpm, yarn or bun). This asks the public npm registry, https://registry.npmjs.org/. Only the package name is sent. Every 5 minutes while a session is active, vaken reads the public Claude status page, https://status.claude.com, and sends nothing of yours.

What goes to Claude. By default vaken makes no extra model calls. It adds short safety notes to what Claude already reads, and a note about what to keep (goal, next steps, open files and decisions) with every compaction vaken starts. Auto compaction starts on Watch only for a new install (a Compact now button); you can choose Auto. For a long message, at most once an hour, one short note asks Claude for working habits: a visible task list, a done and next close, clickable questions and chapters (tasks.visible, habit.*, on by default). Plain mode (plain.mode, on by default) asks Claude for short, simple words. While you are on the phone, the phone note (phone.note, on by default) tells Claude what a phone cannot do. More goes to Claude only when you choose it: features such as Plan first or Prompt review, buttons that send a message, "Say it simpler", and the cache keeper (off by default). All of it goes through Claude Code, with your account.

Built-in app tools. vaken calls the desktop app's own built-in tools on your computer: the session tools (to read your plan usage, list your sessions and, when you press a button, change a session's model or effort) and the window tool (to open the pane in a new window). These calls stay inside the app.

Where it stores data. On your computer only.

  • The plugin store of Claude Code, with keys that start with cockpit:.
  • Files under ~/.claude/cockpit/: copies of changed files for Undo, hand-over notes, and pictures.
  • In your project, only when you ask: .claude/cockpit-* files and .claude/worktrees/.

vaken does not store your prompts or transcripts as text. "Delete everything vaken stored" in Settings removes the store keys and the files under ~/.claude/cockpit/.

Privacy and data

  • What is stored: counts, names, paths, states, exit codes and times. Never your prompt text, transcript text or tool output. A session title and a goal are a few key words of your first prompt.
  • Where: in the plugin store of Claude Code (keys that start with cockpit:, under ~/.claude) and in files under ~/.claude/cockpit/. In your project only when you ask.
  • What leaves your computer: only the status page read and npm view, both described above. A model call happens only when you press a button or turn a feature on. It goes through Claude Code, with your account. vaken has no server and no telemetry.
  • Remove it all: open Settings and press "Delete everything vaken stored" at the bottom. The first press shows what would go, the second deletes. It never touches your project files or settings.json.
  • Full details: PRIVACY.md.
  • Security reports: use GitHub private vulnerability reporting: open the Security tab of the repository and choose "Report a vulnerability" (SECURITY.md). Do not post a security problem as a public issue.

For reviewers: what the hooks do

Where vaken changes an event before it passes it on, it does so on purpose. This list gives the reason and the setting. Defaults are in hooks/core/settings.ts and the hooks/core/ file of each feature; presets are in hooks/core/presets.ts.

Notes added to what Claude reads.

  • Assumption review (assumptions.ts, prompt.submit): one line asks Claude to list its assumptions. Setting assume.check, default off.
  • Working habits (tasklist.ts, prompt.submit): for a long prompt, one note with the habits you turned on (a visible task list, a done and next close), at most once an hour. Only habits set to On.
  • Plan first (planfirst.ts, prompt.submit): one line asks for a short plan. Only when plan.first is Ask. Default Suggest shows a line to you only.
  • Prompt review (promptcheck.ts, prompt.submit): one line asks Claude to ask one question about a short prompt. Only when prompt.check is Ask. Default Tip shows a line to you only.
  • Checks (proof.ts, prompt.submit): a note that a claim has no passing check. Only when claude.notes is "All checks"; default "Safety only". With Claims on (default Warn), a "done" claim without a passing check also gets a one-line warning in the turn result.
  • Compaction (compaction.ts, session.compact): the keep instruction (goal, what is done, what is next, open files and branches, decisions, any waiting question) is added to every compaction vaken starts. Setting compact.card, default on. Also, once per crossing of compact.from, a short note asks Claude to finish the step and end its turn (compactnudge.ts, tool.call), only when vaken would compact but Claude is mid-task.
  • Guard (guard.ts, tool.call): a short safety note after a warned step. Always on.
  • Phone note (phone.ts, prompt.compose): one fixed section, only while the person is on the phone, at most until Phone mode would end. On the phone means: a phone (surface mobile) is attached, or the last prompt or command came through the Remote Control bridge (origin bridge) and no prompt was typed at the Mac (origin composer) since. Setting phone.note, default on. The text (hooks/core/phonenote.ts, PHONE_NOTE_TEXT): the person is on a phone and cannot run commands, open files, see the Mac screen or open a localhost link; run commands yourself and show the short result, never ask them to open, run or look at something on the Mac; send a file or picture with your file-sending tool if you have one, else show the key lines, and for a localhost page send a picture, never the link; sum up diffs and long output in a few plain lines; say in one line when a sign-in or connector needs the Mac's browser; offer next steps with your question tool.

Prompts the person's own command submits. /vaken show, /vaken run and /vaken pic (phone.ts, eyes.ts, command.run) submit one fixed prompt as the person's words ($.prompt.submit with asUser), half a second after the command ends, only when the person typed the command. Only the path or the command changes (hooks/core/phonenote.ts):

  • show: "Please send me the file <path> with your tool that sends files to the person. If you have no such tool, show its first 40 lines as text; for a picture, describe it in a few lines." The path must be inside the project (also where a link lands), not a secret-looking file (the guard's secretPathKind), and a file that is there.
  • run: "Please run exactly this command in the project folder and show me the short output (the last lines, or a few plain lines if it is long):" then the command. vaken runs nothing itself; Claude's permission prompts and the guard apply.
  • pic: vaken takes one 390-wide picture with the Preview card's headless Chrome (localhost only, outside addresses go to a dead proxy) into .claude/cockpit-eyes/, then: "Please send me the picture <path> with your tool that sends files to the person. If you have no such tool, describe what the picture shows in a few lines."

Prompts vaken rewrites from the person's own prompt (phone.ts, eyes.ts, prompt.submit). A phone, or a message typed while Claude works, can send the words above as plain text. When a prompt from the person (origin composer or bridge) is exactly /vaken show ..., /vaken run ... or /vaken pic ..., vaken puts the same fixed prompt in its place (same checks); a refusal is shown to the person as a notice and nothing goes to Claude. The number menu, only for a prompt or command from the phone (origin bridge): /vaken alone answers with the menu as a notice and sends nothing to Claude. For 10 minutes after it, and only until the next prompt from the phone, a prompt from the phone that is exactly one digit becomes a fixed prompt (hooks/core/phonenote.ts); a digit from the Mac is never changed:

  • 1: "Sum up what changed since my last message in a few plain lines."
  • 2: "Run the project's tests and show the short result."
  • 3: the pic word above (the dev server vaken found).
  • 4: "continue"
  • 5: no prompt; the person gets the short status the phone hello gives, as a notice.

The first prompt from the phone in a stint also adds the phone hello (a system row Claude never reads). vaken keeps which origin kinds it has seen, with the time, under cockpit:phone:origins (no text).

Effort for quick asks (home.tsx, turn.step). Only after you press the low-effort button the model-fit card offers for quick asks (setting hints.model), the main session's steps are sent with low effort while your asks stay quick; it ends when you stop pressing or an ask is not quick. Nothing else about the step changes, and helper agents are never touched.

Model routing (route.ts, agent.spawn). A tip only: when a helper that only reads or searches could use a cheaper model, vaken says so. It passes the event on unchanged, so the agent starts as Claude asked.

Task runner (orchestra.ts, agent.spawn). It only watches. It passes the event on unchanged, then notes which task of your run a new agent belongs to, by the task code on the first line of its brief.

Away mode (away.ts, command.run). It handles its own /vaken-away command and removes a time such as "for

Source 90 files
hooks/register.tsx 218 lines
1// Vaken: one plugin, one module
2import type { EngineInterface, Register } from 'claude-code'
3import { withToastGate } from './core/io'
4import type { Io } from './core/io'
5import { homeFrom } from './core/platform'
6
7import { registerAgentCap } from './features/agentcap'
8import { registerAway } from './features/away'
9import { registerAttention } from './features/attention'
10import { registerTellMe } from './features/tellme'
11import { registerCacheKeeper } from './features/cachekeeper'
12import { registerCalm } from './features/calm'
13import { registerCompaction } from './features/compaction'
14import { registerCost } from './features/cost'
15import { registerInsight } from './features/insight'
16import { registerKeeper } from './features/keeper'
17import { registerInbox } from './features/inbox'
18import { registerContinuity } from './features/continuity'
19import { registerCoach } from './features/coach'
20import { registerRepeat } from './features/repeat'
21import { registerCrew3 } from './features/crew3'
22import { registerCrew } from './features/crew'
23import { registerDiet } from './features/diet'
24import { registerErrors } from './features/errors'
25import { registerEyes } from './features/eyes'
26import { registerGuard } from './features/guard'
27import { registerGuardBack } from './features/guardback'
28import { registerGuardWorld } from './features/guardworld'
29import { registerHappened } from './features/happened'
30import { registerHome } from './features/home'
31import { registerLoopBreaker } from './features/loopbreaker'
32import { registerAgentBoard } from './features/agentboard'
33import { registerOrchestra } from './features/orchestra'
34import { registerSimple } from './features/simple'
35import { registerAssumptions } from './features/assumptions'
36import { registerTaskList } from './features/tasklist'
37import { registerNeighbors } from './features/neighbors'
38import { registerExplain } from './features/explain'
39import { registerFreshStart } from './features/freshstart'
40import { registerCostHint } from './features/costhint'
41import { registerPhone } from './features/phone'
42import { registerPhoneDo } from './features/phonedo'
43import { registerPlanFirst } from './features/planfirst'
44import { registerStarters } from './features/starters'
45import { registerSetup } from './features/setup'
46import { registerPlain } from './features/plain'
47import { registerPromptCheck } from './features/promptcheck'
48import { registerShape } from './features/shape'
49import { registerToday } from './features/today'
50import { registerValue } from './features/value'
51import { registerNotes } from './features/notes'
52import { registerTeach } from './features/teach'
53import { registerNight } from './features/night'
54import { registerPresets } from './features/presets'
55import { registerProof2 } from './features/proof2'
56import { registerProof } from './features/proof'
57import { registerResume } from './features/resume'
58import { registerClaudeStatus } from './features/claudestatus'
59import { registerRoute } from './features/route'
60import { registerSteer } from './features/steer'
61import { registerTrust } from './features/trust'
62import { registerUndo } from './features/undo'
63import { registerShip } from './features/ship'
64import { flushSkills, isSkillsRun, keepListing, noteSkillUse, skillsAnswer, skillsFailed, skillsPending, skillsReady, wantsListing } from './features/skills'
65import { registerStability } from './features/stability'
66import { registerPressLog } from './features/presslog'
67import { registerNextSteps } from './features/nextsteps'
68import { registerLean } from './features/lean'
69import { registerAllowRules } from './features/allowrules'
70import { registerRelay } from './features/relay'
71
72// IO-BLOCK-START
73function io($: EngineInterface): Io {
74  return withToastGate({
75    now: () => $.clock.now(),
76    home: () => homeFrom({ HOME: () => $.env.get('HOME'), USERPROFILE: () => $.env.get('USERPROFILE'), HOMEDRIVE: () => $.env.get('HOMEDRIVE'), HOMEPATH: () => $.env.get('HOMEPATH') }),
77    sessionId: () => $.session.id(),
78    get: key => $.store.get(key),
79    set: (key, value) => $.store.set(key, value),
80    del: key => $.store.delete(key),
81    keys: () => $.store.keys(),
82    read: path => $.fs.read(path),
83    write: (path, text) => $.fs.write(path, text),
84    run: (argv, init) => $.process.run(argv, init),
85    ask: (question, options) => $.ui.ask(question, options),
86    complete: req => $.model.complete(req),
87    toast: text => $.ui.toast(text),
88    invalidate: () => $.ui.invalidate('ui.render'),
89  })
90}
91// IO-BLOCK-END
92
93export const register: Register = on => {
94  // Its word after /vaken-help run must reach it before the help page answers
95  registerPressLog(on)
96  // Its next steps are picked before Home's turn hook checks the band for a redraw
97  registerNextSteps(on)
98  registerLean(on)
99  registerHome(on)
100  registerCompaction(on)
101  registerCacheKeeper(on)
102  registerLoopBreaker(on)
103  registerStability(on)
104  registerAttention(on)
105  registerTellMe(on)
106  registerHappened(on)
107  registerAgentCap(on)
108  registerGuard(on)
109  registerAllowRules(on)
110  registerRelay(on)
111  // RegisterAway wraps the away switch that registerGuardWorld registers, so it comes first
112  registerAway(on)
113  registerGuardWorld(on)
114  registerInbox(on)
115  // Hello on the phone: reads what the inbox reads
116  registerPhone(on)
117  // Run a command from the last answer: /vaken-help run do, for a phone and for the card
118  registerPhoneDo(on)
119  registerGuardBack(on)
120  registerProof(on)
121  registerProof2(on)
122  registerCost(on)
123  registerRoute(on)
124  registerPlain(on)
125  registerPromptCheck(on)
126  registerAssumptions(on)
127  registerTaskList(on)
128  registerShape(on)
129  registerValue(on)
130  registerToday(on)
131  // Focus and the open ends of yesterday
132  registerCalm(on)
133  registerFreshStart(on)
134  registerCostHint(on)
135  registerPlanFirst(on)
136  registerStarters(on)
137  registerSetup(on)
138  registerNeighbors(on)
139  registerAgentBoard(on)
140  registerOrchestra(on)
141  registerSimple(on)
142  registerExplain(on)
143  registerErrors(on)
144  registerSteer(on)
145  registerDiet(on)
146  registerCrew(on)
147  registerCrew3(on)
148  registerEyes(on)
149  registerTeach(on)
150  registerNight(on)
151  registerNotes(on)
152  registerCoach(on)
153  registerRepeat(on)
154  registerInsight(on)
155  registerPresets(on)
156  registerResume(on)
157  registerClaudeStatus(on)
158  registerShip(on)
159  registerUndo(on)
160  registerTrust(on)
161  registerContinuity(on)
162  registerKeeper(on)
163
164  // The Skills card: its hooks are written here, so the plugin directory reads each one where it is registered
165  on('session.start', { cwd: /(?<skills>)/ }, async ($, e, next) => {
166    const result = await next(e)
167    // After next: the engine has finished starting, so its skill list is there. A failed read is tried again after a turn.
168    try {
169      const usage = await $.session.usage({ breakdown: 'summary' })
170      await keepListing(io($), usage)
171    } catch {
172      await keepListing(io($), undefined)
173    }
174    return result
175  }).catch(($, e, next) => next(e))
176
177  on('skill.prompt', { skill: /(?<skills>)/ }, async ($, e, next) => {
178    await noteSkillUse(io($), e.skill)
179    return next(e)
180  }).catch(($, e, next) => next(e))
181
182  on('turn.complete', { turnId: /(?<skills>)/ }, async ($, e, next) => {
183    try {
184      if (skillsPending()) await flushSkills(io($))
185      if (wantsListing(e.agentId)) {
186        // A failed read counts as a try too, so a broken read stops after LISTING_TRIES turns
187        try {
188          const usage = await $.session.usage({ breakdown: 'summary' })
189          await keepListing(io($), usage)
190        } catch {
191          await keepListing(io($), undefined)
192        }
193      }
194    } catch {
195    }
196    return next(e)
197  }).catch(($, e, next) => next(e))
198
199  on('session.end', { sessionId: /(?<skills>)/ }, async ($, e, next) => {
200    // The last counts are lost on a failure, nothing else
201    await flushSkills(io($))
202    return next(e)
203  }).catch(($, e, next) => next(e))
204
205  on('command.run', { command: 'vaken-help' }, async ($, e, next) => {
206    if (!isSkillsRun(e.args)) return next(e)
207    const i = io($)
208    // The language and the waiting counts first, then the skill list is read
209    if (!(await skillsReady(i))) return skillsFailed()
210    try {
211      const usage = await $.session.usage({ breakdown: 'summary' })
212      return skillsAnswer(i, usage)
213    } catch {
214      return skillsAnswer(i, undefined)
215    }
216  })
217}
218
hooks/core/io.ts 369 lines
1// The narrow I/O shared code uses. The validator follows `$` only inside the file that receives it, so shared code takes closures.
2import type { EngineInterface } from 'claude-code'
3import { trFill } from '../i18n/t'
4import { FOCUS_KEY, isFocused, parseFocus, passesFocus } from './focus'
5import { noteRun, noteWrite } from './selfcost'
6
7export type Io = {
8  now: () => Promise<number>
9  home: () => Promise<string>
10  sessionId: () => Promise<string>
11  get: (key: string) => Promise<unknown>
12  set: (key: string, value: unknown) => Promise<void>
13  del: (key: string) => Promise<void>
14  keys: () => Promise<string[]>
15  read: (path: string) => Promise<string>
16  write: (path: string, text: string) => Promise<void>
17  run: EngineInterface['process']['run']
18  ask: (question: string, options: string[]) => Promise<string>
19  complete: EngineInterface['model']['complete']
20  // Only where a call continues this session's own chat; reached through core/modelGate.ts.
21  fork?: EngineInterface['model']['fork']
22  // `urgent` toasts always show; others count against the hourly cap.
23  toast: (text: string, urgent?: boolean) => void
24  invalidate: () => void
25  // The store without this project's settings laid over it.
26  getGlobal?: (key: string) => Promise<unknown>
27  // Each key as `get` gives it, same order.
28  getMany?: (keys: readonly string[]) => Promise<unknown[]>
29  getGlobalMany?: (keys: readonly string[]) => Promise<unknown[]>
30}
31
32// Store keys keep the old product name so saved data survives the rename.
33export const SETTING_PREFIX = 'cockpit:setting:'
34export const PROJECT_OF_KEY = (sessionId: string): string => `cockpit:projectof:${sessionId}`
35export const PROJSET_PREFIX = 'cockpit:projset:'
36export const PROJSET_KEY = (root: string): string => `${PROJSET_PREFIX}${root}`
37// Means 'this row's default, not a choice', so the Guard does not take it for an explicit pick.
38export const USE_DEFAULT = 'use-default'
39// Only this session writes it, so it is read once per session and after its own write.
40export const SESSSET_PREFIX = 'cockpit:sessset:'
41export const SESSSET_KEY = (sessionId: string): string => `${SESSSET_PREFIX}${sessionId}`
42
43// At most TOAST_DEFAULT_CAP ordinary toasts an hour across sessions; urgent ones always show. Held-back text is still in the band and ledger.
44export const TOAST_LOG_KEY = 'cockpit:toasts'
45export const TOAST_DEFAULT_CAP = 6
46export const TOAST_WINDOW_MS = 60 * 60_000
47
48export function toastVerdict(raw: unknown, now: number, cap: number = TOAST_DEFAULT_CAP): { show: boolean; stamps: number[] } {
49  const recent = (Array.isArray(raw) ? raw : []).filter((t): t is number => typeof t === 'number' && now - t < TOAST_WINDOW_MS && t <= now)
50  return recent.length >= cap ? { show: false, stamps: recent } : { show: true, stamps: [...recent, now] }
51}
52
53// The same ordinary toast shows at most once an hour; the band and ledger keep the count.
54const TOAST_SEEN_KEY = 'cockpit:toasts:seen'
55const TOAST_SEEN_KEEP = 50
56const toastShape = (text: string): string => text.replace(/\d+([.,]\d+)?/g, '#').slice(0, 80)
57
58export function repeatVerdict(raw: unknown, now: number, text: string): { show: boolean; seen: Record<string, number> } {
59  const seen: Record<string, number> = {}
60  if (typeof raw === 'object' && raw !== null) for (const [k, t] of Object.entries(raw)) if (typeof t === 'number' && now - t < TOAST_WINDOW_MS && t <= now) seen[k] = t
61  const shape = toastShape(text)
62  if (seen[shape] !== undefined) return { show: false, seen }
63  seen[shape] = now
64  const keep = Object.entries(seen).sort((x, y) => y[1] - x[1]).slice(0, TOAST_SEEN_KEEP)
65  return { show: true, seen: Object.fromEntries(keep) }
66}
67
68// Settings and pane choices are read on almost every step but rarely written, so each group is also kept as one bundle key. A write also goes to the small key beside it, which older copies and tests read.
69export const SETTINGS_KEY = 'cockpit:settings:v1'
70const PREFS_KEY = 'cockpit:prefs:v1'
71export const BUNDLE_TTL_MS = 3_000
72const PREF_PREFIX = 'cockpit:pref:'
73const PREF_KEYS = ['cockpit:firstrun', 'cockpit:layouts', 'cockpit:quiet:asked', 'cockpit:runner:templates']
74type Bundle = { key: string; has: (key: string) => boolean; name: (key: string) => string }
75const BUNDLES: Bundle[] = [
76  { key: SETTINGS_KEY, has: k => k.startsWith(SETTING_PREFIX), name: k => k.slice(SETTING_PREFIX.length) },
77  { key: PREFS_KEY, has: k => k.startsWith(PREF_PREFIX) || PREF_KEYS.includes(k), name: k => k },
78]
79const bundleOf = (key: string): Bundle | undefined => BUNDLES.find(b => b.has(key))
80
81type Obj = Record<string, unknown>
82const asObj = (raw: unknown): Obj | undefined => (typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? (raw as Obj) : undefined)
83// Callers get a copy so a change cannot leak into the held value.
84const copy = (v: unknown): unknown => (typeof v === 'object' && v !== null ? JSON.parse(JSON.stringify(v)) : v)
85
86const held = new Map<string, { at: number; value: Promise<Obj | undefined> }>()
87let shared: { sessionId: string; at: number; root: string | undefined; set: Promise<Obj | undefined> } | undefined
88let ownSet: { sessionId: string; set: Promise<Obj | undefined> } | undefined
89export const forgetProjectSet = (): void => {
90  shared = undefined
91  ownSet = undefined
92}
93export const forgetBundles = (): void => {
94  held.clear()
95  shared = undefined
96  ownSet = undefined
97}
98
99// Writes to one bundle wait for each other so two changes at once both stay.
100let writing: Promise<unknown> = Promise.resolve()
101const inTurn = <T>(work: () => Promise<T>): Promise<T> => {
102  const run = writing.then(work, work)
103  writing = run.catch(() => undefined)
104  return run
105}
106
107async function gather(get: (key: string) => Promise<unknown>, b: Bundle, keys: string[]): Promise<Obj> {
108  const out: Obj = {}
109  for (const k of keys) if (b.has(k)) {
110    const v = await get(k)
111    if (v !== undefined) out[b.name(k)] = v
112  }
113  return out
114}
115
116// Never throws.
117export async function ensureBundles(i: Io): Promise<void> {
118  try {
119    const get = i.getGlobal ?? i.get
120    let keys: string[] | undefined
121    for (const b of BUNDLES) {
122      if (asObj(await get(b.key)) !== undefined) continue
123      keys ??= await i.keys()
124      await i.set(b.key, await gather(get, b, keys))
125    }
126  } catch {
127  }
128}
129
130// While a full view (Help, Settings, Arrange, a guide) is open an ordinary toast is held so it does not cover the list; urgent ones show at once. At most HOLD_MAX wait, none longer than HOLD_MS.
131export const toastHold: { on: () => boolean; held: { text: string; at: number }[]; show: ((text: string) => void) | undefined } = { on: () => false, held: [], show: undefined }
132export const HOLD_MAX = 3
133export const HOLD_MS = 3 * 60_000
134export function holdToast(text: string, now: number): boolean {
135  if (!toastHold.on()) return false
136  if (!toastHold.held.some(h => h.text === text)) toastHold.held = [...toastHold.held, { text, at: now }].slice(-HOLD_MAX)
137  return true
138}
139export function releaseHeldToasts(now: number = Date.now()): void {
140  if (toastHold.held.length === 0 || toastHold.show === undefined) return
141  const open = toastHold.on()
142  const out = toastHold.held.filter(h => !open || now - h.at >= HOLD_MS)
143  if (out.length === 0) return
144  toastHold.held = toastHold.held.filter(h => !out.includes(h))
145  for (const h of out) toastHold.show(h.text)
146}
147
148// A toast waits for the one before it so two cannot both pass the cap. Across sessions it may pass by one.
149let toasting: Promise<void> = Promise.resolve()
150
151// A failed store read shows the toast: the gate must never hide something by accident.
152export function withToastGate(given: Io): Io {
153  // Counted for the Computer card's own-cost line; in memory, no store key.
154  const base: Io = {
155    ...given,
156    set: (key, value) => {
157      noteWrite()
158      return given.set(key, value)
159    },
160    del: key => {
161      noteWrite()
162      return given.del(key)
163    },
164    run: (argv, init) => {
165      noteRun()
166      return given.run(argv, init)
167    },
168  }
169  // Read at most once per step.
170  let clockAt: Promise<number> | undefined
171  let uses = 0
172  const clock = (): Promise<number> => {
173    if (clockAt === undefined || uses >= 32) {
174      clockAt = base.now()
175      uses = 0
176    }
177    uses += 1
178    return clockAt
179  }
180  let gathered: { key: string; stamp: Promise<number>; value: Promise<Obj> } | undefined
181  const fresh = (at: number, now: number): boolean => now - at >= 0 && now - at < BUNDLE_TTL_MS
182
183  const bundle = async (b: Bundle): Promise<Obj | undefined> => {
184    const now = await clock()
185    const h = held.get(b.key)
186    if (h !== undefined && fresh(h.at, now)) return h.value
187    const value = base.get(b.key).then(asObj)
188    const entry = { at: now, value }
189    held.set(b.key, entry)
190    value.catch(() => {
191      if (held.get(b.key) === entry) held.delete(b.key)
192    })
193    return value
194  }
195
196  const projectSet = async (): Promise<Obj | undefined> => {
197    try {
198      const now = await clock()
199      if (shared !== undefined && fresh(shared.at, now)) return await shared.set
200      const sessionId = await base.sessionId()
201      const known = shared !== undefined && shared.sessionId === sessionId ? shared : undefined
202      const rootRead = known !== undefined ? Promise.resolve(known.root) : base.get(PROJECT_OF_KEY(sessionId)).then(r => (typeof r === 'string' && r !== '' ? r : undefined))
203      const root = await rootRead
204      const set = root === undefined ? Promise.resolve(undefined) : base.get(PROJSET_KEY(root)).then(asObj)
205      shared = { sessionId, at: now, root, set }
206      return await set
207    } catch {
208      shared = undefined
209      return undefined
210    }
211  }
212
213  // The session id comes from the project read just before, so this adds no call.
214  const sessionSet = async (): Promise<Obj | undefined> => {
215    try {
216      const sessionId = shared?.sessionId ?? (await base.sessionId())
217      if (ownSet === undefined || ownSet.sessionId !== sessionId) {
218        const set = base.get(SESSSET_KEY(sessionId)).then(asObj)
219        const entry = { sessionId, set }
220        ownSet = entry
221        set.catch(() => {
222          if (ownSet === entry) ownSet = undefined
223        })
224      }
225      return await ownSet.set
226    } catch {
227      ownSet = undefined
228      return undefined
229    }
230  }
231
232  const globalOf = async (key: string, b: Bundle): Promise<unknown> => {
233    const all = await bundle(b)
234    if (all !== undefined) return copy(all[b.name(key)])
235    // With no bundle yet, gather the small keys once per step; a new step or any write gathers again.
236    const stamp = clockAt
237    if (stamp === undefined) return base.get(key)
238    if (gathered === undefined || gathered.key !== b.key || gathered.stamp !== stamp) gathered = { key: b.key, stamp, value: base.keys().then(keys => gather(base.get, b, keys)) }
239    return copy((await gathered.value)[b.name(key)])
240  }
241  const read = async (key: string): Promise<unknown> => {
242    const b = bundleOf(key)
243    if (b === undefined) return base.get(key)
244    if (b.key === SETTINGS_KEY) {
245      const name = b.name(key)
246      const own = (await projectSet())?.[name]
247      const mine = (await sessionSet())?.[name]
248      if (typeof mine === 'string') return mine
249      if (typeof own === 'string') return own
250    }
251    return globalOf(key, b)
252  }
253
254  // Small key first, then the bundle as stored now, so another session's change is kept.
255  const change = (key: string, b: Bundle, value: unknown, isDelete: boolean): Promise<void> =>
256    inTurn(async () => {
257      gathered = undefined
258      if (isDelete) await base.del(key)
259      else await base.set(key, value)
260      const now = await base.now()
261      const all = asObj(await base.get(b.key)) ?? (await gather(base.get, b, await base.keys()))
262      if (isDelete) delete all[b.name(key)]
263      else all[b.name(key)] = copy(value)
264      await base.set(b.key, all)
265      held.set(b.key, { at: now, value: Promise.resolve(all) })
266    })
267  const forgetFor = (key: string): void => {
268    if (key === SETTINGS_KEY || key === PREFS_KEY) held.delete(key)
269    if (key.startsWith(PROJSET_PREFIX) || key.startsWith('cockpit:projectof:')) shared = undefined
270    if (key.startsWith(SESSSET_PREFIX)) ownSet = undefined
271  }
272
273  const getGlobal = async (key: string): Promise<unknown> => {
274    const b = bundleOf(key)
275    if (b !== undefined) return globalOf(key, b)
276    if (shared !== undefined && key === PROJECT_OF_KEY(shared.sessionId) && fresh(shared.at, await clock())) return shared.root
277    return base.get(key)
278  }
279
280  return {
281    ...base,
282    now: () => {
283      const t = base.now()
284      clockAt = t
285      uses = 0
286      return t
287    },
288    get: read,
289    getMany: async keys => {
290      const out: unknown[] = []
291      let layers: { own: Obj | undefined; mine: Obj | undefined } | undefined
292      const alls = new Map<string, Obj | undefined>()
293      for (const key of keys) {
294        const b = bundleOf(key)
295        if (b === undefined || b.key !== SETTINGS_KEY) {
296          out.push(await read(key))
297          continue
298        }
299        layers ??= { own: await projectSet(), mine: await sessionSet() }
300        const name = b.name(key)
301        const mine = layers.mine?.[name]
302        const own = layers.own?.[name]
303        if (typeof mine === 'string') out.push(mine)
304        else if (typeof own === 'string') out.push(own)
305        else {
306          if (!alls.has(b.key)) alls.set(b.key, await bundle(b))
307          const all = alls.get(b.key)
308          out.push(all !== undefined ? copy(all[name]) : await globalOf(key, b))
309        }
310      }
311      return out
312    },
313    getGlobalMany: async keys => {
314      const out: unknown[] = []
315      const alls = new Map<string, Obj | undefined>()
316      for (const key of keys) {
317        const b = bundleOf(key)
318        if (b === undefined) {
319          out.push(await getGlobal(key))
320          continue
321        }
322        if (!alls.has(b.key)) alls.set(b.key, await bundle(b))
323        const all = alls.get(b.key)
324        out.push(all !== undefined ? copy(all[b.name(key)]) : await globalOf(key, b))
325      }
326      return out
327    },
328    set: async (key, value) => {
329      const b = bundleOf(key)
330      if (b !== undefined) return change(key, b, value, false)
331      forgetFor(key)
332      await base.set(key, value)
333    },
334    del: async key => {
335      const b = bundleOf(key)
336      if (b !== undefined) return change(key, b, undefined, true)
337      forgetFor(key)
338      await base.del(key)
339    },
340    getGlobal,
341    toast: (text, urgent) => {
342      if (urgent === true) {
343        base.toast(trFill(text))
344        return
345      }
346      const run = async (): Promise<void> => {
347        try {
348          const now = await base.now()
349          // An ordinary toast is held during focus unless it says a session needs you.
350          if (!passesFocus(text) && isFocused(parseFocus(await base.get(FOCUS_KEY)), now)) return
351          const [seenRaw, logRaw] = await Promise.all([base.get(TOAST_SEEN_KEY), base.get(TOAST_LOG_KEY)])
352          const r = repeatVerdict(seenRaw, now, text)
353          if (!r.show) return
354          const v = toastVerdict(logRaw, now)
355          await Promise.all([base.set(TOAST_SEEN_KEY, r.seen), base.set(TOAST_LOG_KEY, v.stamps)])
356          if (!v.show) return
357        } catch {
358        }
359        if (holdToast(text, Date.now())) {
360          toastHold.show = t => base.toast(trFill(t))
361          return
362        }
363        base.toast(trFill(text))
364      }
365      toasting = toasting.then(run, run)
366    },
367  }
368}
369
hooks/core/platform.ts 151 lines
1// Path and text helpers that behave the same on Mac and Windows. No imports and no process.platform, so tests run both styles anywhere.
2export type PathStyle = 'posix' | 'win32'
3
4export const detectStyle = (path: string): PathStyle => (/^[A-Za-z]:/.test(path) || path.includes('\\') ? 'win32' : 'posix')
5
6export function homeDir(env: Record<string, string | undefined>): string | undefined {
7  if (env.HOME) return env.HOME
8  if (env.USERPROFILE) return env.USERPROFILE
9  if (env.HOMEDRIVE && env.HOMEPATH) return env.HOMEDRIVE + env.HOMEPATH
10  return undefined
11}
12
13// The plugin loader allows `$.env.get` only with a literal name, so each feature hands in four closures. HOME is read first so a Mac reads what it always did.
14export type HomeEnv = { HOME: () => Promise<string | undefined>; USERPROFILE: () => Promise<string | undefined>; HOMEDRIVE: () => Promise<string | undefined>; HOMEPATH: () => Promise<string | undefined> }
15export async function homeFrom(env: HomeEnv): Promise<string> {
16  const home = await env.HOME()
17  if (home) return home
18  return homeDir({ USERPROFILE: await env.USERPROFILE(), HOMEDRIVE: await env.HOMEDRIVE(), HOMEPATH: await env.HOMEPATH() }) ?? ''
19}
20
21export const lastPart = (path: string): string => parts(path).at(-1) ?? ''
22
23type Split = { root: string; segs: string[] }
24
25function split(path: string, style: PathStyle): Split {
26  const win = style === 'win32'
27  const raw = win ? path.replace(/\\/g, '/') : path
28  let root = ''
29  let rest = raw
30  const unc = win ? /^\/\/([^/]+)(.*)$/.exec(raw) : null
31  if (unc !== null) {
32    root = `\\\\${unc[1]}`
33    rest = unc[2]
34  } else if (win && /^[A-Za-z]:/.test(raw)) {
35    root = raw.slice(0, 2)
36    rest = raw.slice(2)
37  } else if (raw.startsWith('/')) root = '/'
38  const segs: string[] = []
39  for (const s of rest.split('/')) {
40    if (s === '' || s === '.') continue
41    if (s === '..' && segs.length > 0 && segs[segs.length - 1] !== '..') segs.pop()
42    else segs.push(s)
43  }
44  return { root, segs }
45}
46
47export function parts(path: string, style: PathStyle = detectStyle(path)): string[] {
48  const { root, segs } = split(path, style)
49  return root === '' || root === '/' ? segs : [root, ...segs]
50}
51
52export function lastName(path: string, style: PathStyle = detectStyle(path)): string {
53  const { segs } = split(path, style)
54  return segs.length === 0 ? path : segs[segs.length - 1]
55}
56
57// Whole parts only.
58export function isInside(parent: string, child: string, style: PathStyle = detectStyle(parent + child)): boolean {
59  const a = split(parent, style)
60  const b = split(child, style)
61  const fold = (s: string): string => (style === 'win32' ? s.toLowerCase() : s)
62  if (fold(a.root) !== fold(b.root)) return false
63  if (a.segs.length > b.segs.length) return false
64  return a.segs.every((s, i) => fold(s) === fold(b.segs[i]))
65}
66
67// Windows is UNVERIFIED: assumed the same idea (drive colon and slashes become '-'), other characters kept, until a real Windows PC shows what Claude Code does.
68export function projectFolderName(path: string, style: PathStyle = detectStyle(path)): string {
69  return style === 'win32' ? path.replace(/[:\\/]/g, '-') : path.replace(/[^A-Za-z0-9]/g, '-')
70}
71
72export const lines = (text: string): string[] => text.split(/\r?\n/)
73
74export function joinPath(style: PathStyle, ...pieces: string[]): string {
75  const sep = style === 'win32' ? '\\' : '/'
76  const any = style === 'win32' ? /[\\/]+/g : /\/+/g
77  const clean = pieces.filter(p => p !== '').map(p => p.replace(any, sep))
78  if (clean.length === 0) return ''
79  if (style === 'win32' && /^[\\/]{2}[^\\/]/.test(pieces.find(p => p !== '') ?? '')) clean[0] = sep + clean[0]
80  const edge = (p: string): string => {
81    let s = p
82    while (s.startsWith(sep)) s = s.slice(1)
83    while (s.endsWith(sep)) s = s.slice(0, -1)
84    return s
85  }
86  let head = clean[0]
87  while (head.length > 1 && head.endsWith(sep) && head !== sep) head = head.slice(0, -1)
88  const rest = clean.slice(1).map(edge).filter(p => p !== '')
89  if (rest.length === 0) return clean[0]
90  const base = head === sep ? '' : head
91  return [base, ...rest].join(sep)
92}
93
94// Windows style ignores letter case and either slash.
95export function homeShown(path: string, home: string): string {
96  if (home === '') return path
97  if (detectStyle(home) !== 'win32') return path.startsWith(home) ? `~${path.slice(home.length)}` : path
98  if (!isInside(home, path, 'win32')) return path
99  const rest = parts(path, 'win32').slice(parts(home, 'win32').length)
100  return rest.length === 0 ? '~' : `~\\${rest.join('\\')}`
101}
102
103export const homeRel = (rel: string, home: string): string => (detectStyle(home) === 'win32' ? `~\\${rel.replace(/\//g, '\\')}` : `~/${rel}`)
104
105
106export const isAbsolute = (path: string): boolean => path.startsWith('/') || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith('\\\\')
107
108// An empty base gives '/rel'.
109export const under = (base: string, ...rel: string[]): string => (base === '' ? joinPath('posix', '/', ...rel) : joinPath(detectStyle(base), base, ...rel))
110
111export function samePath(a: string, b: string): boolean {
112  if (detectStyle(a + b) === 'win32') return isInside(a, b, 'win32') && isInside(b, a, 'win32')
113  const cut = (p: string): string => (p.length > 1 ? p.replace(/\/+$/, '') : p)
114  return cut(a) === cut(b)
115}
116
117export function parentDir(path: string): string {
118  const cut = detectStyle(path) === 'win32' ? Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) : path.lastIndexOf('/')
119  if (cut < 0) return ''
120  const up = path.slice(0, cut)
121  // Never a bare 'C:', which means the current folder of that drive.
122  return /^[A-Za-z]:$/.test(up) ? `${up}${path[cut]}` : up
123}
124
125export function fileName(path: string): string {
126  const cut = detectStyle(path) === 'win32' ? Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) : path.lastIndexOf('/')
127  return path.slice(cut + 1)
128}
129
130export function below(root: string, path: string): string {
131  if (root === '') return path
132  const style = detectStyle(root + path)
133  if (style === 'posix') return path.startsWith(`${root}/`) ? path.slice(root.length + 1) : path
134  if (!isInside(root, path, style)) return path
135  const rest = parts(path, style).slice(parts(root, style).length)
136  return rest.length === 0 ? path : rest.join('\\')
137}
138
139export const strictlyInside = (root: string, path: string): boolean => below(root, path) !== path
140
141export function walkUp(cwd: string, stop: string, max = 12): string[] {
142  const out: string[] = []
143  let dir = cwd
144  for (let n = 0; n < max && dir !== '' && dir !== '/' && !/^[A-Za-z]:[\\/]?$/.test(dir); n += 1) {
145    out.push(dir)
146    if (samePath(dir, stop)) break
147    dir = parentDir(dir)
148  }
149  return out
150}
151
hooks/features/agentcap.ts 225 lines
1// Agent cap runtime: count helper agents in flight (this session in memory, every session in the shared store) and warn or hold at the limit.
2import type { EngineInterface, On, Timer } from 'claude-code'
3
4import { APP_USAGE_KEY, parseStoredUsage } from '../core/appusage'
5import { postBand } from '../core/band'
6import { BOARD_KEY, parseBoard, runningCount } from '../core/agentboard'
7import type { Status } from '../core/agentboard'
8import { t } from '../core/lang'
9import { money } from '../core/prices'
10import { DEPTH_MAX, CAP_DEPTH_BAND, CAP_DEPTH_WHAT, CAP_HOLD_WHAT, CAP_SPEND_BAND, CAP_SPEND_WHAT, CAP_WHAT, capMaxOf, capVerdict, depthOf, depthVerdict, isRunnerSpawn, parseCount, roomVerdict, spendMaxOf, spendVerdict, totalRunning } from '../core/agentcap'
11import { roomOf } from '../core/computer'
12import type { Room } from '../core/computer'
13import { LAPTOP_KEY } from '../core/crewlaptop'
14import type { Laptop } from '../core/crewlaptop'
15import { withToastGate } from '../core/io'
16import { homeFrom } from '../core/platform'
17import type { Io } from '../core/io'
18import { HISTORY_KEY, parseHistory } from '../core/pace'
19import { HELPER_NOTE_MIN, helperFitNote, windowMinutesLeft } from '../core/planfit'
20import { ORCH_KEY, parseRun } from '../core/orchestra'
21import { readSetting } from '../core/settings'
22import { tellsClaude } from '../core/tellclaude'
23import { LEDGER_KEY, pushLog } from './compaction'
24
25// IO-BLOCK-START
26function io($: EngineInterface): Io {
27  return withToastGate({
28    now: () => $.clock.now(),
29    home: () => homeFrom({ HOME: () => $.env.get('HOME'), USERPROFILE: () => $.env.get('USERPROFILE'), HOMEDRIVE: () => $.env.get('HOMEDRIVE'), HOMEPATH: () => $.env.get('HOMEPATH') }),
30    sessionId: () => $.session.id(),
31    get: key => $.store.get(key),
32    set: (key, value) => $.store.set(key, value),
33    del: key => $.store.delete(key),
34    keys: () => $.store.keys(),
35    read: path => $.fs.read(path),
36    write: (path, text) => $.fs.write(path, text),
37    run: (argv, init) => $.process.run(argv, init),
38    ask: (question, options) => $.ui.ask(question, options),
39    complete: req => $.model.complete(req),
40    toast: text => $.ui.toast(text),
41    invalidate: () => $.ui.invalidate('ui.render'),
42  })
43}
44// IO-BLOCK-END
45
46const PREFIX = 'cockpit:agents:'
47let mine = 0
48let warnedAt = 0
49const WARN_GAP_MS = 5 * 60_000
50let fitAt = -Infinity
51const FIT_GAP_MS = 10 * 60_000
52
53export async function runningNow(i: Io, statuses?: Status[]): Promise<number> {
54  const keys = (await i.keys()).filter(k => k.startsWith(PREFIX))
55  const counts = []
56  for (const k of keys) counts.push(parseCount(await i.get(k)))
57  const now = await i.now()
58  // Background helpers are counted from the agent board: only the start call of one runs inside this hook.
59  return totalRunning(counts, now) + runningCount(parseBoard(await i.get(BOARD_KEY)), now, statuses === undefined ? undefined : { session: await i.sessionId(), statuses })
60}
61async function roomNow(i: Io, running: number): Promise<Room | undefined> {
62  if ((await readSetting(i, 'laptop.mode')) !== 'on') return undefined
63  const kept = (await i.get(LAPTOP_KEY)) as Laptop | undefined
64  if (typeof kept !== 'object' || kept === null || typeof kept.at !== 'number') return undefined
65  return roomOf(kept, { running, max: capMaxOf(await readSetting(i, 'cap.max')), capOn: (await readSetting(i, 'cap.mode')) !== 'off' }, await i.now())
66}
67
68// Never holds a helper.
69async function fitNote(i: Io): Promise<string | undefined> {
70  const now = await i.now()
71  if (now - fitAt < FIT_GAP_MS || (await readSetting(i, 'limits.warn')) === 'off') return undefined
72  const usage = parseStoredUsage(await i.get(APP_USAGE_KEY))
73  if (usage === undefined) return undefined
74  const left = windowMinutesLeft(usage, parseHistory(await i.get(HISTORY_KEY)), now)
75  if (left === undefined || left > HELPER_NOTE_MIN) return undefined
76  fitAt = now
77  return helperFitNote(left)
78}
79
80const publish = async (i: Io): Promise<void> => i.set(PREFIX + (await i.sessionId()), { n: mine, at: await i.now() })
81
82const HEARTBEAT_MS = 4 * 60_000
83let heartbeat: Timer | undefined
84function startHeartbeat($: EngineInterface): void {
85  if (heartbeat !== undefined) return
86  const timer = $.clock.every(HEARTBEAT_MS, () => void publish(io($)).catch(() => undefined))
87  heartbeat = timer
88}
89const stopHeartbeat = (): void => {
90  if (mine > 0) return
91  heartbeat?.cancel()
92  heartbeat = undefined
93}
94
95// Spend per request: the session's cost when the person last sent a prompt (in memory; one session per process)
96const spendMem: { base?: number } = {}
97async function costNow($: EngineInterface): Promise<number | undefined> {
98  try {
99    const usage = await $.session.usage()
100    const usd = usage.cost?.usd
101    return typeof usd === 'number' && Number.isFinite(usd) ? usd : undefined
102  } catch {
103    return undefined
104  }
105}
106export const spentSince = (base: number | undefined, now: number | undefined): number | undefined => (now === undefined ? undefined : Math.max(0, now - (base ?? now)))
107
108// The agents of this session by id, each with its parent's id; read only for a spawn inside an agent
109async function parentsOf($: EngineInterface): Promise<Map<string, string | undefined>> {
110  try {
111    const list = await $.agent.list()
112    return new Map(list.map(a => [a.id, a.parentId]))
113  } catch {
114    return new Map()
115  }
116}
117
118// Depth and spend caps: Stop refuses the new agent and says why and how to lift it; Warn says it once in a while. Never throws.
119export async function capsVerdict(i: Io, facts: { depth: number; spent: number | undefined }): Promise<{ deny?: string; band?: string; what?: string; warn?: string }> {
120  const mode = await readSetting(i, 'cap.mode')
121  if (mode === 'off') return {}
122  const d = depthVerdict(mode, facts.depth)
123  const v = d.act ? d : spendVerdict(mode, facts.spent, spendMaxOf(await readSetting(i, 'cap.spend')))
124  if (!v.act) return {}
125  if (!v.hold) return { warn: d.act ? t('pane.agents_go_n_levels_deep', { n: facts.depth, m: DEPTH_MAX }) : t('pane.this_request_has_cost_usd', { usd: money(facts.spent ?? 0), max: money(spendMaxOf(await readSetting(i, 'cap.spend'))) }) }
126  return { deny: v.reason, band: d.act ? CAP_DEPTH_BAND : CAP_SPEND_BAND, what: d.act ? CAP_DEPTH_WHAT : CAP_SPEND_WHAT }
127}
128
129export function registerAgentCap(on: On): void {
130  on('prompt.submit', { text: /(?<agentcap>)/ }, async ($, e, next) => {
131    void costNow($).then(usd => {
132      spendMem.base = usd
133    })
134    return next(e)
135  }).catch(($, e, next) => next(e))
136
137  on('agent.spawn', { subagentType: /(?<agentcap>)/ }, async ($, e, next) => {
138    try {
139      const i = io($)
140      const depth = e.parentAgentId === undefined ? 1 : depthOf(e.parentAgentId, await parentsOf($))
141      // The task runner has its own budget: its helpers are not stopped by the per-request spend (the depth cap still holds)
142      const runner = isRunnerSpawn(next.origin.plugin, parseRun(await i.get(ORCH_KEY(await i.sessionId()))), e)
143      const spent = runner ? undefined : spentSince(spendMem.base, await costNow($))
144      const v = await capsVerdict(i, { depth, spent })
145      const now = await i.now()
146      if (v.deny !== undefined) {
147        await pushLog(i, LEDGER_KEY, { at: now, session: await i.sessionId(), what: v.what ?? CAP_HOLD_WHAT, detail: v.deny, how: 'auto', did: true })
148        await postBand(i, 'warn', 'agentcap', v.band ?? CAP_SPEND_BAND, 3 * 60_000)
149        return { deny: v.deny }
150      }
151      if (v.warn !== undefined && now - warnedAt >= WARN_GAP_MS) {
152        warnedAt = now
153        i.toast(v.warn)
154      }
155    } catch {
156      // the caps never break the session
157    }
158    return next(e)
159  }).catch(($, e, next) => next(e))
160
161  on('tool.call', { tool: /(?<agentcap>)/ }, async ($, e, next) => {
162    if (e.tool !== 'Agent') return next(e)
163    const i = io($)
164    let counted = false
165    let note: string | undefined
166    try {
167      const mode = await readSetting(i, 'cap.mode')
168      let statuses: Status[] | undefined
169      try {
170        const listed = await $.agent.list()
171        statuses = listed.map(a => ({ id: a.id, status: a.status }))
172      } catch {
173        statuses = undefined
174      }
175      const running = await runningNow(i, statuses)
176      let v = capVerdict(mode, running, capMaxOf(await readSetting(i, 'cap.max')))
177      if (!v.act && mode !== 'off') v = roomVerdict(mode, await roomNow(i, running))
178      if (v.act) {
179        const now = await i.now()
180        if (v.hold) {
181          await pushLog(i, LEDGER_KEY, { at: now, session: await i.sessionId(), what: CAP_HOLD_WHAT, detail: v.reason, how: 'auto', did: true })
182          await postBand(i, 'warn', 'agentcap', v.reason.includes('computer is full') ? 'Agent stopped: the computer is full' : 'Agent cap reached', 3 * 60_000)
183          return { deny: v.reason }
184        }
185        if (now - warnedAt >= WARN_GAP_MS) {
186          warnedAt = now
187          await pushLog(i, LEDGER_KEY, { at: now, session: await i.sessionId(), what: CAP_WHAT, detail: v.reason, how: 'auto', did: true })
188          i.toast(v.reason)
189        }
190      }
191      mine += 1
192      counted = true
193      startHeartbeat($)
194      await publish(i)
195      note = (await tellsClaude(i)) ? await fitNote(i) : undefined
196    } catch {
197      // the limit never breaks the session
198    }
199    try {
200      const result = await next(e)
201      return note === undefined || result.deny !== undefined ? result : { ...result, context: [...(result.context ?? []), note] }
202    } finally {
203      if (counted) {
204        mine = Math.max(0, mine - 1)
205        stopHeartbeat()
206        try {
207          await publish(i)
208        } catch {
209        }
210      }
211    }
212  }).catch(($, e, next) => next(e))
213
214  // A closed session takes its count away at once; it does not wait out the count's time limit.
215  on('session.end', { sessionId: /(?<agentcapend>)/ }, async ($, e, next) => {
216    try {
217      mine = 0
218      stopHeartbeat()
219      await io($).del(PREFIX + e.sessionId)
220    } catch {
221    }
222    return next(e)
223  }).catch(($, e, next) => next(e))
224}
225
hooks/features/away.ts 261 lines
1// Away recap and the Away mode.
2import { tr } from '../core/lang'
3import { fillIn } from '../core/fillin'
4import { sayIn } from './saylang'
5import type { EngineInterface, On } from 'claude-code'
6
7import { buildDigest, costSince, awayCall, modeLines, parseDigest, parseEvents, parseRun, parseSaved, restoreLines, watchEvents, digestText } from '../core/away'
8import type { Digest, Restore, Run, Saved } from '../core/away'
9import { AWAY_EVENTS_KEY, AWAY_RUN_KEY, AWAY_SAVED_KEY, BUDGET_SET, COST_STATE_PREFIX, DIGEST_KEY, DIGEST_WHAT, NO_DIGEST, POLICY_SET, seenToast, timerEndDetail, timerToast } from '../core/away'
10import { SESSION_BUDGETS, parseState, spendOf } from '../core/cost'
11import { optionNumber } from '../core/budget'
12import { clearBand } from '../core/band'
13import { AWAY_KEY, AWAY_OFF_WHAT, AWAY_POLICY_KEY, awayText, parseAway } from '../core/guardworld'
14import { withToastGate } from '../core/io'
15import { homeFrom } from '../core/platform'
16import type { Io } from '../core/io'
17import { listRecords } from '../core/record'
18import { findSetting, readSetting, settingStoreKey, writeSetting } from '../core/settings'
19import { LEDGER_KEY, pushLog, readLog } from './compaction'
20import { collectInbox, liveRows } from './inbox'
21import { armOnce } from './everyonce'
22import { isFolded, subArgs } from '../core/menu'
23import { BY_PERSON_ONLY, byPerson } from '../core/origin'
24
25// IO-BLOCK-START
26function io($: EngineInterface): Io {
27  return withToastGate({
28    now: () => $.clock.now(),
29    home: () => homeFrom({ HOME: () => $.env.get('HOME'), USERPROFILE: () => $.env.get('USERPROFILE'), HOMEDRIVE: () => $.env.get('HOMEDRIVE'), HOMEPATH: () => $.env.get('HOMEPATH') }),
30    sessionId: () => $.session.id(),
31    get: key => $.store.get(key),
32    set: (key, value) => $.store.set(key, value),
33    del: key => $.store.delete(key),
34    keys: () => $.store.keys(),
35    read: path => $.fs.read(path),
36    write: (path, text) => $.fs.write(path, text),
37    run: (argv, init) => $.process.run(argv, init),
38    ask: (question, options) => $.ui.ask(question, options),
39    complete: req => $.model.complete(req),
40    toast: text => $.ui.toast(text),
41    invalidate: () => $.ui.invalidate('ui.render'),
42  })
43}
44// IO-BLOCK-END
45
46const CHECK_MS = 20_000
47const BUDGET_KEY = 'cost.budget'
48const SESSION_BUDGET_KEY = 'cost.session'
49
50// Every session also checks, so the mode ends even if this session is gone.
51let endTimer: { cancel: () => void } | undefined
52
53const ledger = async (i: Io, sid: string, what: string, detail: string, how: 'auto' | 'typed'): Promise<void> => pushLog(i, LEDGER_KEY, { at: await i.now(), session: sid, what, detail, how, did: true })
54
55// What each session has cost, in dollars: the engine's own total when it gave one
56async function costNow(i: Io, now: number): Promise<Record<string, number>> {
57  const out: Record<string, number> = {}
58  for (const k of (await i.keys()).filter(x => x.startsWith(COST_STATE_PREFIX))) out[k.slice(COST_STATE_PREFIX.length)] = spendOf(parseState(await i.get(k), now)).usd
59  return out
60}
61
62async function collectEvents(i: Io, run: Run) {
63  const { rows } = await liveRows(i)
64  const known = parseEvents(await i.get(AWAY_EVENTS_KEY))
65  const events = watchEvents(
66    rows.map(r => ({ sid: r.rec.sessionId, name: r.name, kind: r.kind, since: r.kind === 'needs' && r.rec.ask !== undefined ? r.rec.ask.since : r.rec.stateSince })),
67    run.at,
68    known,
69  )
70  if (events.length !== known.length) await i.set(AWAY_EVENTS_KEY, events)
71  return events
72}
73
74async function digestNow(i: Io, run: Run, ended: boolean, to: number): Promise<Digest> {
75  const events = await collectEvents(i, run)
76  const spent = costSince(run.costBase, await costNow(i, to))
77  const { items } = await collectInbox(i)
78  return buildDigest({ from: run.at, to, ledger: await readLog(i, LEDGER_KEY), events, spent, waiting: items, ended })
79}
80
81export async function freshWhileAway(i: Io, text: string): Promise<string> {
82  const fresh = awayText({ away: parseAway(await i.get(AWAY_KEY)) !== undefined, policy: (await i.get(settingStoreKey(AWAY_POLICY_KEY))) === 'careful' ? 'careful' : 'off', refused: [] }).split('\n')[1] ?? ''
83  return text
84    .split('\n')
85    .map(l => (l.startsWith('While away: ') || l.startsWith(`${tr('While away')}: `) ? fresh : l)) // en-only: the start of the switch's own line, matched, not shown
86    .join('\n')
87}
88
89// Sets only what is not already as wanted, and keeps the old values so the end can put them back.
90async function startRun(i: Io, awayAt: number, forMs: number | undefined): Promise<{ run: Run; saved: Saved } | undefined> {
91  if (parseRun(await i.get(AWAY_RUN_KEY)) !== undefined) return undefined
92  const now = await i.now()
93  const costBase = await costNow(i, now)
94  const run: Run = { at: awayAt, ...(forMs === undefined ? {} : { until: now + forMs }), costBase }
95  // The run is written first: it is the claim, so two sessions cannot both begin the mode.
96  await i.set(AWAY_RUN_KEY, run)
97  await i.set(AWAY_EVENTS_KEY, [])
98  const saved: Saved = {}
99  const rawPolicy = await i.get(settingStoreKey(AWAY_POLICY_KEY))
100  if (rawPolicy !== POLICY_SET && findSetting(AWAY_POLICY_KEY) !== undefined && (await writeSetting(i, AWAY_POLICY_KEY, POLICY_SET))) saved.policy = { old: typeof rawPolicy === 'string' ? rawPolicy : null, set: POLICY_SET }
101  const budget = findSetting(BUDGET_KEY)
102  if (budget !== undefined) {
103    const raw = await i.get(settingStoreKey(BUDGET_KEY))
104    const cur = raw === 'off' || raw === 'warn' || raw === 'stop' ? raw : budget.default
105    if (cur !== BUDGET_SET && (await writeSetting(i, BUDGET_KEY, BUDGET_SET))) {
106      saved.budget = { old: typeof raw === 'string' ? raw : null, set: BUDGET_SET, limit: optionNumber(await i.get(settingStoreKey(SESSION_BUDGET_KEY)), SESSION_BUDGETS, Number(findSetting(SESSION_BUDGET_KEY)?.default ?? 25)) }
107    }
108  }
109  await i.set(AWAY_SAVED_KEY, saved)
110  i.invalidate()
111  return { run, saved }
112}
113
114async function putBack(i: Io, key: string, entry: { old: string | null; set: string }): Promise<'back' | 'kept'> {
115  if ((await i.get(settingStoreKey(key))) !== entry.set) return 'kept'
116  if (entry.old === null) await i.del(settingStoreKey(key))
117  else await writeSetting(i, key, entry.old)
118  return 'back'
119}
120
121async function finishRun(i: Io, how: 'auto' | 'typed'): Promise<{ lines: string[]; digest?: Digest } | undefined> {
122  const run = parseRun(await i.get(AWAY_RUN_KEY))
123  if (run === undefined) return undefined
124  await sayIn(i)
125  await i.del(AWAY_RUN_KEY)
126  const saved = parseSaved(await i.get(AWAY_SAVED_KEY))
127  await i.del(AWAY_SAVED_KEY)
128  const restore: Restore = {}
129  if (saved.policy !== undefined) restore.policy = await putBack(i, AWAY_POLICY_KEY, saved.policy)
130  if (saved.budget !== undefined) restore.budget = await putBack(i, BUDGET_KEY, saved.budget)
131  const now = await i.now()
132  let digest: Digest | undefined
133  if ((await readSetting(i, 'away.digest')) !== 'off') {
134    digest = await digestNow(i, run, true, now)
135    await i.set(DIGEST_KEY, { at: now, from: run.at, to: now, text: digest.text })
136    await ledger(i, await i.sessionId(), DIGEST_WHAT, digest.headline.slice(0, 220), how)
137  }
138  await i.del(AWAY_EVENTS_KEY)
139  for (const rec of await listRecords(i)) await clearBand(i, 'away', rec.sessionId)
140  i.invalidate()
141  return { lines: restoreLines(saved, restore), ...(digest === undefined ? {} : { digest }) }
142}
143
144async function endByTimer(i: Io): Promise<void> {
145  if (parseAway(await i.get(AWAY_KEY)) !== undefined) {
146    await i.del(AWAY_KEY)
147    await ledger(i, await i.sessionId(), AWAY_OFF_WHAT, timerEndDetail, 'auto')
148  }
149  if ((await finishRun(i, 'auto')) !== undefined) i.toast(tr(timerToast))
150}
151
152function arm($: EngineInterface, ms: number): void {
153  endTimer?.cancel()
154  const timer = $.clock.after(Math.max(0, ms), () => void awayCheck(io($)).catch(() => undefined))
155  endTimer = timer
156}
157
158// Exported so that a test can run one check by hand (a test clock does not drive a timer made at the start of the session).
159export async function awayCheck(i: Io): Promise<void> {
160  try {
161    const now = await i.now()
162    const away = parseAway(await i.get(AWAY_KEY))
163    const run = parseRun(await i.get(AWAY_RUN_KEY))
164    if (away !== undefined && run === undefined) {
165      await startRun(i, away.at, undefined)
166    } else if (away === undefined && run !== undefined) {
167      if ((await finishRun(i, 'auto')) !== undefined) i.toast(tr(seenToast))
168    } else if (away !== undefined && run !== undefined) {
169      if (run.until !== undefined && now >= run.until) await endByTimer(i)
170      else await collectEvents(i, run)
171    }
172  } catch {
173  }
174}
175
176export function registerAway(on: On): void {
177  on('session.start', { cwd: /(?<away>)/ }, async ($, e, next) => {
178    try {
179      const timer = $.clock.every(CHECK_MS, () => void awayCheck(io($)))
180      armOnce('away', timer)
181      const run = parseRun(await io($).get(AWAY_RUN_KEY))
182      const nowMs = await $.clock.now()
183      if (run?.until !== undefined) arm($, run.until - nowMs)
184    } catch {
185      // the digest and the timer are optional: a failure shows less, never breaks the session
186    }
187    return next(e)
188  }).catch(($, e, next) => next(e))
189
190  // It never answers alone: the switch's own answer is the base of what it returns.
191  on('command.run', { command: 'vaken-away' }, async ($, e, next) => {
192    if (isFolded(e.command, e.args)) return next(e)
193    const call = awayCall(e.args)
194    const i = io($)
195    await sayIn(i)
196    if (call.durationError !== undefined) return { text: tr(call.durationError) }
197
198    if (call.ask.kind === 'on') {
199      const r = await next({ ...e, args: call.passArgs })
200      try {
201        const away = parseAway(await i.get(AWAY_KEY))
202        if (away !== undefined) {
203          const now = await i.now()
204          const started = await startRun(i, away.at, call.forMs)
205          let run = started?.run ?? parseRun(await i.get(AWAY_RUN_KEY))
206          const saved = started?.saved ?? parseSaved(await i.get(AWAY_SAVED_KEY))
207          const lines: string[] = []
208          if (started === undefined && run !== undefined && call.forMs !== undefined) {
209            run = { ...run, until: now + call.forMs }
210            await i.set(AWAY_RUN_KEY, run)
211            lines.push(tr('The end time is changed.'))
212          }
213          if (run !== undefined) {
214            if (run.until !== undefined) arm($, run.until - now)
215            else endTimer?.cancel()
216            lines.push(...modeLines(run, saved, now))
217            return { ...r, text: [await freshWhileAway(i, r.text ?? ''), '', ...lines].join('\n') }
218          }
219        }
220      } catch {
221      }
222      return r
223    }
224
225    if (call.ask.kind === 'off') {
226      // Away mode tightens the guard while the person is gone, so only the person may end it.
227      if (!byPerson(e.origin)) return { text: BY_PERSON_ONLY }
228      const r = await next(e)
229      try {
230        if (parseAway(await i.get(AWAY_KEY)) === undefined) {
231          endTimer?.cancel()
232          const done = await finishRun(i, 'typed')
233          if (done !== undefined) return { ...r, text: [await freshWhileAway(i, r.text ?? ''), '', ...(done.digest === undefined ? [] : [done.digest.text, '']), ...done.lines].join('\n').trimEnd() }
234        }
235      } catch {
236      }
237      return r
238    }
239
240    const r = await next(e)
241    try {
242      const run = parseRun(await i.get(AWAY_RUN_KEY))
243      if (run !== undefined && parseAway(await i.get(AWAY_KEY)) !== undefined) return { ...r, text: [r.text ?? '', '', ...modeLines(run, parseSaved(await i.get(AWAY_SAVED_KEY)), await i.now())].join('\n') }
244    } catch {
245    }
246    return r
247  }).catch(($, e, next) => next(e))
248
249  on('command.run', { command: 'vaken-away' }, async ($, e, next) => {
250    const rest0 = subArgs(e.args, 'digest')
251    if (rest0 === undefined) return next(e)
252    const i = io($)
253    await sayIn(i)
254    const now = await i.now()
255    const run = parseRun(await i.get(AWAY_RUN_KEY))
256    if (run !== undefined) return { text: `${(await digestNow(i, run, false, now)).text}\n\n${tr('Away mode is still on. /vaken-away off ends it and keeps the digest.')}` }
257    const saved = parseDigest(await i.get(DIGEST_KEY))
258    return { text: saved === undefined ? tr(NO_DIGEST) : digestText(saved, now) }
259  })
260}
261
hooks/features/attention.ts 259 lines
1// Attention runtime: the heartbeat (a working session that went quiet, or one shell step that runs long), the notification router (toasts for other sessions)
2import type { EngineInterface, On } from 'claude-code'
3
4import { parseStoredUsage, APP_USAGE_KEY } from '../core/appusage'
5import { parseStoredSessions, APP_SESSIONS_KEY } from '../core/appsessions'
6import { RECAP_AFTER_MS, RUNAWAY_BAND_ID, batchText, glanceLines, heartbeat, isQuiet, noticePlan, notices, recapWords, runawayLine, runawayMem, runawayNow, stepAsked, stepEnd, stepStart, stepsReset } from '../core/attention'
7import { stepHash } from '../core/allowrules'
8import { fieldsOf } from '../core/eventfields'
9import { redrawIfChanged } from '../core/redraw'
10import { isShellTool } from '../core/tools'
11import type { NoticeRow, Seen } from '../core/attention'
12import { clearBand, postBand } from '../core/band'
13import { cacheWords } from '../core/cachefacts'
14import { actedToday } from '../core/ledger'
15import { withToastGate } from '../core/io'
16import { homeFrom } from '../core/platform'
17import type { Io } from '../core/io'
18import { alivePids, listRecords, readRecord } from '../core/record'
19import type { SessionRecord } from '../core/record'
20import { readNote } from '../core/flush'
21import { readState, stateKey } from '../core/proof'
22import { readSetting } from '../core/settings'
23import { WATCH_BAND_ID, WATCH_BAND_MS, stepWatches } from '../core/watch'
24import { buildView, cacheTtlMs, hereWord, limitAgo, limitBlocks, limitLabel, needsCount, resetSaid } from './home/logic'
25import type { View } from './home/logic'
26import { loadView } from './home/load'
27import { armOnce } from './everyonce'
28import { subArgs } from '../core/menu'
29import { tellNow } from '../core/tellme'
30import { sayIn } from './saylang'
31import { tr } from '../core/lang'
32
33// IO-BLOCK-START
34function io($: EngineInterface): Io {
35  return withToastGate({
36    now: () => $.clock.now(),
37    home: () => homeFrom({ HOME: () => $.env.get('HOME'), USERPROFILE: () => $.env.get('USERPROFILE'), HOMEDRIVE: () => $.env.get('HOMEDRIVE'), HOMEPATH: () => $.env.get('HOMEPATH') }),
38    sessionId: () => $.session.id(),
39    get: key => $.store.get(key),
40    set: (key, value) => $.store.set(key, value),
41    del: key => $.store.delete(key),
42    keys: () => $.store.keys(),
43    read: path => $.fs.read(path),
44    write: (path, text) => $.fs.write(path, text),
45    run: (argv, init) => $.process.run(argv, init),
46    ask: (question, options) => $.ui.ask(question, options),
47    complete: req => $.model.complete(req),
48    toast: text => $.ui.toast(text),
49    invalidate: () => $.ui.invalidate('ui.render'),
50  })
51}
52// IO-BLOCK-END
53
54const CHECK_MS = 20_000
55const TOLD_KEY = 'cockpit:notified'
56
57// The runaway step's band line (core/attention.ts runawayNow): posted again only when its minutes change or its time to live runs low
58const RUNAWAY_TTL_MS = 2 * 60_000
59const RUNAWAY_REPOST_MS = 60_000
60let runawayPosted: { text: string; at: number } | undefined
61let ownIds = 0
62async function postRunaway(i: Io, minutes: number, now: number): Promise<void> {
63  const text = runawayLine(minutes, runawayMem.turnId !== undefined)
64  if (runawayPosted !== undefined && runawayPosted.text === text && now - runawayPosted.at < RUNAWAY_REPOST_MS) return
65  runawayPosted = { text, at: now }
66  await postBand(i, 'info', RUNAWAY_BAND_ID, text, RUNAWAY_TTL_MS)
67}
68async function dropRunaway(i: Io): Promise<void> {
69  if (runawayPosted === undefined) return
70  runawayPosted = undefined
71  await clearBand(i, RUNAWAY_BAND_ID)
72  await redrawIfChanged(i)
73}
74
75let prev: Record<string, Seen> = {}
76
77async function viewNow(i: Io) {
78  const now = await i.now()
79  const records = await listRecords(i)
80  const alive = await alivePids(i, records)
81  return buildView(records, now, await i.sessionId(), alive, parseStoredUsage(await i.get(APP_USAGE_KEY)), undefined, parseStoredSessions(await i.get(APP_SESSIONS_KEY)))
82}
83
84async function check($: EngineInterface): Promise<void> {
85  const i = io($)
86  try {
87    const now = await i.now()
88    const id = await i.sessionId()
89    const step = (await readSetting(i, 'heartbeat.mode')) === 'on' ? runawayNow(now) : undefined
90    // A long shell step is the reason for the silence: its own calm line stands in for Gone idle and May be stuck
91    if (step !== undefined) {
92      await clearBand(i, 'heartbeat')
93      await postRunaway(i, step.minutes, now)
94    } else {
95      await dropRunaway(i)
96      if ((await readSetting(i, 'heartbeat.mode')) === 'on') {
97        const rec = await readRecord(i, id)
98        if (rec !== undefined) {
99          const silent = now - rec.lastEventAt
100          const beat = rec.ask !== undefined ? 'ok' : heartbeat(rec.state, silent)
101          if (beat === 'ok') await clearBand(i, 'heartbeat')
102          else await postBand(i, beat === 'stuck' ? 'urgent' : 'warn', 'heartbeat', beat === 'stuck' ? 'May be stuck' : 'Gone idle', 2 * 60_000)
103        }
104      }
105    }
106    const mode = await readSetting(i, 'notify.mode')
107    const view = await viewNow(i)
108    const rows = noticeRows(view)
109    const raw = await i.get(TOLD_KEY)
110    const told: Record<string, string> = typeof raw === 'object' && raw !== null ? (raw as Record<string, string>) : {}
111    const fired = await stepWatches(i, [...view.needs, ...view.working, ...view.waiting, ...view.idle].map(w => ({ id: w.rec.sessionId, name: w.name, kind: w.kind, ...(w.rec.done === undefined ? {} : { done: w.rec.done }) })), now)
112    for (const f of fired) {
113      i.toast(f.text, true)
114      await postBand(i, 'info', WATCH_BAND_ID, f.text, WATCH_BAND_MS)
115    }
116    const r = notices(prev, rows, told, mode, now)
117    r.notices = r.notices.filter(n => !fired.some(f => f.id === n.id) || !n.marker.startsWith('done:'))
118    const plan = noticePlan(prev, r, r.notices.length > 0 && isQuiet(await readSetting(i, 'notify.quiet'), new Date(now).getHours()))
119    prev = plan.next
120    if (plan.tell.length > 0) {
121      for (const n of plan.tell) told[n.id] = n.marker
122      await i.set(TOLD_KEY, told)
123      i.toast(batchText(plan.tell), plan.urgent)
124      const needs = plan.tell.filter(n => n.marker.startsWith('needs')).length
125      if (needs > 0) tellNow({ kind: 'needs', n: needs })
126    }
127  } catch {
128    // the router never breaks the session
129  }
130}
131
132// A working session that went silent reads idle on the board, but for the notices it is still at work, so its finish is told.
133export function noticeRows(view: Pick<View, 'needs' | 'waiting' | 'working' | 'idle'>): NoticeRow[] {
134  const silent = view.idle.filter(r => r.rec.state === 'working').map(r => ({ ...r, kind: 'working' as const }))
135  return [...view.needs, ...view.waiting, ...view.working, ...silent].map(r => ({ id: r.rec.sessionId, name: r.name, kind: r.kind, reason: r.reason, since: r.rec.ask !== undefined && r.kind === 'needs' ? r.rec.ask.since : r.rec.stateSince }))
136}
137
138// The recap's facts: the goal, and how many sessions need you, counted now.
139async function recapOf(i: Io, rec: SessionRecord, now: number, say?: (s: string) => string): Promise<string> {
140  const goal = readState(await readNote(i, stateKey(rec.sessionId))).goal?.text
141  const needs = (await viewNow(i)).needs.length
142  return recapWords({ gapMs: now - rec.lastEventAt, branch: rec.branch, cache: rec.cache === undefined ? undefined : cacheWords(rec.cache, now, cacheTtlMs(parseStoredUsage(await i.get(APP_USAGE_KEY))), false, say), ...(goal === undefined || goal === '' ? {} : { goal }), needs }, say)
143}
144
145export function registerAttention(on: On): void {
146  on('session.start', { cwd: /(?<attention>)/ }, async ($, e, next) => {
147    try {
148      // Always at full pace
149      const timer = $.clock.every(CHECK_MS, () => void check($).catch(() => undefined))
150      armOnce('attention', timer)
151    } catch {
152    }
153    return next(e)
154  }).catch(($, e, next) => next(e))
155
156  // The runaway step's clock (core/attention.ts): a main-loop shell step from its call to its end; a hash and times only, never the command
157  on('tool.call', { tool: /(?<runaway>)/ }, async ($, e, next) => {
158    // A call with no id of its own (a plugin's own call) gets one here, so its end still finds it
159    const id = e.agentId === undefined && isShellTool(e.tool) ? (typeof e.tool_use_id === 'string' ? e.tool_use_id : `own-${(ownIds += 1)}`) : undefined
160    if (id !== undefined) {
161      try {
162        const startedAt = await $.clock.now()
163        stepStart(id, stepHash(e.tool, { command: fieldsOf(e).command }), startedAt)
164      } catch {
165      }
166    }
167    try {
168      return await next(e)
169    } finally {
170      if (id !== undefined) {
171        stepEnd(id)
172        void dropRunaway(io($)).catch(() => undefined)
173      }
174    }
175  }).catch(($, e, next) => next(e))
176
177  // Claude Code tells the person it needs a permission: the step that waits for the OK is not timed. It only notes it, never answers.
178  on('classic.Notification', { notification_type: /permission/i }, async ($, e, next) => {
179    try {
180      // The notice says the tool ("... permission to use Bash"); only a shell step is timed
181      const tool = /\buse (.+?)\s*$/i.exec(e.message)?.[1] ?? ''
182      if (e.agent_id === undefined && isShellTool(tool)) {
183        const askedAt = await $.clock.now()
184        stepAsked(askedAt)
185      }
186    } catch {
187    }
188    return next(e)
189  }).catch(($, e, next) => next(e))
190
191  // The main loop's running answer, so Stop the answer can end it; a new or ended answer has no step left running
192  on('turn.start', { turnId: /(?<runaway>)/ }, async ($, e, next) => {
193    try {
194      if (fieldsOf(e).agentId === undefined) stepsReset(e.turnId)
195    } catch {
196    }
197    return next(e)
198  }).catch(($, e, next) => next(e))
199
200  on('turn.complete', { turnId: /(?<runaway>)/ }, async ($, e, next) => {
201    try {
202      if (e.agentId === undefined) {
203        stepsReset()
204        await dropRunaway(io($))
205      }
206    } catch {
207    }
208    return next(e)
209  }).catch(($, e, next) => next(e))
210
211  on('prompt.submit', { text: /(?<attention>)/ }, async ($, e, next) => {
212    try {
213      const i = io($)
214      if ((await readSetting(i, 'recap.mode')) === 'on' && !e.text.trimStart().startsWith('/')) {
215        const rec = await readRecord(i, await i.sessionId())
216        const now = await i.now()
217        if (rec !== undefined && rec.state !== 'working' && now - rec.lastEventAt >= RECAP_AFTER_MS) {
218          await postBand(i, 'info', 'recap', await recapOf(i, rec, now), 3 * 60_000)
219        }
220      }
221    } catch {
222    }
223    return next(e)
224  }).catch(($, e, next) => next(e))
225
226  on('command.run', { command: 'vaken-today' }, async ($, e, next) => {
227    const rest0 = subArgs(e.args, 'recap')
228    if (rest0 === undefined) return next(e)
229    const i = io($)
230    await sayIn(i)
231    const rec = await readRecord(i, await i.sessionId())
232    const now = await i.now()
233    if (rec === undefined) return { text: tr('Nothing to recap yet.') }
234    return { text: await recapOf(i, rec, now, tr) }
235  })
236
237  on('command.run', { command: 'vaken-today' }, async ($, e, next) => {
238    const rest0 = subArgs(e.args, 'glance')
239    if (rest0 === undefined) return next(e)
240    await sayIn(io($))
241    // The same load as the pane and /vaken (loadView): the limit that leads with its reset and age
242    const { view, now } = await loadView(io($))
243    const ledger = view.ledger ?? []
244    const lead = limitBlocks(view)[0]
245    return {
246      text: glanceLines({
247        needs: view.needs.map(r => ({ name: r.name, reason: r.reason })),
248        needsTotal: needsCount(view),
249        limitPercent: lead?.percent,
250        limitLabel: lead === undefined ? undefined : limitLabel(lead.label, tr),
251        limitReset: lead === undefined || lead.reset === '' ? undefined : resetSaid(lead.reset, tr),
252        limitAgo: lead === undefined ? undefined : limitAgo([lead], tr),
253        hereState: hereWord(view.here, 'explained', view.hereWaits, tr),
254        didCount: actedToday(ledger, now, view.counts),
255      }, tr).join('\n'),
256    }
257  })
258}
259
hooks/features/tellme.ts 166 lines
1// Tell me: one Mac notification while you are away from the app, and the status line under the prompt box.
2import type { EngineInterface, On } from 'claude-code'
3
4import { isQuiet } from '../core/attention'
5import { FOCUS_KEY, isFocused, parseFocus } from '../core/focus'
6import { withToastGate } from '../core/io'
7import { homeFrom } from '../core/platform'
8import type { Io } from '../core/io'
9import { readSetting } from '../core/settings'
10import { bindPlatform, platformOfIo } from '../core/procs'
11import { LONG_ANSWER_MS, PERSON_KEY, PERSON_SAVE_MS, TELL_RUN_MS, TELL_TITLE, isAwayAt, isMacHome, latestAt, mayTell, notifyArgv, statusMem, statusNext, statusText, tellBus, tellStep, tellText, waysOf, winSoundArgv } from '../core/tellme'
12import type { HowWay, TellGate, TellItem, TellKind } from '../core/tellme'
13
14// IO-BLOCK-START
15function io($: EngineInterface): Io {
16  return withToastGate({
17    now: () => $.clock.now(),
18    home: () => homeFrom({ HOME: () => $.env.get('HOME'), USERPROFILE: () => $.env.get('USERPROFILE'), HOMEDRIVE: () => $.env.get('HOMEDRIVE'), HOMEPATH: () => $.env.get('HOMEPATH') }),
19    sessionId: () => $.session.id(),
20    get: key => $.store.get(key),
21    set: (key, value) => $.store.set(key, value),
22    del: key => $.store.delete(key),
23    keys: () => $.store.keys(),
24    read: path => $.fs.read(path),
25    write: (path, text) => $.fs.write(path, text),
26    run: (argv, init) => $.process.run(argv, init),
27    ask: (question, options) => $.ui.ask(question, options),
28    complete: req => $.model.complete(req),
29    toast: text => $.ui.toast(text),
30    invalidate: () => $.ui.invalidate('ui.render'),
31  })
32}
33// IO-BLOCK-END
34
35// A limit warning repeats while it holds, so it is told once an hour at most.
36const AGAIN_MS: Partial<Record<TellKind, number>> = { limit: 60 * 60_000 }
37
38let gate: TellGate = { held: [] }
39let personAt: number | undefined
40let personSavedAt: number | undefined
41let waiting = false
42const toldAt = new Map<TellKind, number>()
43
44async function seen($: EngineInterface): Promise<void> {
45  const now = await $.clock.now()
46  personAt = now
47  // Shared with the other sessions, so a press in one counts for all; written at most once in PERSON_SAVE_MS.
48  if (personSavedAt === undefined || now - personSavedAt >= PERSON_SAVE_MS) {
49    personSavedAt = now
50    await $.store.set(PERSON_KEY, now)
51  }
52}
53
54async function deliver($: EngineInterface, items: TellItem[]): Promise<void> {
55  const i = bindPlatform(io($), () => $.env.get('OS'))
56  const text = tellText(items)
57  const how = await readSetting(i, 'notify.how')
58  const mac = isMacHome(await i.home())
59  const ways = waysOf(how, mac, (await platformOfIo(i)) === 'win32')
60  // The Windows sound plays beside the banner: one failing never stops the other.
61  const sound = ways.includes('winsound') ? playWinSound($) : undefined
62  await banner($, text, how, ways.filter(w => w !== 'winsound'))
63  await sound
64}
65
66async function playWinSound($: EngineInterface): Promise<void> {
67  try {
68    await $.process.run(winSoundArgv(), { timeoutMs: TELL_RUN_MS })
69  } catch {
70  }
71}
72
73async function banner($: EngineInterface, text: string, how: string, ways: readonly HowWay[]): Promise<void> {
74  for (const way of ways) {
75    try {
76      if (way === 'speak') {
77        await $.audio.speak(text)
78        return
79      }
80      if (way === 'notify') {
81        const r = await $.ui.notify(text, { title: TELL_TITLE })
82        if (r.isSent) return
83        continue
84      }
85      const r = await $.process.run(notifyArgv(text, how === 'sound'), { timeoutMs: TELL_RUN_MS })
86      if (r.exitCode === 0) return
87    } catch {
88    }
89  }
90}
91
92async function offer($: EngineInterface, item: TellItem | undefined): Promise<void> {
93  const now = await $.clock.now()
94  const step = tellStep(gate, item, now)
95  gate = step.gate
96  if (step.send !== undefined) await deliver($, step.send)
97  else if (step.waitMs !== undefined && !waiting) {
98    waiting = true
99    $.clock.after(step.waitMs, () => {
100      waiting = false
101      void offer($, undefined).catch(() => undefined)
102    })
103  }
104}
105
106async function push($: EngineInterface, item: TellItem): Promise<void> {
107  const now = await $.clock.now()
108  // The memory answers first, so a person at the keys costs no read.
109  if (!isAwayAt(personAt, now)) return
110  const again = AGAIN_MS[item.kind]
111  const last = toldAt.get(item.kind)
112  if (again !== undefined && last !== undefined && now - last < again) return
113  const i = io($)
114  const away = isAwayAt(latestAt(personAt, await i.get(PERSON_KEY)), now)
115  const facts = { mode: await readSetting(i, 'notify.mode'), quiet: isQuiet(await readSetting(i, 'notify.quiet'), new Date(now).getHours()), focused: isFocused(parseFocus(await i.get(FOCUS_KEY)), now), away }
116  if (!mayTell(item.kind, facts)) return
117  toldAt.set(item.kind, now)
118  await offer($, item)
119}
120
121function applyStatus($: EngineInterface): void {
122  const line = statusNext(statusMem.on, statusText(statusMem.facts), statusMem.shown)
123  if (line === null) return
124  statusMem.shown = line
125  $.ui.status(line)
126}
127
128export function registerTellMe(on: On): void {
129  on('session.start', { cwd: /(?<tellme>)/ }, async ($, e, next) => {
130    try {
131      const startAt = await $.clock.now()
132      personAt = startAt
133      tellBus.push = item => void push($, item).catch(() => undefined)
134    } catch {
135    }
136    return next(e)
137  }).catch(($, e, next) => next(e))
138
139  on('prompt.submit', { text: /(?<tellme>)/ }, async ($, e, next) => {
140    try {
141      await seen($)
142    } catch {
143    }
144    return next(e)
145  }).catch(($, e, next) => next(e))
146
147  on('ui.press', { element: /(?<tellme>)/ }, async ($, e, next) => {
148    try {
149      await seen($)
150    } catch {
151    }
152    return next(e)
153  }).catch(($, e, next) => next(e))
154
155  on('turn.complete', { turnId: /(?<tellme>)/ }, async ($, e, next) => {
156    try {
157      if (e.agentId === undefined) {
158        if (!e.isAborted && e.durationMs >= LONG_ANSWER_MS) tellBus.push?.({ kind: 'done' })
159        applyStatus($)
160      }
161    } catch {
162    }
163    return next(e)
164  }).catch(($, e, next) => next(e))
165}
166
hooks/features/cachekeeper.ts 196 lines
1// The cache keeper (opt-in, Settings > Money and plan): while a session is quiet
2import { tr } from '../core/lang'
3import type { EngineInterface, On } from 'claude-code'
4
5import { parseStoredUsage, APP_USAGE_KEY } from '../core/appusage'
6import { cacheFromUsage, cacheWords, warmLeftMs } from '../core/cachefacts'
7import { ttlOrGuess } from '../core/compactmoment'
8import { KEEPER_MAX_PINGS, KEEPER_PROMPT, KEEPER_STOP_WHAT, KEEPER_UNREAD_WHAT, KEPT_LOST_WHAT, KEPT_PAID_WHAT, KEPT_WHAT, TEST_LAST_MS, TEST_TTL_MS, cacheHeld, keeperVerdict, keptDetail, keptNet, keptNetDetail, nextPingInMs, pingHeld } from '../core/cachekeeper'
9import { priceOf } from '../core/prices'
10import { withToastGate } from '../core/io'
11import { MODEL_KEEPER_WHAT, askFork } from '../core/modelGate'
12import { homeFrom } from '../core/platform'
13import type { Io } from '../core/io'
14import { putRecord, readRecord } from '../core/record'
15import { readSetting } from '../core/settings'
16import { LEDGER_KEY, logLines, pushLog, readLog, why } from './compaction'
17import { cacheTtlMs } from './home/logic'
18import { armOnce } from './everyonce'
19import { subArgs } from '../core/menu'
20import { fillIn } from '../core/fillin'
21import { sayIn } from './saylang'
22
23// IO-BLOCK-START
24function io($: EngineInterface): Io {
25  return withToastGate({
26    now: () => $.clock.now(),
27    home: () => homeFrom({ HOME: () => $.env.get('HOME'), USERPROFILE: () => $.env.get('USERPROFILE'), HOMEDRIVE: () => $.env.get('HOMEDRIVE'), HOMEPATH: () => $.env.get('HOMEPATH') }),
28    sessionId: () => $.session.id(),
29    get: key => $.store.get(key),
30    set: (key, value) => $.store.set(key, value),
31    del: key => $.store.delete(key),
32    keys: () => $.store.keys(),
33    read: path => $.fs.read(path),
34    write: (path, text) => $.fs.write(path, text),
35    run: (argv, init) => $.process.run(argv, init),
36    ask: (question, options) => $.ui.ask(question, options),
37    complete: req => $.model.complete(req),
38    fork: req => $.model.fork(req),
39    toast: text => $.ui.toast(text),
40    invalidate: () => $.ui.invalidate('ui.render'),
41  })
42}
43// IO-BLOCK-END
44
45// The ping goes in the last minutes of the cache's life (leadMs), so this must be well under that.
46const CHECK_MS = 30_000
47// A test ping from the command waits a moment, because a call cannot run inside the command that waits for it.
48const TEST_DELAY_MS = 1_500
49
50let pings = 0
51let stretchOf = 0
52let busyPinging = false
53let testUntil = 0
54// The tokens each held read took since your last answer: the next answer shows whether they paid.
55let keptReads: number[] = []
56
57// How many tokens the window holds: the app's reading
58const windowTokens = (rec: { ctx?: { tokens?: number }; cache?: { read: number; write: number; fresh: number } }): number | undefined => rec.ctx?.tokens ?? (rec.cache === undefined ? undefined : rec.cache.read + rec.cache.write + rec.cache.fresh)
59
60type Pinged = { ok: true; held: boolean; read: number } | { ok: false; why: string }
61
62// Never throws.
63async function pingOnce($: EngineInterface, sessionId: string, n: number): Promise<Pinged> {
64  const i = io($)
65  try {
66    const r = await askFork(i, { what: MODEL_KEEPER_WHAT, log: false }, { prompt: KEEPER_PROMPT })
67    const now = await i.now()
68    if (!r.isAnswered) {
69      // The host cannot fork a chat that has no reply yet: say it in plain words.
70      const reason = r.reason === 'nothing-to-fork' ? 'This session has no reply yet. Send one message, wait for the answer, then try again.' : 'error' in r && r.error !== undefined ? `${r.reason}: ${String(r.error)}` : r.reason
71      await pushLog(i, LEDGER_KEY, { at: now, session: sessionId, what: KEEPER_UNREAD_WHAT, detail: reason, how: 'auto' })
72      return { ok: false, why: reason }
73    }
74    const held = pingHeld(r.usage)
75    const cache = cacheFromUsage(r.usage, now)
76    if (cache !== undefined) {
77      stretchOf = now
78      await putRecord(i, { sessionId, cache: { ...cache, at: now } }, false)
79    }
80    if (held) {
81      keptReads.push(r.usage.cache_read_input_tokens)
82      await pushLog(i, LEDGER_KEY, { at: now, session: sessionId, what: KEPT_WHAT, detail: keptDetail(r.usage.cache_read_input_tokens, n), how: 'auto', did: true })
83    } else {
84      // The lapsed read wrote the cache again, so the next answer's hit is not the earlier reads' doing: settle them now.
85      await settle(i, sessionId, priceOf((await readRecord(i, sessionId))?.model), { read: 0, write: 0, fresh: 0 }, false, now)
86      await pushLog(i, LEDGER_KEY, { at: now, session: sessionId, what: KEEPER_STOP_WHAT, detail: 'The cache had gone stale, so the read paid for a rewrite.', how: 'auto' })
87    }
88    return { ok: true, held, read: r.usage.cache_read_input_tokens }
89  } catch (err) {
90    return { ok: false, why: why(err) }
91  }
92}
93
94// Writes what the reads since your last answer came to, once. Never throws.
95async function settle(i: Io, sessionId: string, price: ReturnType<typeof priceOf>, nextFacts: { read: number; write: number; fresh: number }, held: boolean, now: number): Promise<void> {
96  const reads = keptReads
97  keptReads = []
98  const net = keptNet(price, reads, nextFacts, held)
99  if (net === undefined) return
100  try {
101    await pushLog(i, LEDGER_KEY, { at: now, session: sessionId, what: net.usd > 0 ? KEPT_PAID_WHAT : KEPT_LOST_WHAT, detail: keptNetDetail(net, reads.length), how: 'auto', usd: net.usd })
102  } catch {
103    // a lost line only shows less
104  }
105}
106
107// Never throws.
108async function check($: EngineInterface): Promise<void> {
109  if (busyPinging) return
110  const i = io($)
111  try {
112    if ((await readSetting(i, 'cache.keeper')) !== 'on') return
113    const id = await i.sessionId()
114    const rec = await readRecord(i, id)
115    if (rec?.cache === undefined) return
116    if (rec.cache.at !== stretchOf) {
117      // A new answer since the last read: it shows whether the reads paid.
118      if (keptReads.length > 0 && stretchOf !== 0) await settle(i, id, priceOf(rec.model), rec.cache, cacheHeld(rec.cache), await i.now())
119      pings = 0
120      stretchOf = rec.cache.at
121    }
122    const now = await i.now()
123    const testing = now < testUntil
124    const ttl = testing ? TEST_TTL_MS : ttlOrGuess(cacheTtlMs(parseStoredUsage(await i.get(APP_USAGE_KEY))))
125    if (nextPingInMs(rec.cache.at, ttl, now) > 0) return
126    const v = keeperVerdict({ mode: 'on', tokens: windowTokens(rec), minTokens: testing ? 0 : undefined, pings, busy: rec.state === 'working' || rec.ask !== undefined, warmLeftMs: warmLeftMs(rec.cache, now, ttl) })
127    if (!v.ping) return
128    busyPinging = true
129    pings += 1
130    const r = await pingOnce($, id, pings)
131    if (!r.ok || !r.held) pings = KEEPER_MAX_PINGS
132    i.invalidate()
133  } catch {
134    // the keeper never breaks the session
135  } finally {
136    busyPinging = false
137  }
138}
139
140export function registerCacheKeeper(on: On): void {
141  on('session.start', { cwd: /(?<cockpit>)/ }, async ($, e, next) => {
142    try {
143      const timer = $.clock.every(CHECK_MS, () => void check($))
144      armOnce('cachekeeper', timer)
145    } catch {
146      // the keeper is optional: a failure shows less, never breaks the session
147    }
148    return next(e)
149  }).catch(($, e, next) => next(e))
150
151  on('command.run', { command: 'vaken-help' }, async ($, e, next) => {
152    const rest0 = subArgs(e.args, 'run', 'keeper')
153    if (rest0 === undefined) return next(e)
154    const i = io($)
155    await sayIn(i)
156    const id = await i.sessionId()
157    if (rest0.trim().toLowerCase() === 'test') {
158      testUntil = (await i.now()) + TEST_LAST_MS
159      pings = 0
160      return { text: fillIn(tr('Short test for 10 minutes: the keeper treats the cache as stale after {secs} seconds and ignores the size limit. It needs Keep session cheap set to On, in Settings > Money and plan. Within about a minute it should read the cache, up to {max} times. Run /vaken-help run keeper to see.'), { secs: Math.round(TEST_TTL_MS / 1000), max: KEEPER_MAX_PINGS }) }
161    }
162    if (rest0.trim().toLowerCase() === 'now') {
163      $.clock.after(TEST_DELAY_MS, () => {
164        void (async () => {
165          const r = await pingOnce($, id, pings + 1)
166          i.toast(r.ok ? fillIn(tr(r.held ? 'Kept the cache warm: {k}k tokens read from it' : 'Kept the cache warm: {k}k tokens read from it (it had gone stale)'), { k: Math.round(r.read / 1000) }) : fillIn(tr('The cache read failed. {why}'), { why: tr(r.why) }))
167          i.invalidate()
168        })()
169      })
170      return { text: tr("Reading this session's cache once, in a moment. Run /vaken-help run keeper to see the result.") }
171    }
172    const isOn = (await readSetting(i, 'cache.keeper')) === 'on'
173    const rec = await readRecord(i, id)
174    const now = await i.now()
175    const testing = now < testUntil
176    const ttl = testing ? TEST_TTL_MS : ttlOrGuess(cacheTtlMs(parseStoredUsage(await i.get(APP_USAGE_KEY))))
177    const v = keeperVerdict({ mode: isOn ? 'on' : 'off', tokens: rec === undefined ? undefined : windowTokens(rec), minTokens: testing ? 0 : undefined, pings, busy: rec?.state === 'working', warmLeftMs: rec?.cache === undefined ? 0 : warmLeftMs(rec.cache, now, ttl) })
178    const nextMin = rec?.cache === undefined ? undefined : Math.round(nextPingInMs(rec.cache.at, ttl, now) / 60_000)
179    const last = logLines((await readLog(i, LEDGER_KEY)).filter(x => x.what.startsWith('Kept') || x.what.startsWith('Keeper')), 3) // en-only: matches the title of a stored ledger line
180    return {
181      text: [
182        isOn ? tr('Keeper: on.') : tr('Keeper: off.'),
183        tr('Claude keeps a saved copy of this session (the cache), so each answer costs less. It goes stale after about an hour of quiet (5 minutes when you pay with usage credits). The keeper reads it just before, so a break does not make your next answer cost more.'),
184        ...(isOn ? [] : [tr('Turn it on: Settings > Money and plan.')]),
185        '',
186        ...(rec?.cache === undefined ? [tr('No turn yet, so no cache to keep.')] : [`${cacheWords(rec.cache, now, ttl, false, tr)}${testing ? ` ${tr('(short test)')}` : ''}`]),
187        fillIn(tr('Reads since your last answer: {n} of {max}.'), { n: pings, max: KEEPER_MAX_PINGS }),
188        v.ping ? (nextMin === undefined || nextMin <= 0 ? tr('Next read: due now.') : fillIn(tr('Next read: in about {n} min.'), { n: nextMin })) : fillIn(tr('No read now: {why}'), { why: v.why }),
189        ...(last.length === 0 ? [] : ['', tr('Last:'), ...last]),
190        '',
191        tr('Try: /vaken-help run keeper now (one read now) or /vaken-help run keeper test (a one-minute test).'),
192      ].join('\n'),
193    }
194  })
195}
196
hooks/features/calm.ts 309 lines
1// Calm: Focus 50 minutes and the open ends of yesterday.
2import type { EngineInterface, On } from 'claude-code'
3
4import { DIGEST_KEY, parseDigest } from '../core/away'
5import { postBand, clearBand } from '../core/band'
6import { CALM_KEY, parseCalm } from '../core/calm'
7import type { Calm } from '../core/calm'
8import { forgetNote, holdNote, readNote } from '../core/flush'
9import { FOCUS_KEY, FOCUS_MS, FOCUS_POLL_MS, focusEmpty, focusMem, focusSummary, isFocused, minutesLeft, parseFocus } from '../core/focus'
10import type { Focus } from '../core/focus'
11import { allowKey } from '../core/guard'
12import { heldKey, parseAllowOnce, parseHeld } from '../core/allowonce'
13import { withToastGate } from '../core/io'
14import { homeFrom } from '../core/platform'
15import type { Io } from '../core/io'
16import { didKind } from '../core/ledger'
17import { OPEN_ENDS_BAND_MS, OPEN_ENDS_PREFIX, OPEN_ENDS_SHOW, noteMatters, openBand, openDayOf, openDayStart, openEnds, openEndsKey, openShown, parseOpenNote } from '../core/openends'
18import type { OpenEnd, OpenNote } from '../core/openends'
19import { ORCH_KEY, parseRun } from '../core/orchestra'
20import { projectName } from '../core/projects'
21import { relevantKinds, readState, stateKey, statusOf } from '../core/proof'
22import { quietly } from '../core/quiet'
23import { alivePids, listRecords } from '../core/record'
24import { serialUpdate } from '../core/serial'
25import { weeklyShown } from '../core/weekly'
26import type { WeeklyNote } from '../core/weekly'
27import { LEDGER_KEY, readLog } from './compaction'
28import { classify } from './home/logic'
29import { armOnce } from './everyonce'
30import { subArgs } from '../core/menu'
31import { fillIn } from '../core/fillin'
32import { tr } from '../core/lang'
33import { sayIn } from './saylang'
34
35// IO-BLOCK-START
36function io($: EngineInterface): Io {
37  return withToastGate({
38    now: () => $.clock.now(),
39    home: () => homeFrom({ HOME: () => $.env.get('HOME'), USERPROFILE: () => $.env.get('USERPROFILE'), HOMEDRIVE: () => $.env.get('HOMEDRIVE'), HOMEPATH: () => $.env.get('HOMEPATH') }),
40    sessionId: () => $.session.id(),
41    get: key => $.store.get(key),
42    set: (key, value) => $.store.set(key, value),
43    del: key => $.store.delete(key),
44    keys: () => $.store.keys(),
45    read: path => $.fs.read(path),
46    write: (path, text) => $.fs.write(path, text),
47    run: (argv, init) => $.process.run(argv, init),
48    ask: (question, options) => $.ui.ask(question, options),
49    complete: req => $.model.complete(req),
50    toast: text => $.ui.toast(text),
51    invalidate: () => $.ui.invalidate('ui.render'),
52  })
53}
54// IO-BLOCK-END
55
56// `kept`: the session whose open-ends note this copy wrote while it ran.
57// `resumed`: this session has had its first answer, so an older mid-answer end in its project was cleared once
58const calmMem: { checkedDay?: string; root?: string; inTurn: boolean; kept?: string; resumed?: boolean } = { inTurn: false }
59
60export async function readFocus(i: Io): Promise<Focus | undefined> {
61  const f = parseFocus(await i.get(FOCUS_KEY))
62  focusMem.focus = f
63  return f
64}
65
66export async function startFocus(i: Io): Promise<Focus> {
67  const now = await i.now()
68  const f: Focus = { from: now, until: now + FOCUS_MS }
69  await i.set(FOCUS_KEY, f)
70  focusMem.focus = f
71  i.invalidate()
72  return f
73}
74
75async function summaryOf(i: Io, f: Focus, now: number): Promise<{ finished: number; warnings: number }> {
76  const records = await listRecords(i)
77  const alive = await alivePids(i, records)
78  const finished = records.filter(r => r.stateSince >= f.from && classify(r, now, alive) === 'waiting').length
79  const warnings = (await readLog(i, LEDGER_KEY)).filter(x => x.did === true && x.at >= f.from && x.at <= now && didKind(x.what) !== 'did').length
80  return { finished, warnings }
81}
82
83export async function endFocus(i: Io, isPress = false): Promise<string | undefined> {
84  const f = parseFocus(await i.get(FOCUS_KEY))
85  focusMem.focus = undefined
86  if (f === undefined) return undefined
87  await i.del(FOCUS_KEY)
88  const now = await i.now()
89  const facts = await summaryOf(i, f, Math.min(now, Math.max(f.from, f.until)))
90  const text = focusSummary(facts)
91  if (isPress || (now >= f.until && !focusEmpty(facts))) i.toast(text, true)
92  i.invalidate()
93  return text
94}
95
96export async function focusPoll(i: Io): Promise<void> {
97  try {
98    const before = focusMem.focus
99    const f = await readFocus(i)
100    if (f !== undefined && (await i.now()) >= f.until) await endFocus(i)
101    else if ((before === undefined) !== (f === undefined)) i.invalidate()
102  } catch {
103  }
104}
105
106export async function focusCommand(i: Io, args: string): Promise<string> {
107  const ask = args.trim().toLowerCase()
108  if (ask === 'off' || ask === 'end' || ask === 'stop') return (await endFocus(i)) ?? tr('Quiet is not on.')
109  const now = await i.now()
110  const f = await readFocus(i)
111  if (isFocused(f, now)) return fillIn(tr('Quiet: {n} min left. Only what needs you gets through. /vaken-help run focus off ends it.'), { n: minutesLeft(f, now) })
112  await startFocus(i)
113  return tr('Quiet is on for 50 minutes in every session: toasts and the band\'s other lines wait, only what needs you gets through. /vaken-help run focus off ends it.')
114}
115
116// `atEnd` false: the note is kept while the session runs too (saved within OWN_SAVE_EVERY_MS), so a crash still leaves it; one that no longer matters is removed.
117export async function noteOpenEnds(i: Io, sid: string, root: string | undefined, midTurn: boolean, atEnd = true): Promise<OpenNote | undefined> {
118  if (root === undefined || root === '') return undefined
119  const proof = readState(await readNote(i, stateKey(sid)))
120  const checks: OpenNote['checks'] = {}
121  for (const k of relevantKinds(proof)) {
122    const st = statusOf(proof, k)
123    if (st === 'ok' || st === 'failed') checks[k] = st
124  }
125  const held = parseHeld(await i.get(heldKey(sid)))
126  const allow = parseAllowOnce(await i.get(allowKey(sid)))
127  const run = parseRun(await i.get(ORCH_KEY(sid)))
128  const note: OpenNote = {
129    at: await i.now(),
130    project: projectName(root),
131    checks,
132    held: held !== undefined && held.keys.length > 0 && !(allow !== undefined && allow.at >= held.at) ? 1 : 0,
133    tasks: run === undefined ? 0 : run.tasks.filter(t => t.state !== 'done').length,
134    midTurn,
135  }
136  const key = openEndsKey(sid)
137  if (!noteMatters(note)) {
138    if (calmMem.kept === sid) {
139      calmMem.kept = undefined
140      forgetNote(key)
141      await i.del(key)
142    }
143    return undefined
144  }
145  if (atEnd) {
146    forgetNote(key)
147    await i.set(key, note)
148  } else {
149    calmMem.kept = sid
150    await holdNote(i, key, note, 'own')
151  }
152  return note
153}
154
155// The end of an answer reads nothing from the store: the note kept at the turn's start only loses its mid-answer mark.
156export async function answeredOpenEnds(i: Io, sid: string): Promise<void> {
157  if (calmMem.kept !== sid) return
158  const key = openEndsKey(sid)
159  const kept = parseOpenNote(await readNote(i, key))
160  if (kept === undefined || !kept.midTurn) return
161  const note = { ...kept, at: await i.now(), midTurn: false }
162  if (noteMatters(note)) await holdNote(i, key, note, 'own')
163  else {
164    calmMem.kept = undefined
165    forgetNote(key)
166    await i.del(key)
167  }
168}
169
170// A new session in a project that has its first answer picks up where the last one stopped: an older "ended mid-answer" there no longer counts (in the notes and in today's open ends)
171export async function resumedOpenEnds(i: Io, sid: string, root: string | undefined): Promise<void> {
172  if (root === undefined || root === '') return
173  const project = projectName(root)
174  for (const k of (await i.keys()).filter(x => x.startsWith(OPEN_ENDS_PREFIX) && x !== openEndsKey(sid))) {
175    const n = parseOpenNote(await i.get(k))
176    if (n === undefined || n.project !== project || !n.midTurn) continue
177    const note = { ...n, midTurn: false }
178    forgetNote(k)
179    if (noteMatters(note)) await i.set(k, note)
180    else await i.del(k)
181  }
182  await serialUpdate(i, CALM_KEY, old => {
183    const c = parseCalm(old)
184    if (c.open === undefined) return c
185    const ends = c.open.ends.map(e => (e.project === project ? { ...e, midTurn: 0 } : e)).filter(e => e.failed.length > 0 || e.held > 0 || e.tasks > 0 || e.midTurn > 0)
186    return { ...c, open: { ...c.open, ends } }
187  })
188}
189
190// Never throws.
191export async function morningCheck(i: Io): Promise<void> {
192  try {
193    const now = await i.now()
194    const day = openDayOf(now)
195    if (calmMem.checkedDay === day) return
196    calmMem.checkedDay = day
197    if (parseCalm(await i.get(CALM_KEY)).open?.day === day) return
198    const notes: OpenNote[] = []
199    for (const k of (await i.keys()).filter(x => x.startsWith(OPEN_ENDS_PREFIX))) {
200      const n = parseOpenNote(await i.get(k))
201      if (n !== undefined) notes.push(n)
202    }
203    const ends = openEnds(notes, openDayStart(now))
204    await serialUpdate(i, CALM_KEY, old => ({ ...parseCalm(old), open: { day, ends, dismissed: false } }))
205    for (const [n, end] of ends.slice(0, OPEN_ENDS_SHOW).entries()) await postBand(i, 'info', `openends:${n}`, openBand(end), OPEN_ENDS_BAND_MS)
206  } catch {
207  }
208}
209
210export async function dismissOpenEnds(i: Io): Promise<void> {
211  await serialUpdate(i, CALM_KEY, old => {
212    const c = parseCalm(old)
213    return c.open === undefined ? c : { ...c, open: { ...c.open, dismissed: true } }
214  })
215  // The notes go too, so the same note never comes back on a later day; today's notes are tomorrow's open ends and stay
216  const dayStart = openDayStart(await i.now())
217  for (const k of (await i.keys()).filter(x => x.startsWith(OPEN_ENDS_PREFIX))) {
218    const n = parseOpenNote(await i.get(k))
219    if (n === undefined || n.at < dayStart) {
220      forgetNote(k)
221      await i.del(k)
222    }
223  }
224  for (let n = 0; n < OPEN_ENDS_SHOW; n += 1) await clearBand(i, `openends:${n}`)
225  i.invalidate()
226}
227
228// `rest`: the projects past the first few, behind the card's "Show N more" fold
229export type CalmView = { weekly?: WeeklyNote; open: OpenEnd[]; more: number; rest?: OpenEnd[]; focus?: Focus; away?: { to: number; text: string } }
230export async function loadCalm(i: Io, now: number): Promise<CalmView> {
231  await morningCheck(i)
232  const c: Calm = parseCalm(await i.get(CALM_KEY))
233  const weekly = weeklyShown(c.weekly, now)
234  const open = openShown(c.open, now)
235  const focus = focusMem.focus
236  const digest = parseDigest(await i.get(DIGEST_KEY))
237  return { ...(weekly === undefined ? {} : { weekly }), open: open.slice(0, OPEN_ENDS_SHOW), more: Math.max(0, open.length - OPEN_ENDS_SHOW), ...(open.length > OPEN_ENDS_SHOW ? { rest: open.slice(OPEN_ENDS_SHOW) } : {}), ...(isFocused(focus, now) ? { focus } : {}), ...(digest === undefined ? {} : { away: { to: digest.to, text: digest.text } }) }
238}
239export const calmSignature = (c: CalmView | undefined, now: number): string =>
240  c === undefined ? '' : `${c.weekly?.at ?? 0}|${[...c.open, ...(c.rest ?? [])].map(x => `${x.project}${x.failed.join('/')}${x.held}${x.tasks}${x.midTurn}`).join(',')}${c.more}|${c.focus === undefined ? '' : minutesLeft(c.focus, now)}|${c.away?.to ?? 0}`
241
242export function registerCalm(on: On): void {
243  on('session.start', { cwd: /(?<calm>)/ }, async ($, e, next) => {
244    try {
245      calmMem.checkedDay = undefined
246      calmMem.inTurn = false
247      calmMem.resumed = false
248      try {
249        const root = await $.session.root()
250        calmMem.root = root || e.cwd
251      } catch {
252        calmMem.root = e.cwd
253      }
254      await readFocus(io($))
255      const timer = $.clock.every(FOCUS_POLL_MS, quietly('calm:focus', () => $.clock.now(), () => focusPoll(io($))))
256      armOnce('calm', timer)
257    } catch {
258      // Focus and the open ends are optional: a failure shows less, never breaks the session
259    }
260    return next(e)
261  }).catch(($, e, next) => next(e))
262
263  on('prompt.submit', { text: /(?<calm>)/ }, async ($, e, next) => {
264    await morningCheck(io($))
265    return next(e)
266  }).catch(($, e, next) => next(e))
267
268  on('turn.start', { turnId: /(?<calm>)/ }, async ($, e, next) => {
269    calmMem.inTurn = true
270    try {
271      const sid = await $.session.id()
272      await noteOpenEnds(io($), sid, calmMem.root, true, false)
273    } catch {
274    }
275    return next(e)
276  }).catch(($, e, next) => next(e))
277  on('turn.complete', { turnId: /(?<calm>)/ }, async ($, e, next) => {
278    if (e.agentId === undefined) {
279      calmMem.inTurn = false
280      try {
281        const sid = await $.session.id()
282        await answeredOpenEnds(io($), sid)
283        if (calmMem.resumed !== true) {
284          calmMem.resumed = true
285          await resumedOpenEnds(io($), sid, calmMem.root)
286        }
287      } catch {
288      }
289    }
290    return next(e)
291  }).catch(($, e, next) => next(e))
292
293  on('session.end', { sessionId: /(?<calm>)/ }, async ($, e, next) => {
294    try {
295      await noteOpenEnds(io($), e.sessionId, calmMem.root, calmMem.inTurn)
296    } catch {
297    }
298    return next(e)
299  }).catch(($, e, next) => next(e))
300
301  on('command.run', { command: 'vaken-help' }, async ($, e, next) => {
302    const rest0 = subArgs(e.args, 'run', 'focus')
303    if (rest0 === undefined) return next(e)
304    const i = io($)
305    await sayIn(i)
306    return { text: await focusCommand(i, rest0) }
307  })
308}
309
hooks/features/compaction.ts 701 lines
1// Compaction: what the host lets a mod do (a probe), the keep-list added to every compaction, the record of each compaction
2import type { EngineInterface, On } from 'claude-code'
3import { fieldsOf } from '../core/eventfields'
4
5import { parseStoredUsage, APP_USAGE_KEY } from '../core/appusage'
6import { lastAfterTokens, lastSummaryOut, withCompact } from '../core/cachefacts'
7import { postBand } from '../core/band'
8import { AUDIT_KEY, parseAudit, toAudit, withAudit } from '../core/insight'
9import { compare, diffKey, filesFromMessages } from '../core/compactdiff'
10import type { Diff } from '../core/compactdiff'
11import { checkSummary, failingKinds, keepListItems, keepMem, learnedLines } from '../core/compactcheck'
12import type { KeepItem } from '../core/compactcheck'
13import { readState, stateKey } from '../core/proof'
14import { loadIndex } from '../core/undo'
15import { COUNTS_KEY, FREED_TITLE, SHORTENED_TITLE, addCount, countOf } from '../core/counts'
16import { serialUpdate } from '../core/serial'
17import { DEFAULT_AFTER_TOKENS, DEFAULT_SUMMARY_OUT, HELPERS_LINE, cardText, compactInstructions, keepWords, openLines, paybackTurns, ttlOrGuess, withKeepList } from '../core/compactmoment'
18import { BREAK_RETRY_MS, SIZE_LOOK2_MS, SIZE_LOOK_MS, breakAtMs, giveUpLeftMin, leadMsOf, minTokensOf } from '../core/compactauto'
19import type { Trigger } from '../core/compactauto'
20import { fromOf, nudge } from '../core/compactnudge'
21import { AUTO_NOTE_WHAT, noteText, noteWords } from '../core/autosafe'
22import { NEW_TURN, NO_BRIEF, STOP_WORDS, TYPING, detailWords, skippedWords, triggerWords } from '../core/compactwords'
23import { t, tr } from '../core/lang'
24import type { Probe } from '../core/undo'
25import { allowKey } from '../core/guard'
26import { heldKey, heldOpen, parseAllowOnce, parseHeld } from '../core/allowonce'
27import { failedKey, failedLine, parseFailed } from '../core/errors'
28import { BACKGROUND_MAX_MS, REST_KEY, endsBackground, helpersOpen, WOULD_WHAT, notGoodLines, restChecks, restDetail, restReady, restTrigger } from '../core/compactrest'
29import type { RestFacts } from '../core/compactrest'
30import { BOARD_KEY, boardRows, parseBoard } from '../core/agentboard'
31import { LEAN_TOKENS_TITLE, LEAN_WHAT, shownTitle, startOfDay } from '../core/ledger'
32import type { Entry } from '../core/ledger'
33import { withToastGate } from '../core/io'
34import { homeFrom } from '../core/platform'
35import type { Io } from '../core/io'
36import { putRecord, readRecord } from '../core/record'
37import { readSetting } from '../core/settings'
38import { tellsCompact } from '../core/tellclaude'
39import { cacheTtlMs } from './home/logic'
40import { hhmmss } from '../core/time'
41
42// IO-BLOCK-START
43function io($: EngineInterface): Io {
44  return withToastGate({
45    now: () => $.clock.now(),
46    home: () => homeFrom({ HOME: () => $.env.get('HOME'), USERPROFILE: () => $.env.get('USERPROFILE'), HOMEDRIVE: () => $.env.get('HOMEDRIVE'), HOMEPATH: () => $.env.get('HOMEPATH') }),
47    sessionId: () => $.session.id(),
48    get: key => $.store.get(key),
49    set: (key, value) => $.store.set(key, value),
50    del: key => $.store.delete(key),
51    keys: () => $.store.keys(),
52    read: path => $.fs.read(path),
53    write: (path, text) => $.fs.write(path, text),
54    run: (argv, init) => $.process.run(argv, init),
55    ask: (question, options) => $.ui.ask(question, options),
56    complete: req => $.model.complete(req),
57    toast: text => $.ui.toast(text),
58    invalidate: () => $.ui.invalidate('ui.render'),
59  })
60}
61// IO-BLOCK-END
62
63export const NUDGE_KEY = (sessionId: string): string => `cockpit:compact:nudge:${sessionId}`
64export const LEDGER_KEY = 'cockpit:ledger:compact'
65const LOG_CAP = 24
66// The ledger keeps more: the cache keeper adds an entry per ping, and the compacts must not be pushed out.
67const LEDGER_CAP = 60
68
69export type { Entry }
70
71const DONE_BAND_MS = 10 * 60_000
72
73// The ledger, the counts and the audit are shared by every session: each write goes through serialUpdate
74const isEntry = (entry: Entry) => (x: unknown): boolean => {
75  const got = x as Entry
76  return typeof got === 'object' && got !== null && got.at === entry.at && got.what === entry.what && got.session === entry.session
77}
78
79// `quiet`: the row only joins the log, with no band line and no audit row (the person pressed it or already sees it).
80export async function pushLog(i: Io, key: string, entry: Entry, quiet = false): Promise<void> {
81  const cap = key === LEDGER_KEY ? LEDGER_CAP : LOG_CAP
82  await serialUpdate(i, key, old => [entry, ...(Array.isArray(old) ? (old as Entry[]) : [])].slice(0, cap), stored => Array.isArray(stored) && stored.some(isEntry(entry)))
83  if (key === LEDGER_KEY) {
84    let written = 0
85    await serialUpdate(
86      i,
87      COUNTS_KEY,
88      old => {
89        let bumped = addCount(old, entry.at, entry.what)
90        written = countOf(bumped, entry.at, entry.what)
91        // A compaction that really made the window smaller also adds to today's two sums (core/counts.ts)
92        if (entry.before !== undefined && entry.after !== undefined && entry.before > entry.after) bumped = addCount(addCount(bumped, entry.at, SHORTENED_TITLE), entry.at, FREED_TITLE, entry.before - entry.after)
93        return bumped
94      },
95      stored => countOf(stored, entry.at, entry.what) >= written,
96    )
97  }
98  if (key === LEDGER_KEY && entry.did === true && !quiet) {
99    await postBand(i, 'info', `did:${entry.what}`, shownTitle(entry.what), DONE_BAND_MS, entry.session)
100    const row = toAudit(entry)
101    await serialUpdate(i, AUDIT_KEY, old => withAudit(parseAudit(old), row), stored => parseAudit(stored).some(r => r.at === row.at && r.what === row.what && r.session === row.session))
102  }
103}
104
105// The day's lean cuts as ONE row: the first cut of the day adds it, later ones add to its counts. Memory sums come in batches (features/lean.ts), never per cut.
106export async function noteLeanDay(i: Io, now: number, cuts: number, tokens: number): Promise<void> {
107  const session = await i.sessionId()
108  await serialUpdate(
109    i,
110    LEDGER_KEY,
111    old => {
112      const list = Array.isArray(old) ? (old as Entry[]) : []
113      const at = list.findIndex(e => typeof e === 'object' && e !== null && e.what === LEAN_WHAT && e.at >= startOfDay(now))
114      if (at < 0) return [{ at: now, session, what: LEAN_WHAT, how: 'auto' as const, did: true, cuts, saved: tokens }, ...list].slice(0, LEDGER_CAP)
115      const row = list[at] as Entry
116      return list.map((e, n) => (n === at ? { ...row, cuts: (row.cuts ?? 0) + cuts, saved: (row.saved ?? 0) + tokens } : e))
117    },
118    stored => Array.isArray(stored) && stored.some(e => (e as Entry | null)?.what === LEAN_WHAT),
119  )
120  await serialUpdate(i, COUNTS_KEY, old => addCount(addCount(old, now, LEAN_WHAT, cuts), now, LEAN_TOKENS_TITLE, tokens))
121}
122
123// A line from an old version or a broken write is dropped: each needs its time and its title.
124const goodEntry = (x: unknown): x is Entry => typeof x === 'object' && x !== null && typeof (x as Entry).at === 'number' && Number.isFinite((x as Entry).at) && typeof (x as Entry).what === 'string'
125export async function readLog(i: Io, key: string): Promise<Entry[]> {
126  const v = await i.get(key)
127  return Array.isArray(v) ? v.filter(goodEntry).map(x => (x.detail === undefined || typeof x.detail === 'string' ? x : { ...x, detail: String(x.detail) })) : []
128}
129
130export const why = (err: unknown): string => (err instanceof Error ? err.message : String(err)).slice(0, 160)
131
132export function logLines(list: Entry[], max = 12): string[] {
133  return list.slice(0, max).map(x => `${hhmmss(x.at)} ${shownTitle(x.what)}${x.detail === undefined ? '' : `: ${x.detail}`}`)
134}
135
136// The files this session edited, newest first: the transcript's edit steps when the hook has them (paths only), then the undo copies vaken keeps
137async function editedPaths(i: Io, sessionId: string, more: readonly string[]): Promise<string[]> {
138  const fromSteps = [...more].reverse()
139  try {
140    return [...fromSteps, ...(await loadIndex(i, sessionId)).snaps.slice().sort((a, b) => b.at - a.at).map(s => s.path)]
141  } catch {
142    return fromSteps
143  }
144}
145
146// The keep-list and the items it asks the summary to keep (core/compactcheck.ts). Never throws.
147export async function keepPlan(i: Io, sessionId: string, edited: readonly string[] = []): Promise<{ text: string; items: KeepItem[] }> {
148  const rec = await readRecord(i, sessionId)
149  const base = cardText({ title: rec?.title, branch: rec?.branch })
150  try {
151    const now = await i.now()
152    const held = heldOpen(parseHeld(await i.get(heldKey(sessionId))), parseAllowOnce(await i.get(allowKey(sessionId))), now)
153    const failed = parseFailed(await i.get(failedKey(sessionId)))
154    const open = openLines({ failed: failedLine(failed === undefined ? undefined : { ...failed, what: keepWords(failed.what) }, now), held: held === undefined ? undefined : (held.words ?? 'a step') })
155    const proof = readState(await i.get(stateKey(sessionId)))
156    const goal = proof.goal?.text ?? rec?.title
157    const items = keepListItems({ ...(goal === undefined ? {} : { goal }), edited: await editedPaths(i, sessionId, edited), failing: failingKinds(proof) })
158    return { text: [base, ...learnedLines(items, goal === rec?.title), ...open].join('\n'), items }
159  } catch {
160    return { text: base, items: [] }
161  }
162}
163
164// Never throws.
165export async function keepList(i: Io, sessionId: string): Promise<string> {
166  return (await keepPlan(i, sessionId)).text
167}
168
169// After a compaction: which changed files the summary names (core/compactdiff.ts) and, with the keep-list on, is each kept item in it?
170// The summary is read here and dropped: the record keeps names of our own and counts, the items left out stay in this process's memory.
171export async function checkKept(i: Io, sessionId: string, files: readonly string[], items: readonly KeepItem[] | undefined, summary: string | undefined): Promise<void> {
172  try {
173    if (summary === undefined) return
174    const now = await i.now()
175    const diff: Diff = compare([...files], summary, (await readRecord(i, sessionId))?.branch, now)
176    const c = items === undefined || items.length === 0 ? undefined : checkSummary(sessionId, items, summary, now)
177    keepMem.last = c
178    await i.set(diffKey(sessionId), c === undefined ? diff : { ...diff, keep: { total: c.total, lost: c.missing.length } })
179    if (c !== undefined && c.missing.length > 0) i.invalidate()
180  } catch {
181  }
182}
183
184// Where Auto gave up, per session: it could not start a compaction there, so it leaves that session alone for GIVE_UP_RETRY_MS (the This session card says so)
185const givenUp = new Map<string, number>()
186export const noteGiveUp = (sessionId: string, at: number): void => void givenUp.set(sessionId, at)
187export const giveUpMinOf = (sessionId: string, now: number): number => {
188  const left = giveUpLeftMin(givenUp.get(sessionId), now)
189  if (left === 0) givenUp.delete(sessionId)
190  return left
191}
192
193// The running flag is the one hard block with no way past it: it is claimed with a holder number before anything is awaited
194type How = NonNullable<Entry['how']>
195export const compacting: { pending: boolean; how?: How; owner?: number; seenBy?: number; sent?: { how: How; at: number } } = { pending: false }
196// How long a sent compaction still names its way in the record: a big session can take 16 s to compact
197const SENT_MARK_MS = 5 * 60_000
198let owners = 0
199
200export function claimCompacting(how: How): number | undefined {
201  if (compacting.pending) return undefined
202  owners += 1
203  compacting.pending = true
204  compacting.how = how
205  compacting.owner = owners
206  return owners
207}
208
209export function releaseCompacting(owner: number): void {
210  if (compacting.owner !== owner) return
211  compacting.pending = false
212  compacting.how = undefined
213  compacting.owner = undefined
214}
215
216// The way the compaction now passing the hook was started: the running one's, a just-sent one's (used once)
217function howNow(now: number): How {
218  if (compacting.pending) {
219    compacting.seenBy = compacting.owner
220    return compacting.how ?? 'button'
221  }
222  const s = compacting.sent
223  compacting.sent = undefined
224  return s !== undefined && now >= s.at && now - s.at < SENT_MARK_MS ? s.how : 'typed'
225}
226
227// What one session's rest keeps: the turn that just ended and the background commands it started. One slot per session, so two sessions never share a turn or a command.
228// `starts` counts the main turns that started: a compaction about to be sent checks it did not change. `background` holds the start time of each background command not yet seen to end; `timers` the looks scheduled for the turn that just ended.
229type RestSlot = { turnId?: string; endedAt: number; background: number[]; startedAt?: number; timers: { cancel: () => void }[]; starts: number }
230const slots = new Map<string, RestSlot>()
231export function cancelLooks(slot: RestSlot): void {
232  for (const timer of slot.timers) timer.cancel()
233  slot.timers = []
234}
235// A background command of the session ended (its task notification, or the person stopped it): the oldest one still counted is done.
236export function backgroundEnded(sessionId: string): void {
237  restSlotOf(sessionId).background.shift()
238}
239export function restSlotOf(sessionId: string): RestSlot {
240  const got = slots.get(sessionId)
241  if (got !== undefined) return got
242  const fresh: RestSlot = { endedAt: 0, background: [], timers: [], starts: 0 }
243  slots.set(sessionId, fresh)
244  return fresh
245}
246
247// Why Auto compacted this time: read once by the record of the compaction that follows
248let autoWhy: { kind: Trigger; pct: number | undefined; at: number } | undefined
249
250// What a compaction needs from the engine
251export type CompactOps = {
252  io: Io
253  cwd: () => Promise<string>
254  probe: Probe
255  agents: () => Promise<number> // helper agents the engine lists as running
256  command: (args: string) => Promise<unknown>
257  direct?: (instructions: string) => Promise<{ skip?: string; tokensBefore?: number; tokensAfter?: number; outTokens?: number; summary?: string }>
258}
259
260// What the rule needs, from the session's record, the agent board, the engine's agent list
261async function restFacts(i: Io, agents: () => Promise<number>, sessionId: string, turnId?: string): Promise<RestFacts | undefined> {
262  const rec = await readRecord(i, sessionId)
263  if (rec === undefined) return undefined
264  const slot = restSlotOf(sessionId)
265  const now = await i.now()
266  // Unknown plan: the short cache time for the payback sum, so a lapsed cache is never called warm; the break trigger never fires then (ttlKnown).
267  const knownTtl = cacheTtlMs(parseStoredUsage(await i.get(APP_USAGE_KEY)))
268  const ttl = ttlOrGuess(knownTtl)
269  const mine = boardRows(parseBoard(await i.get(BOARD_KEY)), now).filter(r => r.session === sessionId.slice(0, 8) && r.state === 'running')
270  const board = mine.length
271  let engine = 0
272  try {
273    engine = await agents()
274  } catch {
275  }
276  slot.background = slot.background.filter(at => now - at < BACKGROUND_MAX_MS)
277  const tokens = rec.ctx?.tokens
278  // The last compaction of any kind: the record's, or one just started here (its record comes when the engine reports it)
279  const lastCompact = (rec.compacts ?? []).reduce((m, c) => Math.max(m, c.at), slot.startedAt ?? 0)
280  const cacheLeftMs = rec.cache?.at === undefined ? undefined : ttl - (now - rec.cache.at)
281  const guardHeld = heldOpen(parseHeld(await i.get(heldKey(sessionId))), parseAllowOnce(await i.get(allowKey(sessionId))), now) !== undefined
282  return {
283    turnEnded: (turnId === undefined || slot.turnId === turnId) && rec.state !== 'working',
284    waitsForYou: rec.ask !== undefined,
285    agentsRunning: Math.max(board, engine),
286    foregroundAgents: mine.filter(r => !r.background).length,
287    backgroundRecent: slot.background.length,
288    guardHeld,
289    from: fromOf(await readSetting(i, 'compact.from')),
290    minTokens: minTokensOf(await readSetting(i, 'compact.min'), rec.ctx?.window),
291    tokens,
292    ...(rec.contextPercent === undefined ? {} : { percent: rec.contextPercent }),
293    payback: tokens === undefined ? undefined : paybackTurns({ tokens, after: lastAfterTokens(rec.compacts) ?? DEFAULT_AFTER_TOKENS, out: lastSummaryOut(rec.compacts) ?? DEFAULT_SUMMARY_OUT, warm: (cacheLeftMs ?? 0) > 0, ttlMs: ttl }),
294    // No answer has ended in this process yet: the idle time is not known, so it counts as none
295    quietMs: slot.endedAt === 0 ? 0 : now - slot.endedAt,
296    breakAtMs: breakAtMs(ttl, leadMsOf(await readSetting(i, 'compact.lead'))),
297    cacheLeftMs,
298    ttlKnown: knownTtl !== undefined,
299    sinceCompactMs: lastCompact === 0 ? undefined : now - lastCompact,
300  }
301}
302
303// Never throws.
304export async function notGoodNow(ops: CompactOps, sessionId: string, say: (name: string, vars?: Record<string, string | number>) => string): Promise<string[]> {
305  try {
306    const f = await restFacts(ops.io, ops.agents, sessionId)
307    return f === undefined ? [] : notGoodLines(restChecks(f), f, say)
308  } catch {
309    return []
310  }
311}
312
313// The looks Auto takes after an answer: the size trigger at SIZE_LOOK_MS and again at SIZE_LOOK2_MS, the break trigger when a break nears the end of the cache time and once more BREAK_RETRY_MS later
314type Look = 'size' | 'size2' | 'break' | 'break2'
315
316// Is the person's prompt box empty? A box that cannot be read counts as not empty, so Auto waits for the next look.
317async function boxEmpty($: EngineInterface): Promise<boolean> {
318  try {
319    const box = await $.prompt.read()
320    return box.text.trim() === ''
321  } catch {
322    return false
323  }
324}
325
326// Schedules one look for the turn that just ended; a new turn or the end of the session cancels it.
327function lookAt($: EngineInterface, sessionId: string, turnId: string, ms: number, which: Look): void {
328  const timer = $.clock.after(ms, () => void restLook($, sessionId, turnId, which))
329  restSlotOf(sessionId).timers.push(timer)
330}
331
332// One look at the moment. Never throws.
333async function restLook($: EngineInterface, sessionId: string, turnId: string, which: Look): Promise<void> {
334  const i = io($)
335  try {
336    // A timer that outlived its session does nothing
337    if ((await i.sessionId()) !== sessionId) return
338    const slot = restSlotOf(sessionId)
339    if (slot.turnId !== turnId) return
340    const mode = await readSetting(i, 'compact.mode')
341    if (mode !== 'watch' && mode !== 'auto') return
342    const f = await restFacts(i, agentsOf($), sessionId, turnId)
343    if (f === undefined) return
344    const checks = restChecks(f)
345    const ready = restReady(checks)
346    const now = await i.now()
347    await i.set(REST_KEY(sessionId), { at: now, ready, checks })
348    if (!ready) {
349      // One more look soon: the timer may have fired a little early, or a check may have failed for a moment
350      if (which === 'break' && f.ttlKnown !== false) lookAt($, sessionId, turnId, BREAK_RETRY_MS, 'break2')
351      return
352    }
353    if (mode === 'watch') {
354      slot.turnId = undefined
355      // A note, not an action: Watch did nothing, so it is not counted as done for you
356      await pushLog(i, LEDGER_KEY, { at: now, session: sessionId, what: WOULD_WHAT, detail: restDetail(f) })
357      return
358    }
359    if (giveUpMinOf(sessionId, now) > 0) return
360    // The size trigger never compacts over a prompt the person is typing: the second look tries again
361    if ((restTrigger(f) ?? 'size') === 'size' && !(await boxEmpty($))) return
362    await runAuto($, sessionId, turnId, f)
363  } catch {
364    // an automatic step never breaks the session
365  }
366}
367
368// What a path is, from the engine (a file, a folder, or something else
369function probeOf($: EngineInterface): Probe {
370  return async path => {
371    try {
372      const s = await $.fs.stat(path)
373      return { kind: s.kind, size: s.size }
374    } catch {
375      return undefined
376    }
377  }
378}
379
380// The helper agents the engine lists as running.
381function agentsOf($: EngineInterface): () => Promise<number> {
382  return async () => {
383    const list = await $.agent.list()
384    return list.filter(a => a.status === 'running').length
385  }
386}
387
388function opsOf($: EngineInterface): CompactOps {
389  return {
390    io: io($),
391    cwd: () => $.session.cwd(),
392    probe: probeOf($),
393    agents: agentsOf($),
394    command: args => $.command.run({ command: 'compact', args }),
395    direct: async instructions => {
396      const r = await $.session.compact({ instructions })
397      if (r.skip !== undefined) return { skip: r.skip }
398      return { tokensBefore: r.tokensBefore, tokensAfter: r.tokensAfter, outTokens: r.usage?.output_tokens, summary: r.messages[0]?.text }
399    },
400  }
401}
402
403type Saved = { ok: true; name: string; shown: string; checkpoint: boolean } | { ok: false }
404type AutoSaver = (i: Io, sessionId: string, cwd: string, probe: Probe) => Promise<Saved>
405let autoSaver: AutoSaver | undefined
406export const setAutoSaver = (fn: AutoSaver | undefined): void => {
407  autoSaver = fn
408}
409
410// It is a note, not an undo (the engine has no restore of a compaction).
411async function postNote(i: Io, sessionId: string, name: string): Promise<void> {
412  try {
413    const text = noteText(name)
414    await pushLog(i, LEDGER_KEY, { at: await i.now(), session: sessionId, what: AUTO_NOTE_WHAT, detail: text, how: 'auto', did: true })
415    i.toast(noteWords(text, tr))
416  } catch {
417  }
418}
419
420export type CompactEnd = 'busy' | 'skipped' | 'no-brief' | 'sent' | 'failed'
421
422// Claims the running flag (nothing awaited before it), looks at `stops` (Auto's checks
423export async function runCompaction(r: { how: 'button' | 'auto'; sessionId: string; ops: CompactOps; stops?: () => Promise<string | undefined>; because?: string; kind?: Trigger; pct?: number; same?: () => boolean }): Promise<CompactEnd> {
424  const owner = claimCompacting(r.how)
425  if (owner === undefined) return 'busy'
426  const i = r.ops.io
427  const auto = r.how === 'auto'
428  const log = async (what: string, detail?: string): Promise<void> => pushLog(i, LEDGER_KEY, { at: await i.now(), session: r.sessionId, what, ...(detail === undefined ? {} : { detail }) })
429  const skip = async (why: string): Promise<CompactEnd> => {
430    await log('auto-compact skipped', skippedWords(why))
431    return 'skipped'
432  }
433  i.invalidate()
434  try {
435    const first = r.stops === undefined ? undefined : await r.stops()
436    if (first !== undefined) return await skip(first)
437    const saved: Saved = autoSaver === undefined ? { ok: false } : await autoSaver(i, r.sessionId, await r.ops.cwd(), r.ops.probe)
438    if (!saved.ok) {
439      if (auto) return await skip(NO_BRIEF)
440      i.toast(t('toast.compact_no_brief'), true)
441      await log('compact now failed', NO_BRIEF)
442      return 'no-brief'
443    }
444    const late = r.stops === undefined ? undefined : await r.stops()
445    if (late !== undefined) return await skip(late)
446    restSlotOf(r.sessionId).turnId = undefined
447    restSlotOf(r.sessionId).startedAt = await i.now()
448    if (auto && r.kind !== undefined) autoWhy = { kind: r.kind, pct: r.pct, at: await i.now() }
449    const plan = (await readSetting(i, 'compact.card')) === 'on' ? await keepPlan(i, r.sessionId) : undefined
450    const keep = compactInstructions(plan?.text, saved.shown, await helpersNow(i, r.ops.agents, r.sessionId))
451    if (auto) {
452      await log('auto-compact starts', r.because)
453      if (r.because !== undefined) i.toast(r.because)
454    } else {
455      await log('compact now (button)')
456      i.toast(tr('Compacting the session'), true)
457    }
458    let refused: unknown
459    // A new turn may have started while the brief was saved: the check and the call stand together, nothing awaited between them
460    if (r.same !== undefined && !r.same()) return await skip(NEW_TURN)
461    if (r.ops.direct !== undefined) {
462      try {
463        const res = await r.ops.direct(keep)
464        if (res.skip !== undefined) {
465          await log('auto-compact skipped', res.skip)
466          return 'skipped'
467        }
468        await noteCompact(i, r.sessionId, 'plugin', res.tokensBefore, res.tokensAfter, res.outTokens, r.how)
469        // Our own call skips this module's session.compact hook, so it checks the summary here
470        await checkKept(i, r.sessionId, (plan?.items ?? []).filter(x => x.kind === 'file').map(x => x.name), plan?.items, res.summary)
471        if (auto) await postNote(i, r.sessionId, saved.name)
472        return 'sent'
473      } catch (err) {
474        refused = err === undefined ? new Error('refused') : err
475      }
476    }
477    if (r.same !== undefined && !r.same()) return await skip(NEW_TURN)
478    try {
479      await r.ops.command(keep)
480      if (compacting.seenBy !== owner) compacting.sent = { how: r.how, at: await i.now() }
481      if (refused !== undefined) await log('auto-compact sent as /compact', `direct call refused: ${why(refused)}`)
482      if (auto) await postNote(i, r.sessionId, saved.name)
483      return 'sent'
484    } catch (err2) {
485      if (auto) {
486        noteGiveUp(r.sessionId, await i.now())
487        await log('auto-compact could not run', refused === undefined ? why(err2) : `${why(refused)} | ${why(err2)}`)
488      } else {
489        i.toast(tr('Could not compact the session from here. Type /compact yourself.'), true)
490        await log('compact now failed', why(err2))
491      }
492      return 'failed'
493    }
494  } catch {
495    // a compaction never breaks the session
496    return 'failed'
497  } finally {
498    releaseCompacting(owner)
499    i.invalidate()
500  }
501}
502
503// Each check of the rule, as the stop that names it in the ledger
504const CHECK_STOP: Record<string, string> = { ended: 'working', helpers: 'foreground', guard: 'guard', size: 'small', gap: 'gap', time: 'early' }
505
506// Do helpers (agents or background commands) still run in this session? Then the summary must list them. Never throws.
507async function helpersNow(i: Io, agents: () => Promise<number>, sessionId: string): Promise<boolean> {
508  try {
509    const f = await restFacts(i, agents, sessionId)
510    return f !== undefined && helpersOpen(f)
511  } catch {
512    return false
513  }
514}
515
516// Never throws.
517export async function runAuto($: EngineInterface, sessionId: string, turnId: string, looked: RestFacts): Promise<void> {
518  const ops = opsOf($)
519  const kind = restTrigger(looked) ?? 'size'
520  const starts = restSlotOf(sessionId).starts
521  const stops = async (): Promise<string | undefined> => {
522    if (restSlotOf(sessionId).turnId !== turnId) return NEW_TURN
523    if (kind === 'size' && !(await boxEmpty($))) return TYPING
524    const fresh = await restFacts(ops.io, ops.agents, sessionId, turnId)
525    if (fresh === undefined) return NEW_TURN
526    const checks = restChecks(fresh)
527    if (restReady(checks)) return undefined
528    const first = checks.find(c => !c.ok)
529    const stop = first?.id === 'time' && helpersOpen(fresh) ? 'busy' : CHECK_STOP[first?.id ?? '']
530    return first === undefined ? NEW_TURN : (STOP_WORDS[stop ?? ''] ?? first.label)
531  }
532  await runCompaction({ how: 'auto', sessionId, ops, stops, kind, same: () => restSlotOf(sessionId).starts === starts, ...(looked.percent === undefined ? {} : { pct: looked.percent }), because: triggerWords(kind, looked.percent ?? 0, tr) })
533}
534
535// Keeps what one compaction did to the window: in this session's record (so the next advice uses the real summary size) and in the ledger.
536async function noteCompact(i: Io, sessionId: string, trigger: string, before?: number, after?: number, outTokens?: number, how?: Entry['how'], isLedger = true): Promise<void> {
537  const now = await i.now()
538  const old = await readRecord(i, sessionId)
539  await putRecord(i, { sessionId, compacts: withCompact(old?.compacts, { at: now, trigger, before, after, outTokens }) }, true)
540  // A compaction Auto started says when: "during a break, 640k to 18k tokens"
541  const why = how === 'auto' && autoWhy !== undefined && now >= autoWhy.at && now - autoWhy.at < SENT_MARK_MS ? `${detailWords(autoWhy.kind, autoWhy.pct)}, ` : ''
542  if (how === 'auto') autoWhy = undefined
543  if (isLedger) await pushLog(i, LEDGER_KEY, { at: now, session: sessionId, ...(before === undefined ? {} : { before }), ...(after === undefined ? {} : { after }), ...(how === undefined ? {} : { how }), what: `compacted (${trigger})`, detail: `${why}${before === undefined ? '?' : Math.round(before / 1000)}k to ${after === undefined ? '?' : Math.round(after / 1000)}k tokens${outTokens === undefined ? '' : `, summary output ${outTokens}`}` })
544}
545
546// The agent a turn belongs to, when the event names one (a helper agent's turn); the main session's turn names none.
547function loopOf(x: object): unknown {
548  return 'agentId' in x ? x.agentId : undefined
549}
550
551export function registerCompaction(on: On): void {
552  on('session.start', { cwd: /(?<cockpit>)/ }, async ($, e, next) => {
553    try {
554    } catch {
555      // the probe is a tool for us: a failure shows less, never breaks the session
556    }
557    return next(e)
558  }).catch(($, e, next) => next(e))
559
560  // Every compaction passes here (the person's /compact, the engine's own auto-compaction, a precompute).
561  on('session.compact', async ($, e, next) => {
562    let sent = e
563    let id = ''
564    let plan: { text: string; items: KeepItem[] } | undefined
565    let files: string[] = []
566    try {
567      const i = io($)
568      id = await i.sessionId()
569      if (e.agentId === undefined) {
570        files = filesFromMessages(e.messages ?? [])
571        plan = (await readSetting(i, 'compact.card')) === 'on' ? await keepPlan(i, id, files) : undefined
572        const parts = [plan?.text ?? '', (await helpersNow(i, agentsOf($), id)) ? HELPERS_LINE() : ''].filter(x => x !== '')
573        const instructions = parts.reduce((acc: string | undefined, part) => withKeepList(acc, part), e.instructions)
574        if (instructions !== e.instructions) {
575          sent = { ...e, instructions }
576        }
577      }
578    } catch {
579      sent = e
580    }
581    const result = await next(sent)
582    try {
583      if (e.agentId === undefined && e.trigger !== 'precompute' && result.skip === undefined && result.messages.length > 0) await checkKept(io($), id, files, plan?.items, result.messages[0].text)
584    } catch {
585    }
586    try {
587      // Our own automatic compact does not pass here (a call skips its caller's hooks), so it notes itself
588      if (e.agentId === undefined && e.trigger !== 'precompute') {
589        const doneAt = await $.clock.now()
590        if (result.skip === undefined) await noteCompact(io($), id, e.trigger, result.tokensBefore, result.tokensAfter, result.usage?.output_tokens, howNow(doneAt))
591        else await pushLog(io($), LEDGER_KEY, { at: doneAt, session: id, what: `compaction skipped (${e.trigger})`, detail: result.skip })
592      }
593    } catch {
594    }
595    return result
596  }).catch(($, e, next) => next(e))
597
598  on('turn.complete', { turnId: /(?<cockpit>)/ }, async ($, e, next) => {
599    if (e.agentId === undefined) {
600      try {
601        const i = io($)
602        const id = await i.sessionId()
603        const slot = restSlotOf(id)
604        cancelLooks(slot)
605        slot.turnId = e.turnId
606        slot.endedAt = await i.now()
607        const mode = await readSetting(i, 'compact.mode')
608        if (mode === 'watch' || mode === 'auto') {
609          // The size trigger looks a little after the answer and again later; the break trigger looks when the cache time, less the lead, has passed idle.
610          lookAt($, id, e.turnId, SIZE_LOOK_MS, 'size')
611          lookAt($, id, e.turnId, SIZE_LOOK2_MS, 'size2')
612          // Without a known plan the cache time is not known, so there is no break look
613          const ttl = cacheTtlMs(parseStoredUsage(await i.get(APP_USAGE_KEY)))
614          if (ttl !== undefined) lookAt($, id, e.turnId, breakAtMs(ttl, leadMsOf(await readSetting(i, 'compact.lead'))), 'break')
615        }
616      } catch {
617      }
618    }
619    return next(e)
620  }).catch(($, e, next) => next(e))
621
622  // A new main turn: the person is back, so the rest the rule waited on is over.
623  // A helper agent's turn is not the person coming back: it does not cancel the main session's look.
624  on('turn.start', { turnId: /(?<cockpit>)/ }, async ($, e, next) => {
625    try {
626      if (loopOf(e) === undefined) {
627        const slot = restSlotOf(await io($).sessionId())
628        slot.turnId = undefined
629        slot.starts += 1
630        cancelLooks(slot)
631      }
632    } catch {
633    }
634    return next(e)
635  }).catch(($, e, next) => next(e))
636
637  // The session ends: its looks go with it
638  on('session.end', { sessionId: /(?<compactlooks>)/ }, async ($, e, next) => {
639    try {
640      const slot = restSlotOf(e.sessionId)
641      slot.turnId = undefined
642      cancelLooks(slot)
643      slot.background = []
644      givenUp.delete(e.sessionId)
645    } catch {
646    }
647    return next(e)
648  }).catch(($, e, next) => next(e))
649
650  // A background command ended: its task notification reaches the session as a prompt of its own kind. The notification does not say which task it is, so it counts as the end of the oldest one counted; a notification that never comes is covered by BACKGROUND_MAX_MS.
651  on('prompt.submit', { text: /(?<compactbg>)/ }, async ($, e, next) => {
652    try {
653      if (endsBackground(e.origin)) backgroundEnded(await io($).sessionId())
654    } catch {
655    }
656    return next(e)
657  }).catch(($, e, next) => next(e))
658
659  // The quiet note to Claude at the crossing (core/compactnudge.ts): once per crossing of `compact.from`
660  on('tool.call', { tool: /(?<cockpitnudge>)/ }, async ($, e, next) => {
661    const result = await next(e)
662    try {
663      if (e.agentId !== undefined || result.deny !== undefined) return result
664      const i = io($)
665      const mode = await readSetting(i, 'compact.mode')
666      const id = await i.sessionId()
667      const key = NUDGE_KEY(id)
668      const sent = (await i.get(key)) === true
669      const from = fromOf(await readSetting(i, 'compact.from'))
670      const pct = (await readRecord(i, id))?.contextPercent
671      if (mode === 'off' || pct === undefined || pct < from) {
672        if (sent && mode !== 'off') await i.set(key, false)
673        return result
674      }
675      if (sent) return result
676      if (!(await tellsCompact(i))) return result
677      const facts = await restFacts(i, agentsOf($), id, restSlotOf(id).turnId ?? '')
678      if (facts === undefined) return result
679      const r = nudge({ mode, sent, from, minTokens: facts.minTokens, facts: { percent: facts.percent, tokens: facts.tokens, sinceCompactMs: facts.sinceCompactMs } })
680      if (r.sent !== sent) await i.set(key, r.sent)
681      return r.note === undefined ? result : { ...result, context: [...(result.context ?? []), r.note] }
682    } catch {
683      return result
684    }
685  }).catch(($, e, next) => next(e))
686
687  on('tool.call', { tool: /(?<cockpit>^(?:Bash|PowerShell)$)/ }, async ($, e, next) => {
688    const r = await next(e)
689    try {
690      const shown = r.result as { backgroundTaskId?: unknown } | undefined
691      if (shown?.backgroundTaskId !== undefined || fieldsOf(e).run_in_background === true) {
692        const i = io($)
693        const nowMs = await $.clock.now()
694        restSlotOf(await i.sessionId()).background.push(nowMs)
695      }
696    } catch {
697    }
698    return r
699  }).catch(($, e, next) => next(e))
700}
701
hooks/features/cost.ts 366 lines
1// Cost, why it cost, the limit consequence and budgets.
2import { tr } from '../core/lang'
3import { fillIn } from '../core/fillin'
4import { sayIn } from './saylang'
5import type { EngineInterface, On } from 'claude-code'
6
7import { APP_SESSIONS_KEY, parseStoredSessions } from '../core/appsessions'
8import { APP_USAGE_KEY, parseStoredUsage } from '../core/appusage'
9import { COST_SETTINGS, DAY_BUDGETS, SESSION_BUDGETS, addSample, addTool, addTurn, costText, estimateTotal, parseState, leanCutsRead, sizeKindOf, spendOf, turnOf, whereOf, whyText } from '../core/cost'
10import type { CostState, WhereWent } from '../core/cost'
11import { finishMem } from '../core/continuity'
12import { fieldsOf } from '../core/eventfields'
13import { isShellTool } from '../core/tools'
14import { EXTENDED_WHAT, HELD_WHAT, WARNED_WHAT, budgetLines, isCostly, ledgerHeld, ledgerWarned, noteText, optionNumber, parseAsk, readings, rises, stopReason, toExtend, toastText, worst } from '../core/budget'
15import type { Facts, Level, Which } from '../core/budget'
16import { limitsText, runningNow } from '../core/costlimits'
17import { withToastGate } from '../core/io'
18import { homeFrom, lastName } from '../core/platform'
19import type { Io } from '../core/io'
20import { HISTORY_KEY, parseHistory } from '../core/pace'
21import { PRICES_DATE, money, moneyEn } from '../core/prices'
22import { alivePids, listRecords } from '../core/record'
23import { readSetting, settingStoreKey } from '../core/settings'
24import { tellsClaude } from '../core/tellclaude'
25import { LEDGER_KEY, pushLog } from './compaction'
26import { ymd } from '../core/time'
27import { subArgs } from '../core/menu'
28
29// IO-BLOCK-START
30function io($: EngineInterface): Io {
31  return withToastGate({
32    now: () => $.clock.now(),
33    home: () => homeFrom({ HOME: () => $.env.get('HOME'), USERPROFILE: () => $.env.get('USERPROFILE'), HOMEDRIVE: () => $.env.get('HOMEDRIVE'), HOMEPATH: () => $.env.get('HOMEPATH') }),
34    sessionId: () => $.session.id(),
35    get: key => $.store.get(key),
36    set: (key, value) => $.store.set(key, value),
37    del: key => $.store.delete(key),
38    keys: () => $.store.keys(),
39    read: path => $.fs.read(path),
40    write: (path, text) => $.fs.write(path, text),
41    run: (argv, init) => $.process.run(argv, init),
42    ask: (question, options) => $.ui.ask(question, options),
43    complete: req => $.model.complete(req),
44    toast: text => $.ui.toast(text),
45    invalidate: () => $.ui.invalidate('ui.render'),
46  })
47}
48// IO-BLOCK-END
49
50const STATE_PREFIX = 'cockpit:cost:s:'
51const DAY_PREFIX = 'cockpit:cost:day:'
52const DAY_EXTRA_PREFIX = 'cockpit:cost:dayextra:'
53const KEEP_MS = 3 * 24 * 3_600_000
54
55const DEFAULT = (key: string): string => COST_SETTINGS.find(s => s.key === key)?.default ?? ''
56
57type Conf = { mode: string; session: number; day: number; why: boolean }
58async function conf(i: Io): Promise<Conf> {
59  return {
60    mode: await readSetting(i, 'cost.budget'),
61    session: optionNumber(await i.get(settingStoreKey('cost.session')), SESSION_BUDGETS, Number(DEFAULT('cost.session'))),
62    day: optionNumber(await i.get(settingStoreKey('cost.day')), DAY_BUDGETS, Number(DEFAULT('cost.day'))),
63    why: (await readSetting(i, 'cost.why')) === 'on',
64  }
65}
66
67let live: CostState | undefined
68let liveId = ''
69const told: Record<Which, Level> = { session: 'ok', day: 'ok' }
70let notes: string[] = []
71const heldLogged = new Set<string>()
72
73async function ensure(i: Io): Promise<CostState> {
74  const id = await i.sessionId()
75  if (live === undefined || liveId !== id) {
76    live = parseState(await i.get(STATE_PREFIX + id), await i.now())
77    liveId = id
78    told.session = 'ok'
79    told.day = 'ok'
80    notes = []
81    heldLogged.clear()
82  }
83  return live
84}
85
86const save = async (i: Io, s: CostState): Promise<void> => i.set(STATE_PREFIX + liveId, s)
87// The engine's cost readings of this session, kept in memory (no read): the Plan limits card's share of the 5-hour window (core/windowshare.ts)
88export const liveSamples = (id: string): ReadonlyArray<readonly [number, number]> | undefined => (live !== undefined && liveId === id ? live.samples : undefined)
89// Where this session's spend went (core/cost.ts whereOf), from memory: the Plan limits card's Where it went row
90export const liveWhere = (id: string | undefined): WhereWent | undefined => (live !== undefined && id !== undefined && liveId === id ? whereOf(live) : undefined)
91
92type DayRec = { base: number; usd: number }
93const isDayRec = (v: unknown): v is DayRec => typeof v === 'object' && v !== null && typeof (v as DayRec).base === 'number' && typeof (v as DayRec).usd === 'number'
94
95async function noteDay(i: Io, s: CostState, startedBeforeToday: () => Promise<boolean>): Promise<void> {
96  const now = await i.now()
97  const key = `${DAY_PREFIX}${ymd(now)}:${liveId}`
98  const old = await i.get(key)
99  const spend = spendOf(s).usd
100  const base = isDayRec(old) ? old.base : (await startedBeforeToday()) ? spend : 0
101  await i.set(key, { base, usd: Math.max(0, spend - base) } satisfies DayRec)
102}
103
104const OTHERS_EVERY_MS = 60_000
105let othersToday: { prefix: string; at: number; usd: number; sessions: number } | undefined
106async function daySum(i: Io): Promise<{ usd: number; sessions: number }> {
107  const now = await i.now()
108  const prefix = `${DAY_PREFIX}${ymd(now)}:`
109  const own = prefix + liveId
110  if (othersToday === undefined || othersToday.prefix !== prefix || now - othersToday.at < 0 || now - othersToday.at >= OTHERS_EVERY_MS) {
111    let usd = 0
112    let sessions = 0
113    for (const k of (await i.keys()).filter(x => x.startsWith(prefix) && x !== own)) {
114      const v = await i.get(k)
115      if (isDayRec(v)) {
116        usd += v.usd
117        sessions += 1
118      }
119    }
120    othersToday = { prefix, at: now, usd, sessions }
121  }
122  const mine = await i.get(own)
123  return isDayRec(mine) ? { usd: othersToday.usd + mine.usd, sessions: othersToday.sessions + 1 } : { usd: othersToday.usd, sessions: othersToday.sessions }
124}
125
126const dayExtra = async (i: Io): Promise<number> => {
127  const v = await i.get(DAY_EXTRA_PREFIX + ymd(await i.now()))
128  return typeof v === 'number' && v > 0 ? v : 0
129}
130
131async function factsNow(i: Io, s: CostState, c: Conf): Promise<{ facts: Facts; day: { usd: number; sessions: number }; extra: { session: number; day: number } }> {
132  const spend = spendOf(s)
133  const day = await daySum(i)
134  const extra = { session: s.extra, day: await dayExtra(i) }
135  return { facts: { mode: c.mode, source: spend.source, session: { usd: spend.usd, limit: c.session + extra.session }, day: { usd: day.usd, limit: c.day + extra.day } }, day, extra }
136}
137
138// Never throws.
139async function evaluate(i: Io): Promise<void> {
140  try {
141    const c = await conf(i)
142    if (c.mode === 'off') return
143    const s = await ensure(i)
144    const { facts } = await factsNow(i, s, c)
145    for (const r of rises(told, readings(facts))) {
146      // Warn tells the person only, unless the person chose All checks (core/tellclaude.ts).
147      if (c.mode === 'stop' || (await tellsClaude(i))) notes.push(noteText(r, c.mode))
148      // Used up is urgent: the hourly gate would take it for the 80% toast again, numbers aside.
149      i.toast(toastText(r, tr), r.level === 'over')
150      await pushLog(i, LEDGER_KEY, { at: await i.now(), session: liveId, what: WARNED_WHAT, detail: ledgerWarned(r), how: 'auto', did: true })
151      i.invalidate()
152    }
153  } catch {
154  }
155}
156
157// Whether this session began before today's midnight: the engine says when it began.
158async function beganBeforeToday($: EngineInterface, now: number): Promise<boolean> {
159  try {
160    const u = await $.session.usage()
161    return u.startedAt < new Date(ymd(now).replace(/-/g, '/')).getTime()
162  } catch {
163    return false
164  }
165}
166
167const folder = (cwd: string): string => lastName(cwd)
168
169export function registerCost(on: On): void {
170  on('session.start', { cwd: /(?<cost>)/ }, async ($, e, next) => {
171    try {
172      const i = io($)
173      live = undefined
174      await ensure(i)
175      const now = await i.now()
176      for (const k of await i.keys()) {
177        if (k.startsWith(STATE_PREFIX)) {
178          const st = parseState(await i.get(k), now)
179          const lastAt = Math.max(st.engineAt ?? 0, st.recent.at(-1)?.at ?? 0, st.startedAt)
180          if (now - lastAt > KEEP_MS && k !== STATE_PREFIX + liveId) await i.del(k)
181        } else if (k.startsWith(DAY_PREFIX) || k.startsWith(DAY_EXTRA_PREFIX)) {
182          const day = /(\d{4}-\d{2}-\d{2})/.exec(k)?.[1]
183          if (day !== undefined && now - new Date(day.replace(/-/g, '/')).getTime() > KEEP_MS) await i.del(k)
184        }
185      }
186    } catch {
187      // the cost is optional: a failure shows less, never breaks the session
188    }
189    return next(e)
190  }).catch(($, e, next) => next(e))
191
192  // The engine's own total, and what this session has spent today.
193  on('session.measure', { changed: /(?<cost>)/ }, async ($, e, next) => {
194    try {
195      if (e.cost !== undefined) {
196        const i = io($)
197        const s = await ensure(i)
198        const now = await i.now()
199        addSample(s, now, e.cost.usd)
200        await noteDay(i, s, () => beganBeforeToday($, now))
201        await save(i, s)
202        await evaluate(i)
203      }
204    } catch {
205    }
206    return next(e)
207  }).catch(($, e, next) => next(e))
208
209  // Each turn's tokens and model, from the engine.
210  on('turn.complete', { turnId: /(?<cost>)/ }, async ($, e, next) => {
211    try {
212      // Finish safely pressed while Claude worked, and the turn ended with no step to carry it: it goes as a message of its own
213      const finish = e.agentId === undefined ? finishMem.note : undefined
214      if (finish !== undefined) {
215        finishMem.note = undefined
216        // After this hook, so the turn has ended before the message is sent
217        $.clock.after(0, () => {
218          void (async () => {
219            try {
220              await $.prompt.submit({ text: finish, asUser: true })
221            } catch {
222            }
223          })()
224        })
225      }
226      const i = io($)
227      const s = await ensure(i)
228      const t = turnOf(e.usage, await i.now(), e.durationMs, e.agentId !== undefined)
229      if (t !== undefined) {
230        addTurn(s, t)
231        const now = await i.now()
232        await noteDay(i, s, () => beganBeforeToday($, now))
233        await save(i, s)
234        await evaluate(i)
235      }
236    } catch {
237    }
238    return next(e)
239  }).catch(($, e, next) => next(e))
240
241  on('tool.call', { tool: /(?<cost>)/ }, async ($, e, next) => {
242    const i = io($)
243    try {
244      if (isCostly(e.tool)) {
245        const c = await conf(i)
246        if (c.mode === 'stop') {
247          const s = await ensure(i)
248          const { facts } = await factsNow(i, s, c)
249          const over = worst(readings(facts).filter(r => r.level === 'over'))
250          if (over !== undefined) {
251            const key = `${e.tool}:${over.which}`
252            if (!heldLogged.has(key)) {
253              heldLogged.add(key)
254              await pushLog(i, LEDGER_KEY, { at: await i.now(), session: liveId, what: HELD_WHAT, detail: ledgerHeld(e.tool, over), how: 'auto', did: true })
255              i.toast(tr('Stopped a call to {tool}: the {which} cost budget is used up. Type /vaken-usage budget extend to go on.').replace('{tool}', e.tool).replace('{which}', tr(over.which)))
256              i.invalidate()
257            }
258            return { deny: stopReason(e.tool, over) }
259          }
260        }
261      }
262    } catch {
263    }
264    const result = await next(e)
265    // Nothing below may throw: a failure after next must not run the tool twice.
266    try {
267      if (result.deny === undefined && live !== undefined) {
268        const kind = e.agentId === undefined ? sizeKindOf(e.tool, isShellTool(e.tool)) : undefined
269        addTool(live, (result.text ?? '').length, kind, kind === 'read' && leanCutsRead(e.tool, fieldsOf(e), result.text ?? ''))
270        // Finish safely pressed while Claude works (core/continuity.ts): the request goes with this step's result, once
271        const finish = e.agentId === undefined ? finishMem.note : undefined
272        if (finish !== undefined) finishMem.note = undefined
273        if (notes.length > 0 || finish !== undefined) {
274          const out = { ...result, context: [...(result.context ?? []), ...notes, ...(finish === undefined ? [] : [finish])] }
275          notes = []
276          return out
277        }
278      }
279    } catch {
280    }
281    return result
282  }).catch(($, e, next) => next(e))
283
284  on('command.run', { command: 'vaken-usage' }, async ($, e, next) => {
285    const rest0 = subArgs(e.args, 'cost')
286    if (rest0 === undefined) return next(e)
287    const i = io($)
288    await sayIn(i)
289    const s = await ensure(i)
290    const c = await conf(i)
291    const { facts, day, extra } = await factsNow(i, s, c)
292    const model = s.recent.filter(t => !t.sub).at(-1)?.model
293    return { text: costText({ state: s, now: await i.now(), ...(model === undefined ? {} : { model }), day, budget: budgetLines(facts, extra, day.sessions) }) }
294  })
295
296  on('command.run', { command: 'vaken-usage' }, async ($, e, next) => {
297    const rest0 = subArgs(e.args, 'why')
298    if (rest0 === undefined) return next(e)
299    const i = io($)
300    await sayIn(i)
301    const c = await conf(i)
302    if (!c.why) return { text: tr('The "why it cost" paragraph is off. Turn it on: Settings > Money and plan.') }
303    const s = await ensure(i)
304    const source = s.engineUsd === undefined ? '' : ` ${fillIn(tr("The engine's own total for the session is {usd}."), { usd: money(s.engineUsd) })}`
305    return { text: `${whyText(s)}${estimateTotal(s) > 0 ? `${source}\n${fillIn(tr('Source: the token counts the engine reported for each answer, priced with the list prices of {date}. Estimate.'), { date: PRICES_DATE })}` : ''}` }
306  })
307
308  on('command.run', { command: 'vaken-usage' }, async ($, e, next) => {
309    const rest0 = subArgs(e.args, 'limits')
310    if (rest0 === undefined) return next(e)
311    const i = io($)
312    await sayIn(i)
313    const now = await i.now()
314    const usage = parseStoredUsage(await i.get(APP_USAGE_KEY))
315    const records = await listRecords(i)
316    const alive = await alivePids(i, records)
317    const live2 = records.filter(r => alive === undefined || r.pid === undefined || alive.has(r.pid))
318    const running = runningNow(live2, parseStoredSessions(await i.get(APP_SESSIONS_KEY)), now)
319    const spenders = live2
320      .filter(r => r.state === 'working' && r.costUsd !== undefined)
321      .sort((a, b) => (b.costUsd ?? 0) - (a.costUsd ?? 0))
322      .map((r): [string, number] => [r.title ?? folder(r.cwd), r.costUsd ?? 0])
323    return { text: limitsText({ usage, history: parseHistory(await i.get(HISTORY_KEY)), running, spenders, now }) }
324  })
325
326  on('command.run', { command: 'vaken-usage' }, async ($, e, next) => {
327    const rest0 = subArgs(e.args, 'budget')
328    if (rest0 === undefined) return next(e)
329    const i = io($)
330    await sayIn(i)
331    const ask = parseAsk(rest0)
332    if (ask.kind === 'bad') return { text: ask.why }
333    const c = await conf(i)
334    const s = await ensure(i)
335    const now = await factsNow(i, s, c)
336    if (ask.kind === 'status') return { text: [...budgetLines(now.facts, now.extra, now.day.sessions), '', tr('At 100% in Stop mode, /vaken-usage budget extend lifts the block. It adds one more budget to the one that is at 80% or more.')].join('\n') }
337    if (c.mode === 'off') return { text: tr('The budget is off, so there is nothing to extend. Turn it on: Settings > Money and plan.') }
338    const which = toExtend(ask, readings(now.facts))
339    if (which.length === 0) return { text: tr('Nothing to extend: no budget is at 80% yet. To raise one anyway: /vaken-usage budget extend session, or /vaken-usage budget extend day.') }
340    const added: string[] = []
341    // The ledger keeps the English line; the answer says it in the language
342    const addedEn: string[] = []
343    for (const w of which) {
344      if (w === 'session') {
345        s.extra += c.session
346        await save(i, s)
347        added.push(fillIn(tr('session budget +{add}, now {now}'), { add: money(c.session), now: money(c.session + s.extra) }))
348        addedEn.push(`session budget +${moneyEn(c.session)}, now ${moneyEn(c.session + s.extra)}`)
349      } else {
350        const extra = now.extra.day + c.day
351        await i.set(DAY_EXTRA_PREFIX + ymd(await i.now()), extra)
352        added.push(fillIn(tr('day budget +{add}, now {now}'), { add: money(c.day), now: money(c.day + extra) }))
353        addedEn.push(`day budget +${moneyEn(c.day)}, now ${moneyEn(c.day + extra)}`)
354      }
355    }
356    const after = await factsNow(i, s, c)
357    rises(told, readings(after.facts))
358    notes = []
359    heldLogged.clear()
360    await pushLog(i, LEDGER_KEY, { at: await i.now(), session: liveId, what: EXTENDED_WHAT, detail: `${addedEn.join('; ')} (estimates).`, how: 'typed', did: true })
361    i.invalidate()
362    const still = worst(readings(after.facts).filter(r => r.level === 'over'))
363    return { text: fillIn(tr('Extended: {list}. {then}'), { list: added.join('; '), then: still === undefined ? tr('Costly calls are allowed again.') : fillIn(tr('The {which} budget is still used up. Extend again to go on.'), { which: tr(still.which) }) }) }
364  })
365}
366
hooks/features/insight.ts 210 lines
1// Insight runtime: the audit export, wait tracking, the quota planner, review by story and cost per outcome.
2import type { EngineInterface, On } from 'claude-code'
3import { fieldsOf } from '../core/eventfields'
4
5import { parseStoredUsage, APP_USAGE_KEY } from '../core/appusage'
6import { parseState as parseCost, spendOf } from '../core/cost'
7import { freePath } from '../core/fileops'
8import { t, tr } from '../core/lang'
9import { sayIn } from './saylang'
10import { refusedWords, safeWrite, takenProbe } from '../core/safewrite'
11import type { SafeFs } from '../core/safewrite'
12import { readNote } from '../core/flush'
13import { withToastGate } from '../core/io'
14import { isShellTool } from '../core/tools'
15import { homeFrom } from '../core/platform'
16import type { Io } from '../core/io'
17import { AUDIT_KEY, OUTCOMES_KEY, tidyKeys, tidyText, addOutcome, addWait, auditFile, auditText, fitText, outcomesText, parseAudit, parseNumstat, parseOutcomes, parseWaits, storyText, waitsKey, waitsText } from '../core/insight'
18import { doneMet, readState, stateKey } from '../core/proof'
19import { listRecords, readRecord } from '../core/record'
20import { serialUpdate } from '../core/serial'
21import { LEDGER_KEY, pushLog } from './compaction'
22import { armOnce } from './everyonce'
23import { subArgs } from '../core/menu'
24
25// IO-BLOCK-START
26function io($: EngineInterface): Io {
27  return withToastGate({
28    now: () => $.clock.now(),
29    home: () => homeFrom({ HOME: () => $.env.get('HOME'), USERPROFILE: () => $.env.get('USERPROFILE'), HOMEDRIVE: () => $.env.get('HOMEDRIVE'), HOMEPATH: () => $.env.get('HOMEPATH') }),
30    sessionId: () => $.session.id(),
31    get: key => $.store.get(key),
32    set: (key, value) => $.store.set(key, value),
33    del: key => $.store.delete(key),
34    keys: () => $.store.keys(),
35    read: path => $.fs.read(path),
36    write: (path, text) => $.fs.write(path, text),
37    run: (argv, init) => $.process.run(argv, init),
38    ask: (question, options) => $.ui.ask(question, options),
39    complete: req => $.model.complete(req),
40    toast: text => $.ui.toast(text),
41    invalidate: () => $.ui.invalidate('ui.render'),
42  })
43}
44// IO-BLOCK-END
45
46// The engine's file calls a safe write needs (core/safewrite.ts).
47function safeFs($: EngineInterface): SafeFs {
48  return { stat: (path, options) => $.fs.stat(path, options), list: path => $.fs.list(path) }
49}
50
51let askOpen: { since: number; kind: 'question' | 'permission' } | undefined
52const COST_PREFIX = 'cockpit:cost:s:'
53const lastCostKey = (id: string): string => `cockpit:outcomes:last:${id}`
54const MIN_OUTCOME_USD = 0.01
55let doneMark = ''
56
57async function noteWait(i: Io, kind: 'question' | 'permission' | 'after', ms: number): Promise<void> {
58  const now = await i.now()
59  await serialUpdate(i, waitsKey(), old => addWait(parseWaits(old, now), kind, ms))
60}
61
62async function noteOutcome(i: Io, kind: 'done' | 'merged'): Promise<void> {
63  const id = await i.sessionId()
64  const now = await i.now()
65  const spend = spendOf(parseCost(await i.get(COST_PREFIX + id), now))
66  const before = typeof (await i.get(lastCostKey(id))) === 'number' ? ((await i.get(lastCostKey(id))) as number) : 0
67  const usd = Math.max(0, spend.usd - before)
68  if (usd < MIN_OUTCOME_USD) return
69  await i.set(lastCostKey(id), spend.usd)
70  const outcome = { at: now, kind, usd, session: id.slice(0, 8) }
71  await serialUpdate(i, OUTCOMES_KEY, old => addOutcome(parseOutcomes(old), outcome), stored => parseOutcomes(stored).some(o => o.at === now && o.session === outcome.session && o.kind === kind))
72  await pushLog(i, LEDGER_KEY, { at: now, session: id, what: kind === 'merged' ? 'Noted a merged pull request' : 'Noted finished work', detail: `Cost since the last outcome: about $${usd.toFixed(2)} (estimate).`, how: 'auto' })
73}
74
75export function registerInsight(on: On): void {
76  on('session.start', { cwd: /(?<insight>)/ }, async ($, e, next) => {
77    try {
78      const timer = $.clock.every(15_000, () => {
79        void (async () => {
80          try {
81            const i = io($)
82            const rec = await readRecord(i, await i.sessionId())
83            const now = await i.now()
84            if (rec?.ask !== undefined && askOpen === undefined) askOpen = { since: rec.ask.since, kind: rec.ask.kind }
85            else if (rec?.ask === undefined && askOpen !== undefined) {
86              await noteWait(i, askOpen.kind, now - askOpen.since)
87              askOpen = undefined
88            }
89          } catch {
90          }
91        })()
92      })
93      armOnce('insight', timer)
94    } catch {
95    }
96    return next(e)
97  }).catch(($, e, next) => next(e))
98
99  on('prompt.submit', { text: /(?<insight>)/ }, async ($, e, next) => {
100    try {
101      const i = io($)
102      if (!e.text.trimStart().startsWith('/')) {
103        const rec = await readRecord(i, await i.sessionId())
104        if (rec !== undefined && rec.state === 'waiting') await noteWait(i, 'after', (await i.now()) - rec.stateSince)
105      }
106    } catch {
107    }
108    return next(e)
109  }).catch(($, e, next) => next(e))
110
111  on('tool.call', { tool: /(?<insight>)/ }, async ($, e, next) => {
112    const result = await next(e)
113    try {
114      if (isShellTool(e.tool) && e.agentId === undefined && result.deny === undefined && result.isError !== true && /(^|[;&|]\s*)gh\s+pr\s+merge\b/.test(String(fieldsOf(e).command ?? ''))) await noteOutcome(io($), 'merged')
115    } catch {
116    }
117    return result
118  }).catch(($, e, next) => next(e))
119
120  on('turn.complete', { turnId: /(?<insight>)/ }, async ($, e, next) => {
121    if (e.agentId === undefined) {
122      $.clock.after(4_000, () => {
123        void (async () => {
124          try {
125            const i = io($)
126            const s = readState(await readNote(i, stateKey(await i.sessionId())))
127            const mark = `${s.seq}:${s.done.join(',')}`
128            if (s.done.length > 0 && doneMet(s, s.done) && mark !== doneMark) {
129              doneMark = mark
130              await noteOutcome(i, 'done')
131            }
132          } catch {
133          }
134        })()
135      })
136    }
137    return next(e)
138  }).catch(($, e, next) => next(e))
139
140  on('command.run', { command: 'vaken-help' }, async ($, e, next) => {
141    const rest0 = subArgs(e.args, 'run', 'audit')
142    if (rest0 === undefined) return next(e)
143    const i = io($)
144    await sayIn(i).catch(() => undefined)
145    const rows = parseAudit(await i.get(AUDIT_KEY))
146    if (rest0.trim().toLowerCase() === 'export') {
147      if (rows.length === 0) return { text: tr('Nothing to export yet.') }
148      // An export never overwrites a file that is there: it takes the next free name (cockpit-audit-2.md).
149      const root = await $.session.root()
150      const fs = safeFs($)
151      const path = await freePath(takenProbe(fs), `${root}/.claude/cockpit-audit.md`)
152      if (path === undefined) return { text: tr('Too many exports are in the .claude folder already. Remove an old .claude/cockpit-audit*.md file and try again.') }
153      if (!(await safeWrite(fs, (p, x) => i.write(p, x), root, path, auditFile(rows))).ok) return { text: refusedWords(path, tr) }
154      return { text: t('cmdd.wrote_path_n_actions', { path, n: rows.length }) }
155    }
156    return { text: auditText(rows) }
157  })
158
159  on('command.run', { command: 'vaken-today' }, async ($, e, next) => {
160    const rest0 = subArgs(e.args, 'waits')
161    if (rest0 === undefined) return next(e)
162    const i = io($)
163    await sayIn(i).catch(() => undefined)
164    return { text: waitsText(parseWaits(await i.get(waitsKey()), await i.now())) }
165  })
166
167  on('command.run', { command: 'vaken-usage' }, async ($, e, next) => {
168    const rest0 = subArgs(e.args, 'fit')
169    if (rest0 === undefined) return next(e)
170    const i = io($)
171    await sayIn(i).catch(() => undefined)
172    return { text: fitText(parseStoredUsage(await i.get(APP_USAGE_KEY)), Number(rest0.trim().replace('%', '')), await i.now()) }
173  })
174
175  on('command.run', { command: 'vaken-ship' }, async ($, e, next) => {
176    const rest0 = subArgs(e.args, 'review-story')
177    if (rest0 === undefined) return next(e)
178    const i = io($)
179    await sayIn(i).catch(() => undefined)
180    try {
181      const cwd = await $.session.cwd()
182      const r = await i.run(['git', 'diff', '--numstat', 'HEAD'], { cwd, timeoutMs: 5_000 })
183      const goal = readState(await readNote(i, stateKey(await i.sessionId()))).goal?.text
184      return { text: storyText(goal, r.exitCode === 0 ? parseNumstat(r.stdout) : []) }
185    } catch {
186      return { text: tr('Vaken could not read the change with git.') }
187    }
188  })
189
190  on('command.run', { command: 'vaken-help' }, async ($, e, next) => {
191    const rest0 = subArgs(e.args, 'run', 'outcomes')
192    if (rest0 === undefined) return next(e)
193    const i = io($)
194    await sayIn(i).catch(() => undefined)
195    return { text: outcomesText(parseOutcomes(await i.get(OUTCOMES_KEY)), await i.now()) }
196  })
197
198  on('command.run', { command: 'vaken-help' }, async ($, e, next) => {
199    const rest0 = subArgs(e.args, 'run', 'tidy')
200    if (rest0 === undefined) return next(e)
201    const i = io($)
202    await sayIn(i).catch(() => undefined)
203    const live = [...(await listRecords(i)).map(r => r.sessionId), await i.sessionId()]
204    const keys = tidyKeys(await i.keys(), live)
205    if (rest0.trim().toLowerCase() !== 'yes') return { text: tidyText(keys, false) }
206    for (const k of keys) await i.del(k)
207    return { text: tidyText(keys, true) }
208  })
209}
210