attend's agent-facing driver in Claude Code (ADR-406): dormant by default, listening on request or by project config, one status row, typed tools over the…

<img src="docs/images/agent-ways-logo.svg" alt="Agent Ways logo — a W made of nodes and edges with a red-to-green gradient representing attention falloff, emerging from a dim background knowledge graph" width="600" />
Organizational socialization for AI coding agents. Ways encode "the way we do it around here" — the local norms an agent cannot know because it was never told them — and deliver them the way human teams actually transmit norms: situated, at the moment of relevant action, just before tools execute.
An LLM session cannot internalize norms — no weight updates, no carried memory; every session is a new hire. So the system re-enacts socialization mechanically, on a spaced schedule that substitutes for the memory the agent does not have. In one sentence: procedural memory for coding agents, maintained by spaced repetition. Every project-coined term here maps to an established concept — the vocabulary reference is the index.
Current status: Agent Ways ships with full support for Claude Code. Support for additional CLI-based coding agents is in development.
<a href="https://youtu.be/Ma4sDBPJVvU"><img src="https://img.youtube.com/vi/Ma4sDBPJVvU/maxresdefault.jpg" alt="Video: A turn with agent-ways, a two-minute animated explainer on YouTube" width="720" /></a> <sub><b>A turn with agent-ways</b> (2 min): one Claude Code turn as the hooks see it, then two sessions and a person on the attend bus. <a href="https://youtu.be/Ma4sDBPJVvU">Watch on YouTube</a> or play the <a href="https://aaronsb.github.io/agent-ways/explainers/a-turn-with-ways/">interactive version</a>.</sub>
sequenceDiagram
participant U as You
participant C as Agent
participant W as Ways
participant J as Judge (optional)
rect rgba(21, 101, 192, 0.2)
U->>C: "fix the auth bug"
W->>J: matched: Security, Debugging, Commits
J-->>W: relevant: Security, Debugging
W-->>C: Security · Debugging
end
rect rgba(106, 27, 154, 0.2)
C->>W: about to run: git commit
W-->>C: Commit format rules
Note right of W: tool lanes skip the judge
end
rect rgba(0, 105, 92, 0.2)
C->>W: spawning subagent
W-->>C: Security, to the subagent
end
rect rgba(198, 40, 40, 0.15)
Note over U,J: Context fills up → auto-compact → ways reset → cycle repeats
end
Ways = policy and process encoded as contextual guidance. Triggered by keywords, commands, and file patterns — they fire before tools execute, re-disclose on a token-distance cadence as their influence fades, and carry into subagents.
Why this works: System prompt adherence decays as a power law over conversation turns — instructions at position zero lose influence as context grows. This is the forgetting curve (Ebbinghaus) operating over token distance instead of days, and the countermeasure is the one human learning already uses: spaced repetition. Ways inject small, relevant guidance near the attention cursor at the moment it matters and re-disclose it as its influence fades, maintaining steady-state adherence instead of a damped sawtooth. It's progressive disclosure applied to the model itself.
ways session replayways session replay replays a session's way-firing history frame by frame, and follows a live session as it writes. Each frame shows a way firing at a specific point in the conversation — you can see how guidance clusters near the active attention cursor and packs into the context window like a compression pattern.
<sub>Download the recording (228K MP4).</sub>
Semantic matching runs on your machine through the embedding engine (all-MiniLM-L6-v2, a ~21MB GGUF model). It handles similarity of meaning: "pin lockfile versions" matches the supply chain way even though those exact words are absent from the way's vocabulary. ways status reports the matcher's current calibration.
Matching proposes; the relevance judge decides. On your prompts, and on messages you queue while Claude works, the ways that matched go to a small hosted model (Claude Haiku, through Anthropic or OpenRouter) that answers yes or no for each, up to eight per prompt. Only the ways it passes are injected, so a way that shares words with your prompt but not its intent stays out. The judge runs in the resident ways-agent, which holds the API key. Without a key, or when the judge can't answer in time, every matched way is injected as before. The relevance judge covers the flow, what it sends, and what it costs.
This repo ships with software development ways, but the mechanism is general-purpose. You could have ways for:
agent-ways is a suite of binaries plus the ways corpus, the hooks that deliver it, skills and subagents. tools/suite-bins lists the Rust binaries the installer builds and links onto your PATH.
flowchart LR
classDef outside fill:#475569,stroke:#94a3b8,color:#ffffff
classDef core fill:#7c3aed,stroke:#4a5568,color:#ffffff
classDef compute fill:#2d7d9a,stroke:#4a5568,color:#ffffff
classDef store fill:#2d8e5e,stroke:#4a5568,color:#ffffff
classDef external fill:#f6821f,stroke:#4a5568,color:#1a1a1a
CC["Claude Code<br>hooks · Monitor · MCP"]:::outside
W["ways CLI<br>the hook engine"]:::core
E["way-embed<br>local embeddings"]:::compute
R[("ways roots<br>project · user · core")]:::store
A["ways-agent<br>judge daemon, holds the key"]:::core
P["hosted provider<br>Anthropic or OpenRouter"]:::external
M["ways-mcp<br>registered as agent-ways<br>ways_status"]:::core
AT["attend<br>sensor loop"]:::compute
B[("message bus<br>signal files · channels")]:::store
CH["attend-chat<br>you, on the bus"]:::outside
AU["ways-audit<br>compliance claims"]:::compute
CC -->|hook events| W
W -->|guidance| CC
W -->|match| E
W -->|read ways| R
W -->|prompt and queued matches| A
A -->|yes or no per way| P
CC -->|Monitor, Stop hook| AT
CC -->|MCP tools| M
AT <--> B
CH <--> B
AU -->|"project or core root"| R
The judge is the only part that sends conversation text off your machine, and only when you have stored a provider key. docs/architecture.md draws the hook flow, the matching pipeline and the per-agent disclosure state machine.
| Component | What it does | Docs |
|---|---|---|
ways | The CLI and the hook engine. Every hook script calls it to match ways, track session state and inject guidance. It also carries install, update, settings and authoring commands. | CLI reference |
way-embed | The embedding engine (C++, llama.cpp) for semantic matching. It is optional: without it, only pattern:, commands:, files: and tool_name: triggers fire. | Matching, finishing an install |
ways-agent | A resident per-user daemon that holds your provider key and runs the relevance judge. The hook starts it on first use. | Relevance judge, ADR-502 |
ways-mcp | The agent-ways MCP server, registered with Claude Code as agent-ways. Today it hosts one read-only tool, ways_status. ADR-501 plans attend and keepalive modules on it. | ADR-501 |
attend | The awareness layer: sensors for git state, peer sessions and process activity, surfaced into a running session as notifications. | Attend and Monitor |
attend-chat | A terminal chat that puts you on the same signal bus the agents use. | attend chat |
ways-audit | Reports on the compliance claims ways carry: coverage, control traces, provenance lint. | Governance |
Attend delivers a peer's message to a session two ways: a Monitor line wakes an idle session, and the Stop hook hands messages over at the end of a busy turn (delivery). Its keepwarm sensor, once armed, wakes an idle session before the prompt cache lapses (keepwarm). In attend chat you address agents by name or channel on the same bus:
<img src="docs/images/attend/attend-chat-fanout.png" alt="attend-chat on the merged tab: messages from the agents Elio and Lachlan and from the operator, each with its project and channel mark, and a draft addressed to @Elio @Lachlan with both recipients flagged under the input" width="720" />
Runs on Linux and macOS. The installer needs git, jq and make, and stops if any is missing.
| Tool | Purpose | Notes | |
|---|---|---|---|
| Claude Code | The agent this configures | `curl -fsSL https://claude.ai/install.sh \ | bash` |
git | Stages the app source, update checks | Usually pre-installed | |
jq | JSON in hook scripts and macros | Must install | |
make | Drives the build and the binary downloads | Usually pre-installed with a build toolchain | |
python3 | The adr and doc tools, chart-tool, the bash-bound guard | Stdlib only, no pip packages | |
gh, logged in | Downloads the prebuilt binaries; issue sync, repo macros | Run gh auth login. Without it every binary builds from source | |
cargo | Source build of a suite binary | When gh is missing or logged out, or no prebuilt fits your platform | |
cmake, C++ compiler | Source build of way-embed | Same as cargo; make deps installs them |
make setup acquires each suite binary in this order: keep a working one in bin/, download the prebuilt release through gh, build from source with cargo. Standard utilities (bash, awk, sed, grep, find, timeout, tr, sort, wc, date) are assumed present via coreutils.
make setup also fetches the embedding engine and its model. If that step fails, the install still completes, and Finishing an install walks through turning semantic matching on.
Platform install guides: macOS (Homebrew) · Arch Linux · Debian / Ubuntu · Fedora / RHEL
macOS note:
timeoutis a GNU coreutils command not present by default. Installcoreutilsvia Homebrew — see the macOS guide for PATH setup.
curl -sL https://raw.githubusercontent.com/aaronsb/agent-ways/main/scripts/install.sh | bash -s -- --bootstrap
The installer:
$XDG_DATA_HOME/agent-ways and builds the binaries, fetching the embedding model (~21MB);~/.local/bin;ways manage repair --commit, which applies with no flag), which symlinks the projected roots (skills/, agents/, commands/, hooks/ways/, built binaries) into ~/.claude, merges its hook entries and permissions into settings.json, and registers the agent-ways MCP server in ~/.claude.json;Your existing ~/.claude (sessions, credentials, your own settings.json values, projects/) is preserved. If one of the projected root paths is already a real directory of yours, reconcile stops and names it; it never deletes it. The install guide covers that case, forks and previous installs. Restart Claude Code and the ways are active.
To customize, add your own ways under $XDG_CONFIG_HOME/agent-ways/ways/ (see Creating Ways). To replace the shipped corpus, fork the repo and install from your fork. To work on agent-ways itself, set up a development checkout.
To remove it, ways manage uninstall lists what it would do: withdraw from ~/.claude and your other targets, remove the MCP registration, unlink the commands, delete the app and its caches. ways manage uninstall --commit does it. Your own ways, API keys and event log stay unless you add --purge (ADR-198). To put the same version back cleanly, ways manage reinstall --commit fetches it first, then uninstalls and installs, keeping what is yours.
Stop and read this if you're letting an AI agent run the installer. You are about to let an agent modify
~/.claude/— the directory that controls how Claude Code behaves. The agent is editing its own configuration. Review the repo first. You are responsible for the result.
core.md loads at session start with behavioral guidance, operational rules, and a dynamic ways index. Then, as you work:
enforce mode a way it judges irrelevant is held back; in shadow mode it only logs its verdicts; off skips it.A way fires when matched, then re-discloses on its refire: cadence (a fraction of the context window, ADR-126) as its salience decays. A marker file per way and agent records the fire and drives that re-disclosure state machine; it does not block the way for good.
Matching has two channels: regex patterns for known keywords/commands/files, and sentence-embedding semantic scoring (all-MiniLM-L6-v2). See matching.md for the full strategy. The judge sends text from your conversation to a hosted model; the install guide says what and gives the commands.
ways session opens the session screen. Its timeline tab lists each way once per agent that fired it, with the epoch, the distance back, the trigger and the re-disclosure forecast, and marks what happened to each way: injected, re-disclosed, or kept out by the judge. ways session ways prints the current session's list as text.
<img src="docs/images/ways/session-timeline.png" alt="The ways session timeline at epoch 9 of a 200K-token session, matched view: an Agent column naming main, code-reviewer, a workflow member, two general-purpose subagents and one by id; ways marked as injected, re-disclosed, shadow-flagged, judge-blocked with P(yes) 0.050, held by the context cap and held in the refire window; a check line showing five fires and decay 0.17; and the context gauge at 29% with a forecast of re-disclosures between 58K and 104K tokens" width="800" />
The CLI reference explains each column and mark.
For the complete system guide — trigger flow, state machines, the pipeline from principle to implementation — see docs/hooks-and-ways/README.md.
ways settings on a terminal opens the settings screens: ways, matching, gate, install, attend, sensors and theme. An edit is queued, and nothing reaches a file until you review and apply it. On the gate tab, Enter on a profile's model opens a picker of the models the provider serves, once ways agent models has fetched them:
<img src="docs/images/ways/settings-model-picker.png" alt="The gate tab of ways settings: the anthropic profile's keys in a tree on the left, a picker over it listing claude-haiku-4-5 (current), claude-3-5-haiku-latest, claude-opus-4-5 and claude-sonnet-4-5, and the detail pane on the right giving the key's default and the file it writes, agent.yaml" width="720" />
The same keys work from the command line:
ways settings list # every key and its value
ways settings help ways.disabled_domains # what a key does, its type and default
ways settings set ways.disabled_domains itops,ea
ways settings set gate.mode shadow
User settings live in $XDG_CONFIG_HOME/agent-ways/config.yaml, except the gate.* keys, which live in agent.yaml beside it, and the attend.* keys, which live in $XDG_CONFIG_HOME/attend/config.yaml. A project overlays its own: ways keys in .claude/ways.yaml, attend keys in .claude/attend.yaml. ways settings help <key> names each key's file. The file form of the disabled_domains example:
disabled_domains:
- itops
- ea
A disabled domain is ignored completely: no matching, no output. The CLI reference lists the settings commands.
Ways load from three roots. When the same way id (its path under the root) exists in more than one, the higher root wins (ADR-143):
| Root | Path | Holds |
|---|---|---|
| Project | $PROJECT/.claude/ways/{domain}/{wayname}/ | Ways for one repository, checked in with it |
| User | $XDG_CONFIG_HOME/agent-ways/ways/{domain}/{wayname}/ | Your own ways, and overrides of shipped ways; updates never touch it |
| Core | the app's hooks/ways/, projected to ~/.claude/hooks/ways/ | The shipped corpus; change it in a fork, since a local edit can block ways manage update |
Each way is a {wayname}.md file with YAML frontmatter:
---
description: semantic text # embedding semantic matching (preferred)
vocabulary: domain keywords # space-separated terms augmenting the embedding
pattern: commit|push # regex on user prompts (supplementary)
commands: git\ commit # regex on bash commands
files: \.env$ # regex on file paths
tool_name: ^ExitPlanMode$ # regex on the tool name (tool_event: [PreToolUse, PostToolUse])
macro: prepend # dynamic context via macro.sh
scope: agent, subagent # injection scope
---
Matching has two independent lanes. A way fires when the semantic probability g(s) clears the global threshold τ_s, or when a pattern:/commands:/files: regex matches and g(s) clears the lower keyword floor τ_k. The keyword lane is floor-gated — a regex hit can't drag in an unrelated prompt — except it fails open when no calibration is loaded, and pattern_strict: true bypasses the gate by design. See the engine reference for the exact fire rule.
Project macros are disabled by default. Trust a project with echo "/path/to/project" >> ~/.claude/trusted-project-macros.
For the full authoring guide: extending.md | For matching strategy: matching.md | For macros: macros.md
After creating or tuning a way, verify it matches what you expect — and doesn't match what it shouldn't.
# Score a way against sample prompts (inside Claude Code)
/ways-tests score security "how do i hash passwords with bcrypt"
# Rank all ways against a prompt
/ways-tests score-all "write some unit tests for this module"
# Validate frontmatter
ways author lint --global
# Vocabulary gap analysis
ways author suggest ~/.claude/hooks/ways/softwaredev/code/security/security.md
# How a prompt matches under the live matcher (ADR-160)
ways author match "pin lockfile versions"
# Sibling vocabulary overlap (Jaccard)
ways author tree softwaredev/code/supplychain/depscan --jaccard
# Way-vs-way embedding similarity
ways author siblings softwaredev/code/supplychain/depscan/node
# Session simulation tests (Rust integration tests)
make test-sim
# Interactive: full hook pipeline with subagent injection
# Start a fresh session, then: read and run tests/way-activation-test.md
Other test tools: scripts/doc-graph.sh --stats checks documentation link integrity; ways-audit lint validates provenance metadata. Full test guide: tests/README.md.
The shipped ways cover commits, security, testing, debugging, dependencies, architecture, documentation and more, across eleven domains: collaboration, data, documentation, ea, evaluative, itops, meta, research, softwaredev, workstation and writing. ways status prints the current count. The live index is generated at session start. Replace these entirely if your domain isn't software dev.
Also included:
aaronsb/agent-waysClaude Code ships two official features for injecting guidance: Rules (.claude/rules/*.md) and Skills (~/.claude/skills/). Ways solve problems that neither can.
The problem has a name in principal–agent theory: preference uncertainty. An agent that doesn't know its principal's norms has only two safe strategies — ask constantly, or hedge exhaustively. Remove the ways system and agents of every model tier revert to exactly that. Rules and skills each supply some norms; ways supply them situated — at the moment of action, wherever in the file tree that action happens.
Rules and ways both inject guidance conditionally — but their disclosure models are fundamentally different:
paths: src/api/**). The project's directory tree is the disclosure taxonomy. This works when concerns map cleanly to directoriehooks/register.tsx 1126 lines1// attend's agent-facing driver in Claude Code (ADR-406).
2//
3// Dormant is plain Claude Code: one tool, `attend_listen`, and no polling,
4// delivery or row of this module's. A session is active from session start
5// when its project resolves `mods.attend.listening: active` through the ways
6// config, or from the agent's attend_listen call; it stays active until
7// Claude Code exits. While active the mod polls attend, delivers peer
8// messages as framed turns, serves the send/reply/join/peers tools, draws one
9// status row and drives keepwarm.
10//
11// The keepalive policy (ADR-414) runs in every interactive session with the
12// mod, dormant ones included, while autocompact is off: attend judges, and
13// this module supplies the operator's prompts and the autocompact gate,
14// submits the keepalive and wrap turns, and routes the wrap's reply. A
15// dormant session polls nothing, delivers nothing and joins nothing for it:
16// one timer, set again at each main-loop turn's end. Where the policy
17// applies, it drives every cache wake, ADR-182's armed windows included.
18//
19// Every message travels through attend's signal store by the attend CLI, as
20// an argv array with no shell. The mod never uses $.session.send.
21
22import { atom, read, update } from 'claude-code'
23import type { EngineInterface, ProcessRunResult, PromptSubmitInput, PromptSubmitResult, Register, Timer } from 'claude-code'
24
25import type { AttendStatus, KeepaliveRow, MoveRecord } from '../types/index.d.ts'
26import { adoptMove, claimGaveUp, claimMove, readOutcome, recordMove, recordOf } from './move.ts'
27import type { Move } from './move.ts'
28import {
29 ACTIVE_TOOLS,
30 DEFAULT_CONFIG,
31 configNotice,
32 DORMANT_REFUSAL,
33 OPERATOR_ORIGINS,
34 listenResult,
35 toolResult,
36 LISTEN_TOOL,
37 BEAT_ARGV,
38 PLAIN_BEAT_ARGV,
39 DRAIN_ARGV,
40 KEEPWARM_CHECK_ARGV,
41 LISTEN_OFF_ARGV,
42 LISTEN_ON_ARGV,
43 PEERS_ARGV,
44 UNREAD_ARGV,
45 WAKE_DRAIN_ARGV,
46 configArgv,
47 formatMessage,
48 frameInbound,
49 compactFocus,
50 firstCheckMs,
51 isContextReset,
52 gateFrom,
53 gateIsFresh,
54 isWrapTurn,
55 maySubmit,
56 planCheck,
57 refusalDetail,
58 resetArgv,
59 saveArgv,
60 retryAtMs,
61 rowAfterPrompt,
62 rowAfterTurnEnd,
63 rowRefused,
64 rowText,
65 serialize,
66 wrapPlan,
67 isFullPreamble,
68 joinArgv,
69 keepaliveApplies,
70 keepaliveRowOf,
71 parseDecision,
72 policyArgv,
73 wrappedArgv,
74 keepwarmLine,
75 oneLine,
76 parseConfig,
77 parseDrain,
78 parsePeerCount,
79 parseUnread,
80 peerLines,
81 pollInterval,
82 replyArgv,
83 sendArgv,
84 shortId,
85} from './lib.ts'
86import type { Decision, Gate, Keepalive, Listed, Mod, ModConfig, WrapOutcome, WrapRoute } from './lib.ts'
87
88
89type $ = EngineInterface
90
91const DEFAULTS = {
92 mode: 'dormant',
93 listening: null,
94 peers: 0,
95 unread: 0,
96 channels: [],
97 deliveries: 0,
98 afterCompaction: false,
99 turnsSinceFull: 0,
100 heldNote: null,
101 cacheLapsed: false,
102 keepalive: null,
103 move: null,
104} satisfies AttendStatus
105
106const status = atom({ plugin: 'attend', key: 'status' } as const, DEFAULTS)
107
108// Tools are listed as mcp__attend__<name>; the matchers below spell them out,
109// so the validator can read them.
110const PLUGIN = 'attend'
111
112
113// A drain that finds messages waits this long and drains again, so a burst
114// arrives as one turn.
115const BATCH_MS = 2_000
116// The peer count and the keepwarm check run at most this often.
117const PEERS_EVERY_MS = 30_000
118const KEEPWARM_EVERY_MS = 60_000
119// The heartbeat is touched this often, a third of attend's 90 s liveness
120// grace (ADR-129), during a turn and at the slow interval alike.
121const BEAT_EVERY_MS = 30_000
122// Polls that retry a batch whose submit failed before it is let go.
123const SUBMIT_TRIES = 3
124// The $.store key naming the sessions that listened where the project's
125// config would not start them listening, newest last, so a resume of one
126// comes back listening (ADR-411).
127const LISTENED = 'listened'
128const LISTENED_KEPT = 50
129// A /clear or a /resume tells attend the id that goes on after this long.
130const RELISTEN_MS = 1_000
131// The keepalive policy: a gate read as on or unknown is read again after
132// this long, one read as off before every check, since a turn may follow
133// it; the check reads the transcript and the settings through ways; the
134// first check waits until session start has set the session listening or
135// dormant; a check that could not run asks again.
136const POLICY_TIMEOUT_MS = 30_000
137const POLICY_START_MS = 1_000
138// A submitted wrap whose turn has not started after this long, or has not
139// answered by the time the cache lapses, is reported unfinished.
140const WRAP_START_MS = 10 * 60_000
141const WRAP_LAPSE_MS = 60 * 60_000
142
143// agent-ways theme (tools/agent-theme/themes/agent-ways.theme).
144const SUBTLE = '#3a3a3c'
145const FG = '#d0d0d0'
146
147async function readStatus($: $): Promise<AttendStatus> {
148 return { ...DEFAULTS, ...(await read($, status)) }
149}
150
151async function updateStatus($: $, f: (s: AttendStatus) => AttendStatus) {
152 await update($, status, s => f({ ...DEFAULTS, ...s }))
153}
154
155/** One CLI call; a command that cannot start reads as exit 127. */
156async function run($: $, argv: readonly string[], timeoutMs = 15_000, stdin?: string): Promise<ProcessRunResult> {
157 try {
158 return await $.process.run(argv, stdin === undefined ? { timeoutMs } : { timeoutMs, stdin })
159 } catch (err) {
160 return { exitCode: 127, stdout: '', stderr: String(err), isStdoutTruncated: false, isStderrTruncated: false }
161 }
162}
163
164/** Whether this process has said that ways could not answer for its
165 * settings: said once, not at every read. */
166let configNoticeShown = false
167
168async function readConfig($: $, cwd: string): Promise<ModConfig> {
169 const r = await run($, configArgv(cwd), 10_000)
170 if (r.exitCode === 0) return parseConfig(r.stdout)
171 const notice = configNotice(r.exitCode)
172 if (notice && !configNoticeShown) {
173 configNoticeShown = true
174 await $.ui.toast(notice)
175 }
176 return { ...DEFAULT_CONFIG }
177}
178
179async function registerListen($: $) {
180 await $.tool.register(LISTEN_TOOL)
181}
182
183/** The tools of an active session. Registering one again with the same
184 * spec changes nothing, so every path that finds the session active
185 * registers them, a reloaded module's session.start included. */
186async function registerActiveTools($: $) {
187 for (const tool of ACTIVE_TOOLS) await $.tool.register(tool)
188}
189
190/** Tells attend this session is listening, with the mod as its host; the
191 * next drain applies the cold-start rule: what was addressed to the project
192 * since this Claude Code process started arrives, and what `#open` and the
193 * channels carry from now on. */
194async function listenOn($: $): Promise<ProcessRunResult> {
195 const r = await run($, LISTEN_ON_ARGV)
196 await updateStatus($, s => ({ ...s, listening: r.exitCode === 0 }))
197 return r
198}
199
200/** The sessions that listened, newest last, as $.store holds them. */
201async function readListened($: $): Promise<string[]> {
202 const v = await $.store.get(LISTENED)
203 return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []
204}
205
206/** Whether the project's config starts this session listening on its own,
207 * so a resume of it needs no record. */
208function startsActive(mod: Mod): boolean {
209 return mod.config.listening === 'active' && mod.canPoll
210}
211
212/** Records that session `id` listened, keeping the newest LISTENED_KEPT,
213 * where the config would not reproduce it and the record does not list it
214 * already. $.store has no versioned write, so two processes recording at
215 * once can lose one id; writing this rarely keeps that window small. The
216 * record serves a later resume and never this session: a store that fails
217 * is logged and the session goes on. */
218async function rememberListening($: $, mod: Mod, id: string) {
219 if (startsActive(mod)) return
220 try {
221 const ids = await readListened($)
222 if (ids.includes(id)) return
223 ids.push(id)
224 await $.store.set(LISTENED, ids.slice(-LISTENED_KEPT))
225 } catch (err) {
226 $.ui.log(`attend: could not record this session for a resume: ${String(err)}`)
227 }
228}
229
230/** Makes session `id` active for the rest of the process: listening, the
231 * poll, and the record a resume reads; the caller has registered the
232 * tools. Idempotent. Returns attend's answer to `listen on`. */
233async function activate($: $, mod: Mod, id: string): Promise<ProcessRunResult> {
234 mod.active = true
235 let r: ProcessRunResult
236 try {
237 mod.config = await readConfig($, mod.cwd)
238 mod.canPoll = mod.canPoll || mod.config.headlessPoll
239 // The config read again may change whether the policy applies: one judge
240 // per ledger, the policy's timer or the poll's plain check.
241 const didApply = mod.ka.applies
242 mod.ka.applies = keepaliveApplies(mod.config, mod.isInteractive)
243 if (mod.ka.applies && !didApply) await armKeepalive($, mod, (await $.clock.now()) + POLICY_START_MS)
244 if (!mod.ka.applies) mod.ka.timer?.cancel()
245 mod.lastActivityMs = await $.clock.now()
246 await updateStatus($, s => ({ ...s, mode: 'active' as const }))
247 r = await listenOn($)
248 } finally {
249 mod.isRelistening = false
250 }
251 await rememberListening($, mod, id)
252 if (mod.canPoll) {
253 startTicker($, mod)
254 $.clock.after(0, () => void tick($, mod, true))
255 }
256 return r
257}
258
259// ── following a /clear or an in-session /resume (move.ts) ──────────────
260//
261// The watch runs here, in the hooks module's own file, since the engine
262// follows `$` only into functions declared in it; move.ts holds the state
263// and its rules. watchMove runs on session.start's `$` (mod.startWatch), as
264// session.end's bound aborts the waits of its own.
265
266/** Starts the watch of the module's move: the hold at once, so a reload
267 * finds the move, then the reads on the backoff. One timer at a time. */
268function watchMove($: $, mod: Mod) {
269 const m = mod.move
270 if (!m) return
271 m.timer?.cancel()
272 m.timer = $.clock.after(0, () => void holdFirst($, mod, m))
273}
274
275async function holdFirst($: $, mod: Mod, m: Move) {
276 if (mod.move !== m) return
277 try {
278 await holdMove($, mod, recordOf(m))
279 } catch {
280 // Each read writes the hold again.
281 }
282 if (mod.move !== m) return
283 m.timer = $.clock.after(m.delayMs, () => void stepMove($, mod, m))
284}
285
286/** One read of the id: settle on an id that did not end, otherwise wait
287 * longer (readOutcome). A read that fails counts as no change and is
288 * logged once; past the give-up the session stays as the hold left it. */
289async function stepMove($: $, mod: Mod, m: Move) {
290 if (mod.move !== m) return
291 m.timer = undefined
292 let id: string | undefined
293 try {
294 await holdMove($, mod, recordOf(m))
295 id = await $.session.id()
296 } catch (err) {
297 m.failures += 1
298 if (m.failures === 1) $.ui.log(`attend: could not read the session id after a /clear or a /resume: ${String(err)}`)
299 }
300 const next = readOutcome(mod, m, id)
301 if (next.kind === 'settle' && id !== undefined) return void (await finishMove($, mod, id, next.record))
302 if (next.kind === 'give-up') {
303 const last = next.record.ended[next.record.ended.length - 1] ?? ''
304 $.ui.log(`attend: the session id still reads ${last} ${Math.round(m.waitedMs / 1000)} s after a /${next.record.reason}; the next turn under another id records it`)
305 try {
306 await releaseMove($)
307 } catch {
308 // The record in $.state goes with the next settle, or the process.
309 }
310 return
311 }
312 if (next.kind === 'wait') m.timer = $.clock.after(next.delayMs, () => void stepMove($, mod, m))
313}
314
315/** A main-loop turn: settles the move, or one the watch gave up on, when
316 * `$.session.id()` names an id that did not end; otherwise the watch goes
317 * on. A turn under the new id so does not wait for the next read. */
318async function settleIfMoved($: $, mod: Mod) {
319 try {
320 const id = await $.session.id()
321 const m = mod.move
322 if (m) {
323 const record = claimMove(mod, m, id)
324 if (record) await finishMove($, mod, id, record)
325 return
326 }
327 const given = claimGaveUp(mod, id)
328 if (given) await settleMove($, mod, id, given)
329 } catch (err) {
330 $.ui.log(`attend: could not read the session id after a /clear or a /resume: ${String(err)}`)
331 }
332}
333
334async function finishMove($: $, mod: Mod, id: string, record: MoveRecord) {
335 try {
336 await settleMove($, mod, id, record)
337 } finally {
338 await releaseMove($)
339 }
340}
341
342async function releaseMove($: $) {
343 await updateStatus($, s => ({ ...s, move: null }))
344}
345
346/** Before each read of the id: the move stays in $.state, which Claude Code
347 * empties after session.end, so a reload takes the watch up; a session
348 * that was listening keeps its mode there, so a reload finds it active, and
349 * attend is told once that the session listens, whatever id it sees now.
350 * The next delivery carries the preamble: the model's context changed as
351 * at a compaction. */
352async function holdMove($: $, mod: Mod, m: MoveRecord) {
353 const s = await readStatus($)
354 const isKept = s.move !== null && s.move.ended.join(' ') === m.ended.join(' ')
355 if (isKept && (!m.wasOn || isActive(s))) return
356 await updateStatus($, t => ({
357 ...t,
358 move: m,
359 ...(m.wasOn ? { mode: 'active' as const, afterCompaction: true, turnsSinceFull: 0, heldNote: mod.heldNote ?? null } : {}),
360 }))
361 if (m.wasOn && !mod.isMoveListened) {
362 mod.isMoveListened = true
363 await listenOn($)
364 }
365}
366
367/** The session goes on under `id`, which is none of the ids that ended. An
368 * active session, or a /resume to a session that listened, records the id
369 * and tells attend the id is listening; the poll holds its drain until
370 * then. */
371async function settleMove($: $, mod: Mod, id: string, m: MoveRecord) {
372 try {
373 const goesOn = m.wasOn || mod.active || (m.reason === 'resume' && (await readListened($)).includes(id))
374 if (!goesOn) return
375 mod.isRelistening = true
376 await updateStatus($, s => ({ ...s, mode: 'active' as const, afterCompaction: true, turnsSinceFull: 0, heldNote: mod.heldNote ?? null }))
377 await rememberListening($, mod, id)
378 if (mod.active) {
379 $.clock.after(RELISTEN_MS, () => void listenOn($).finally(() => (mod.isRelistening = false)))
380 } else {
381 mod.active = true
382 await registerActiveTools($)
383 $.clock.after(RELISTEN_MS, () => void activate($, mod, id))
384 }
385 } catch (err) {
386 // No timer will lower the guard, so the poll would stay held.
387 mod.isRelistening = false
388 $.ui.log(`attend: could not carry listening to the session that goes on: ${String(err)}`)
389 }
390}
391
392/** Whether the context fill reads as absent, as it does after a compaction
393 * until the next response; a /compact that failed or was cancelled leaves
394 * it reported. Where usage cannot be read, it counts as cleared: an extra
395 * preamble costs one line. */
396async function isFillCleared($: $): Promise<boolean> {
397 try {
398 return (await $.session.usage()).context.tokens === undefined
399 } catch {
400 return true
401 }
402}
403
404/** The next delivery shows the preamble in full. */
405async function markCompacted($: $) {
406 await updateStatus($, s => ({ ...s, afterCompaction: true }))
407}
408
409function startTicker($: $, mod: Mod) {
410 mod.ticker?.cancel()
411 const every = Math.max(1, Math.min(mod.config.pollSeconds, 5)) * 1000
412 mod.ticker = $.clock.every(every, () => void tick($, mod, false))
413}
414
415/** One beat of the poll: touch the heartbeat, drain while idle, refresh the
416 * row, run the keepwarm check. `force` skips the poll's interval
417 * (activation, a turn's end). The heartbeat keeps its own interval, so a
418 * turn or a slow poll longer than attend's grace does not leave the session
419 * looking gone. */
420async function tick($: $, mod: Mod, force: boolean) {
421 if (mod.isTicking) return
422 if (!(await isOn($, mod))) return
423 mod.isTicking = true
424 try {
425 const now = await $.clock.now()
426 if (now - mod.lastBeatMs >= BEAT_EVERY_MS) {
427 mod.lastBeatMs = now
428 if (mod.isBeatPlain) {
429 await run($, PLAIN_BEAT_ARGV)
430 } else if ((await run($, BEAT_ARGV)).exitCode === 2) {
431 // An older attend: a usage error on --mod. Beat without it from now on.
432 mod.isBeatPlain = true
433 await run($, PLAIN_BEAT_ARGV)
434 }
435 }
436 const isTurnRunning = mod.running.size > 0
437 const interval = pollInterval(mod.config, now - mod.lastActivityMs, isTurnRunning)
438 if (!force && now - mod.lastPollMs < interval) return
439 mod.lastPollMs = now
440 if (!isTurnRunning && !mod.isRelistening) await poll($, mod)
441 await refreshUnread($, mod)
442 if (force || now - mod.lastPeersMs >= PEERS_EVERY_MS) await refreshPeers($, mod)
443 // Where the keepalive policy applies, its own timer drives every wake.
444 const isPlain = !mod.ka.applies
445 if (isPlain && mod.config.keepwarm === 'on' && mod.running.size === 0 && now - mod.lastKeepwarmMs >= KEEPWARM_EVERY_MS) {
446 mod.lastKeepwarmMs = now
447 await keepwarm($)
448 }
449 } finally {
450 mod.isTicking = false
451 }
452}
453
454/** One wake drain; on messages, a plain drain after BATCH_MS, then one
455 * prompt for the batch. The wake drain delivers only once something pending
456 * would wake the session (a message addressed to it, or a post in one of
457 * its named channels), and then delivers all that is pending. A
458 * turn is submitted only when the drain delivered at least one message: the
459 * cold start's held-back note and the session's name are fields of the
460 * drain's document, never a message. The note is kept for the operator's
461 * next prompt.
462 *
463 * A session its config started listening polls from its start like any
464 * other. attend's cold start holds back what was sent before the session
465 * began (ADR-404 D3b), so what wakes a new session is mail sent to it
466 * since, and a session with no turn yet has no cache to lapse.
467 *
468 * The drain marks what it delivers read before the prompt is submitted, so
469 * the batch waits in `mod.pending` until a submit takes it. A submit that
470 * fails, or that a hook drops, leaves the batch there and the next poll
471 * tries it again before draining more, up to SUBMIT_TRIES times. */
472async function poll($: $, mod: Mod) {
473 if (mod.isPolling || mod.isPendingCold) return
474 mod.isPolling = true
475 try {
476 if (mod.pending.length === 0) {
477 // Only what is addressed to the session, or posted in one of its
478 // named channels, starts a turn; other #open posts wait for its next
479 // one (ADR-406 item 2).
480 const first = parseDrain((await run($, WAKE_DRAIN_ARGV)).stdout)
481 if (!first) return
482 // Listening turned off elsewhere (attend listen off, a private scene),
483 // or an identity attend cannot resolve: the row says so.
484 const listening = first.status === 'drained'
485 const was = await readStatus($)
486 if (was.listening !== listening || was.cacheLapsed !== first.cacheLapsed) {
487 await updateStatus($, s => ({ ...s, listening, cacheLapsed: first.cacheLapsed }))
488 }
489 if (first.note) await setHeldNote($, mod, first.note)
490 if (first.messages.length === 0) return
491 const msgs = [...first.messages]
492 await updateStatus($, s => ({ ...s, unread: Math.max(s.unread, msgs.length) }))
493 await new Promise<void>(resolve => $.clock.after(BATCH_MS, resolve))
494 const second = parseDrain((await run($, DRAIN_ARGV)).stdout)
495 if (second) msgs.push(...second.messages)
496 mod.pending = msgs
497 mod.submitTries = 0
498 }
499 if (await deliver($, mod, mod.pending)) {
500 mod.pending = []
501 } else if (++mod.submitTries >= SUBMIT_TRIES) {
502 // Read by attend and refused by the session: they stay readable with
503 // attend message inbox, and the poll goes on to new messages.
504 await $.ui.toast(`attend: ${mod.pending.length} message(s) could not be delivered; attend message inbox lists them`)
505 mod.pending = []
506 }
507 } finally {
508 mod.isPolling = false
509 }
510}
511
512/** Submits one framed batch, which starts a turn in an idle session.
513 * Resolves whether the prompt entered; the preamble counters move only
514 * when it did. */
515async function deliver($: $, mod: Mod, msgs: readonly Listed[]): Promise<boolean> {
516 // A check in flight submits nothing behind this turn.
517 mod.ka.epoch += 1
518 mod.lastActivityMs = await $.clock.now()
519 for (const m of msgs) {
520 mod.ids.set(shortId(m.id), m.id)
521 if (m.re) mod.ids.set(shortId(m.re), m.re)
522 }
523 const s = await readStatus($)
524 const full = isFullPreamble(s.deliveries, s.afterCompaction, s.turnsSinceFull, mod.config.preambleEveryTurns)
525 const entered = await $.prompt
526 .submit({ text: frameInbound(msgs.map(formatMessage), full), asUser: true })
527 .then(r => r.drop === undefined)
528 .catch(() => false)
529 if (!entered) return false
530 await updateStatus($, t => ({
531 ...t,
532 deliveries: t.deliveries + 1,
533 afterCompaction: false,
534 turnsSinceFull: full ? 0 : t.turnsSinceFull,
535 }))
536 return true
537}
538
539/** Keeps the held-back note, or clears it, in the module and in $.state. */
540async function setHeldNote($: $, mod: Mod, note: string | undefined) {
541 mod.heldNote = note
542 await updateStatus($, s => ({ ...s, heldNote: note ?? null }))
543}
544
545/** The operator's prompt while a message waits on a lapsed cache, or while
546 * a held-back note waits: one drain, and what it delivered rides `e` as
547 * context, the note with it, rather than as a turn of its own. The
548 * operator sees what went, in the transcript under their prompt
549 * ({@link showWithPrompt}). A prompt that does not enter leaves the
550 * messages in `mod.pending`, and the note in `mod.heldNote`: taken on a
551 * lapsed cache they wait for the operator's next prompt, otherwise the poll
552 * submits the messages as it does a batch whose submit failed. */
553async function enterWithPending($: $, mod: Mod, e: PromptSubmitInput, next: (e: PromptSubmitInput) => Promise<PromptSubmitResult>, isCold: boolean) {
554 // A batch an earlier cold prompt failed to carry goes first.
555 const carried = mod.isPendingCold ? mod.pending : []
556 const d = parseDrain((await run($, DRAIN_ARGV)).stdout)
557 if (!d && carried.length === 0) return next(e)
558 if (d) {
559 const listening = d.status === 'drained'
560 if ((await readStatus($)).listening !== listening) await updateStatus($, s => ({ ...s, listening }))
561 }
562 const msgs = [...carried, ...(d?.messages ?? [])]
563 if (carried.length > 0) {
564 mod.pending = []
565 mod.isPendingCold = false
566 }
567 for (const m of msgs) {
568 mod.ids.set(shortId(m.id), m.id)
569 if (m.re) mod.ids.set(shortId(m.re), m.re)
570 }
571 const heldNote = d?.note ?? mod.heldNote
572 await setHeldNote($, mod, undefined)
573 const note = heldNote ? `attend: ${oneLine(heldNote)}` : undefined
574 const lines = msgs.map(formatMessage)
575 const block = msgs.length > 0 ? frameInbound(lines, true) : undefined
576 const attached = [block, note].filter((x): x is string => x !== undefined)
577 if (attached.length === 0) return next(e)
578 // Read by attend and not entered: they wait in `mod.pending`. Taken on a
579 // lapsed cache, they wait for the operator's next prompt, with the row
580 // still saying so; otherwise the poll submits them.
581 const keep = async () => {
582 await setHeldNote($, mod, heldNote)
583 if (msgs.length === 0) return
584 mod.pending = [...msgs]
585 mod.submitTries = 0
586 mod.isPendingCold = isCold
587 if (isCold) await updateStatus($, s => ({ ...s, cacheLapsed: true, unread: Math.max(s.unread, msgs.length) }))
588 }
589 let r: PromptSubmitResult
590 try {
591 r = await next({ ...e, context: [...(e.context ?? []), attached.join('\n')] })
592 } catch (err) {
593 await keep()
594 throw err
595 }
596 if (r.drop !== undefined) {
597 await keep()
598 return r
599 }
600 if (msgs.length > 0) await updateStatus($, t => ({ ...t, deliveries: t.deliveries + 1, afterCompaction: false, turnsSinceFull: 0 }))
601 showWithPrompt($, lines, note)
602 return r
603}
604
605/** What rode the operator's prompt as context, which the engine never draws:
606 * a line saying so, then one dim transcript line per message as a
607 * delivery's row draws them, and the held-back note. The model reads none
608 * of it. */
609function showWithPrompt($: $, lines: readonly string[], note: string | undefined) {
610 if (lines.length > 0) {
611 $.ui.log(`attend: ${lines.length} peer message(s) went to Claude with your prompt`)
612 for (const l of lines) $.ui.log(oneLine(l))
613 }
614 if (note) $.ui.log(note)
615}
616
617
618async function refreshUnread($: $, mod: Mod) {
619 const u = parseUnread((await run($, UNREAD_ARGV)).stdout)
620 if (!u) return
621 await updateStatus($, s => ({ ...s, unread: u.unread, channels: [...new Set([...u.channels, ...mod.joined])] }))
622}
623
624async function refreshPeers($: $, mod: Mod) {
625 mod.lastPeersMs = await $.clock.now()
626 const r = await run($, PEERS_ARGV)
627 if (r.exitCode === 0) await updateStatus($, s => ({ ...s, peers: parsePeerCount(r.stdout) }))
628}
629
630/** ADR-182's judgment, run by attend; a `keepwarm:` line becomes a turn. */
631async function keepwarm($: $) {
632 const line = keepwarmLine((await run($, KEEPWARM_CHECK_ARGV, 30_000)).stdout)
633 if (line) await $.prompt.submit({ text: line })
634}
635
636/** Whether this session is active. The module's own flag answers too, and
637 * puts the mode back in $.state should it be missing there. */
638async function isOn($: $, mod: Mod): Promise<boolean> {
639 if (isActive(await readStatus($))) return true
640 if (!mod.active) return false
641 await updateStatus($, s => ({ ...s, mode: 'active' as const }))
642 return true
643}
644
645function isActive(s: AttendStatus): boolean {
646 return s.mode === 'active'
647}
648
649function input<T>(e: unknown): Partial<T> {
650 return e as Partial<T>
651}
652
653// ── the keepalive policy (ADR-414) ──────────────────────────────────────
654
655async function setKeepaliveRow($: $, f: (k: KeepaliveRow | null) => KeepaliveRow | null) {
656 await updateStatus($, s => ({ ...s, keepalive: f(s.keepalive) }))
657}
658
659/** The autocompact gate (ADR-414 item 2): the usage breakdown, estimated
660 * locally with no request, else `autoCompactEnabled` in the merged
661 * settings, else unknown, which counts as on. `fresh` reads it whatever
662 * was kept, as before a submit. A gate that first reads off sends the
663 * operator's prompt held while it did not. */
664async function readGate($: $, ka: Keepalive, fresh = false): Promise<Gate> {
665 const now = await $.clock.now()
666 if (!fresh && gateIsFresh(ka.gate, ka.gateAtMs, now)) return ka.gate
667 let usage: unknown
668 try {
669 usage = await $.session.usage({ breakdown: 'summary' })
670 } catch {
671 usage = undefined
672 }
673 let settings: unknown
674 if (gateFrom(usage, undefined) === 'unknown') {
675 try {
676 settings = await $.settings.read()
677 } catch {
678 settings = undefined
679 }
680 }
681 ka.gate = gateFrom(usage, settings)
682 ka.gateAtMs = now
683 if (ka.gate === 'off' && ka.heldPromptMs !== undefined) {
684 const at = ka.heldPromptMs
685 ka.heldPromptMs = undefined
686 await run($, resetArgv(at / 1000))
687 }
688 return ka.gate
689}
690
691/** The policy's timer: a check at `atMs`. */
692async function armKeepalive($: $, mod: Mod, atMs: number) {
693 mod.ka.timer?.cancel()
694 const wait = Math.max(0, atMs - (await $.clock.now()))
695 mod.ka.timer = $.clock.after(wait, () => {
696 mod.ka.timer = undefined
697 void checkKeepalive($, mod)
698 }) as unknown as Timer
699}
700
701/** One check: read the gate, ask attend, submit what it returns, and set the
702 * timer for when attend says to ask again. Nothing is due while a main-loop
703 * turn runs, and a prompt or a turn that starts while attend judges (the
704 * epoch moves) cancels the submit. A dormant session with autocompact on
705 * stays plain Claude Code and asks nothing. */
706async function checkKeepalive($: $, mod: Mod) {
707 const ka = mod.ka
708 if (!ka.applies || mod.running.size > 0 || mod.config.keepwarm !== 'on') return
709 const epoch = ka.epoch
710 await serialize(ka, async () => {
711 const gate = await readGate($, ka)
712 const isListening = await isOn($, mod)
713 if (!isListening && gate !== 'off') return
714 const r = await run($, policyArgv(gate), POLICY_TIMEOUT_MS)
715 const d: Decision | undefined = r.exitCode === 0 ? parseDecision(r.stdout) : undefined
716 const plan = d ? planCheck(d, isListening) : undefined
717 if (!d || !plan || plan.retry) {
718 const at = retryAtMs(await $.clock.now(), isListening, gate, ka.retries)
719 ka.retries += 1
720 if (at !== null) await armKeepalive($, mod, at)
721 return
722 }
723 ka.retries = 0
724 await setKeepaliveRow($, k => keepaliveRowOf(d, k))
725 if (plan.submit) {
726 const isPolicy = d.policy
727 const gateNow = isPolicy ? await readGate($, ka, true) : gate
728 if (!maySubmit({ epochThen: epoch, epochNow: ka.epoch, running: mod.running.size, isPolicy, gate: gateNow })) {
729 if (plan.submit.kind === 'wrap') await run($, wrappedArgv('unfinished', 'a turn started before the wrap went in'))
730 return
731 }
732 const { text, route } = plan.submit
733 if (route) {
734 const wrap = { route, text, turnId: undefined, reply: undefined, sawTurn: false }
735 ka.wrap = wrap
736 // A wrap whose turn never starts, or never answers before the cache
737 // lapses, is reported rather than left pending.
738 $.clock.after(WRAP_START_MS, () => {
739 if (ka.wrap === wrap && wrap.turnId === undefined) {
740 void reportUnrouted($, ka, wrap.sawTurn ? 'the wrap\'s turn was not recognised' : 'the wrap\'s turn never started')
741 }
742 })
743 $.clock.after(WRAP_LAPSE_MS, () => {
744 if (ka.wrap === wrap) void reportUnrouted($, ka, 'the wrap did not answer before the cache lapsed')
745 })
746 }
747 const isEntered = await $.prompt
748 .submit({ text })
749 .then(x => x.drop === undefined)
750 .catch(() => false)
751 if (!isEntered && route) {
752 ka.wrap = undefined
753 await run($, wrappedArgv('unfinished', 'the wrap prompt did not enter'))
754 }
755 }
756 if (plan.armAtMs !== null) await armKeepalive($, mod, plan.armAtMs)
757 })
758}
759
760/** The operator is present: the count starts again, and a sent wrap and a
761 * stop are cleared (ADR-414 item 4). attend hears of it only while the
762 * gate last read off; otherwise the prompt is held, and sent when the gate
763 * first reads off, so a session with autocompact on runs nothing. */
764async function keepaliveOperator($: $, mod: Mod) {
765 const ka = mod.ka
766 if (!ka.applies) return
767 ka.epoch += 1
768 // Never awaited: the prompt must not wait on the chain a check holds.
769 if (ka.wrap) void reportUnrouted($, ka, 'the operator prompted before the wrap answered')
770 const now = await $.clock.now()
771 if ((await readGate($, ka, true)) === 'off') {
772 ka.heldPromptMs = undefined
773 void serialize(ka, () => run($, resetArgv(now / 1000)))
774 } else {
775 ka.heldPromptMs = now
776 }
777 await setKeepaliveRow($, rowAfterPrompt)
778}
779
780/** A main-loop turn ended, which restarts the clock: the timer is set for
781 * the first point a check could be due, and attend names the due point
782 * there. The wrap's turn routes its reply first. */
783async function keepaliveTurnEnded($: $, mod: Mod, e: { turnId: string; reason: string; answer?: string }) {
784 if (!mod.ka.applies) return
785 await routeWrap($, mod.ka, e.turnId, e.reason, e.answer ?? '')
786 if (mod.running.size > 0) return
787 mod.ka.retries = 0
788 const at = (await $.clock.now()) + firstCheckMs(mod.config)
789 await armKeepalive($, mod, at)
790 await setKeepaliveRow($, k => rowAfterTurnEnd(k, at))
791}
792
793/** The wrap's turn ended: its final reply goes where `wrap` says, and attend
794 * records where it went (ADR-414 item 6). Only the turn the wrap's own
795 * text started is routed; a turn that ended other than with an answer is
796 * written nowhere. */
797async function routeWrap($: $, ka: Keepalive, turnId: string, reason: string, answer: string) {
798 const w = ka.wrap
799 if (!w || w.turnId === undefined || w.turnId !== turnId) return
800 ka.wrap = undefined
801 // The wrap's own answer, from its first ending step, which stands even
802 // when a Stop-hook continuation then ends aborted or in error; the
803 // turn's final answer only where no step was seen.
804 const reply = w.reply ?? answer
805 const report = (o: WrapOutcome, detail = '') => serialize(ka, () => run($, wrappedArgv(o, detail)))
806 const plan = wrapPlan(w.route, w.reply !== undefined ? 'answer' : reason, reply)
807 if (plan.kind === 'unfinished') return void (await report('unfinished', plan.detail))
808 if (plan.kind === 'transcript') await report('transcript')
809 // attend writes the file and records the outcome, or why it could not.
810 if (plan.kind === 'file') await serialize(ka, () => run($, plan.argv, undefined, reply))
811 if (plan.kind === 'send') {
812 const r = await run($, plan.argv)
813 if (r.exitCode === 0) {
814 await report('sent', w.route.to)
815 } else {
816 // Refused (no live session by that name, a channel it cannot post
817 // to) or timed out: the reply goes to the file instead.
818 const detail = refusalDetail(w.route.to, r)
819 if (w.route.file === '') await report('refused', `${detail}; no safe wrap file to keep it in`)
820 else await serialize(ka, () => run($, saveArgv('refused', detail, w.route.file), undefined, reply))
821 await setKeepaliveRow($, rowRefused)
822 }
823 }
824 if (w.route.after === 'compact') {
825 const instructions = compactFocus(reply)
826 // Between turns: a compaction rejects while a turn runs.
827 $.clock.after(1_000, () => {
828 void $.session
829 .compact({ instructions })
830 .then(r => (r.skip === undefined ? markCompacted($) : undefined))
831 .catch(err => $.ui.log(`attend: the compaction after the wrap failed: ${String(err)}`))
832 })
833 }
834}
835
836/** A wrap that went in and was never routed: its turn never started or
837 * was not recognised, or never ended with an answer before the cache
838 * lapsed, or the operator prompted first. attend records it as unfinished.
839 * The wrap is cleared before the first await, so a caller may fire it. */
840async function reportUnrouted($: $, ka: Keepalive, why: string) {
841 ka.wrap = undefined
842 await serialize(ka, () => run($, wrappedArgv('unfinished', why)))
843}
844
845export const register: Register = on => {
846 const mod: Mod = {
847 config: { ...DEFAULT_CONFIG },
848 canPoll: false,
849 isInteractive: false,
850 cwd: '.',
851 running: new Set(),
852 isPolling: false,
853 isTicking: false,
854 ticker: undefined,
855 lastPollMs: 0,
856 lastPeersMs: 0,
857 lastKeepwarmMs: 0,
858 lastBeatMs: 0,
859 isBeatPlain: false,
860 lastActivityMs: 0,
861 ids: new Map(),
862 active: false,
863 pending: [],
864 isPendingCold: false,
865 submitTries: 0,
866 joined: new Set(),
867 isStarted: false,
868 isRelistening: false,
869 move: undefined,
870 gaveUp: undefined,
871 isMoveListened: false,
872 startWatch: undefined,
873 contextTokens: undefined,
874 heldNote: undefined,
875 ka: {
876 applies: false,
877 gate: 'unknown',
878 gateAtMs: -Infinity,
879 timer: undefined,
880 chain: Promise.resolve(),
881 epoch: 0,
882 heldPromptMs: undefined,
883 retries: 0,
884 wrap: undefined,
885 },
886 }
887
888 on('session.start', async ($, e, next) => {
889 mod.cwd = e.cwd
890 mod.config = await readConfig($, e.cwd)
891 // mods.attend.install false: the mod is unavailable, nothing is listed.
892 if (!mod.config.install) return next(e)
893 mod.canPoll = e.isInteractive || mod.config.headlessPoll
894 mod.isInteractive = e.isInteractive
895 mod.ka.applies = keepaliveApplies(mod.config, e.isInteractive)
896 // The first check reads where the transcript stands (a resumed session
897 // may be warm) and records the gate for the status card.
898 if (mod.ka.applies) await armKeepalive($, mod, (await $.clock.now()) + POLICY_START_MS)
899 await registerListen($)
900 mod.isStarted = true
901 // The move's watch runs on this hook's `$`: session.end's bound aborts
902 // the waits of its own.
903 mod.startWatch = () => watchMove($, mod)
904 // A reload finds the mode in $.state; a new process (`claude --resume`)
905 // finds the session id in the record of sessions that listened, or the
906 // project's config starts it, as it does every session there.
907 const id = await $.session.id()
908 const kept = await readStatus($)
909 // A reload in the middle of a /clear or a /resume takes the watch up.
910 if (kept.move) {
911 adoptMove(mod, kept.move)
912 watchMove($, mod)
913 }
914 const wasActive = isActive(kept) || (await readListened($)).includes(id)
915 if (wasActive || startsActive(mod)) {
916 // Listed by turn one; listening and the first drain follow the hook.
917 // Active from here, so a /clear before activate runs keeps it. A
918 // reload keeps a held-back note the cold start will not report again.
919 mod.active = true
920 mod.heldNote = kept.heldNote ?? undefined
921 await registerActiveTools($)
922 $.clock.after(0, () => void activate($, mod, id))
923 } else {
924 // Dormant: attend's drain delivers nothing to this session either.
925 $.clock.after(0, () => void run($, LISTEN_OFF_ARGV))
926 }
927 return next(e)
928 })
929
930 // A /clear or an in-session /resume ends the conversation and the process
931 // goes on under another session id, with no session.start, and Claude
932 // Code empties this plugin's $.state. session.end with reason `clear` or
933 // `resume` is the engine's word for it. The id that goes on shows later,
934 // so this hook records the move as plain data and makes no call on its own
935 // `$`, whose waits session.end's short bound aborts: mod.startWatch()
936 // schedules the watch (watchMove) on session.start's `$`. The mod
937 // hooks no classic.* event: where an organization manages Claude Code, its
938 // policy plugin sends those past the plugins a person installs. An exit, a
939 // logout or a -p run's end changes nothing here; at process start
940 // session.start alone reads the record.
941 on('session.end', ($, e, next) => {
942 if (mod.isStarted && mod.startWatch && (e.reason === 'clear' || e.reason === 'resume')) {
943 mod.isMoveListened = false
944 recordMove(mod, e.sessionId, e.reason, mod.active)
945 mod.startWatch()
946 }
947 return next(e)
948 })
949
950 // A compaction drops the earlier preamble from the model's view, so the
951 // next delivery shows it in full. session.compact passes over the plugins
952 // a person installs where an organization manages Claude Code, so the mod
953 // reads a compaction from what reaches it there: the person's /compact
954 // once it has run and left the fill unreported, its own compaction after a
955 // wrap (markCompacted), and the context fill falling below half between
956 // two measurements, as an automatic compaction usually leaves it.
957 on('command.run', { command: 'compact' }, async ($, e, next) => {
958 const done = await next(e)
959 if (await isFillCleared($)) await markCompacted($)
960 return done
961 })
962
963 on('session.measure', async ($, e, next) => {
964 const before = mod.contextTokens
965 mod.contextTokens = e.context.tokens
966 if (isContextReset(before, e.context.tokens)) await markCompacted($)
967 return next(e)
968 })
969
970 // The operator's next prompt while a message waits on a lapsed cache, or
971 // while the cold start's held-back note waits: what is pending enters
972 // beside it, read in the same turn, rather than as a turn the operator
973 // never asked for.
974 on('prompt.submit', async ($, e, next) => {
975 // Any prompt (a schedule, a peer, a task notice) moves the epoch, so a
976 // check in flight queues nothing behind its turn; only the operator's
977 // starts the count again.
978 mod.ka.epoch += 1
979 if (!OPERATOR_ORIGINS.has(e.origin.kind)) return next(e)
980 await keepaliveOperator($, mod)
981 const isHeldCold = (await readStatus($)).cacheLapsed || mod.isPendingCold
982 if (mod.heldNote === undefined && !isHeldCold) return next(e)
983 if (isHeldCold) await updateStatus($, s => ({ ...s, cacheLapsed: false }))
984 if (!(await isOn($, mod))) return next(e)
985 return enterWithPending($, mod, e, next, isHeldCold)
986 })
987
988 // The main loop's turns only: a subagent's or a background agent's run
989 // is a turn of its own loop and can outlast the operator's attention by
990 // half an hour, while the main loop idles and a message should wake it.
991 on('turn.start', async ($, e, next) => {
992 if (e.agentId !== undefined) return next(e)
993 mod.running.add(e.turnId)
994 // Nothing is due while a main-loop turn runs, and a check in flight
995 // submits nothing. The turn the wrap's own text started is the wrap's.
996 mod.ka.epoch += 1
997 mod.ka.timer?.cancel()
998 mod.ka.timer = undefined
999 const w = mod.ka.wrap
1000 if (w && w.turnId === undefined) {
1001 if (isWrapTurn(e.text ?? '', w.text)) w.turnId = e.turnId
1002 else w.sawTurn = true
1003 }
1004 mod.lastActivityMs = await $.clock.now()
1005 // A turn under the id that goes on, before the watch has read it; a
1006 // turn while the id still reads as one that ended leaves the watch on.
1007 if (mod.move || mod.gaveUp) await settleIfMoved($, mod)
1008 if (await isOn($, mod)) await updateStatus($, s => ({ ...s, turnsSinceFull: s.turnsSinceFull + 1 }))
1009 return next(e)
1010 })
1011
1012 // The wrap's own answer: its turn's first step that ended it. A peer
1013 // message the Stop hook drains, or a notification, continues the turn
1014 // with more steps, and their answer is not the wrap.
1015 on('turn.step', async function* ($, e, next) {
1016 const r = yield* next(e)
1017 const w = mod.ka.wrap
1018 if (e.agentId === undefined && w && w.turnId === e.turnId && w.reply === undefined && r.stopReason === 'end_turn') w.reply = r.answer
1019 return r
1020 })
1021
1022 on('turn.complete', async ($, e, next) => {
1023 const done = await next(e)
1024 if (e.agentId !== undefined) return done
1025 mod.running.delete(e.turnId)
1026 mod.lastActivityMs = await $.clock.now()
1027 await keepaliveTurnEnded($, mod, e)
1028 // Whatever the Stop hook left (or all of it, where no Stop hook runs).
1029 if (mod.canPoll) $.clock.after(250, () => void tick($, mod, true))
1030 return done
1031 })
1032
1033 on('tool.call', { tool: 'mcp__attend__attend_listen' }, async $ => {
1034 const was = isActive(await readStatus($))
1035 await registerActiveTools($)
1036 return listenResult(await activate($, mod, await $.session.id()), was, mod.canPoll)
1037 })
1038
1039 on('tool.call', { tool: 'mcp__attend__attend_send' }, async ($, e) => {
1040 if (!(await isOn($, mod))) return DORMANT_REFUSAL
1041 const a = input<{ message: unknown; channel: unknown; to: unknown }>(e)
1042 const message = typeof a.message === 'string' ? a.message : ''
1043 if (message.trim() === '') return { result: 'message is empty; nothing sent', isError: true }
1044 const channel = typeof a.channel === 'string' && a.channel.trim() !== '' ? a.channel : undefined
1045 const to = typeof a.to === 'string' && a.to.trim() !== '' ? a.to : undefined
1046 mod.lastActivityMs = await $.clock.now()
1047 return toolResult(await run($, sendArgv(message, channel, to)), 'attend message send')
1048 })
1049
1050 on('tool.call', { tool: 'mcp__attend__attend_reply' }, async ($, e) => {
1051 if (!(await isOn($, mod))) return DORMANT_REFUSAL
1052 const a = input<{ message: unknown; re: unknown }>(e)
1053 const message = typeof a.message === 'string' ? a.message : ''
1054 if (message.trim() === '') return { result: 'message is empty; nothing sent', isError: true }
1055 // A handle this module delivered maps here; any other (one the Stop-hook
1056 // drain printed) goes to attend as written, which resolves it.
1057 const raw = typeof a.re === 'string' ? a.re.trim().replace(/^~/, '') : ''
1058 const re = raw === '' ? undefined : mod.ids.get(raw) ?? raw
1059 mod.lastActivityMs = await $.clock.now()
1060 return toolResult(await run($, replyArgv(message, re)), 'attend message reply')
1061 })
1062
1063 on('tool.call', { tool: 'mcp__attend__attend_join' }, async ($, e) => {
1064 if (!(await isOn($, mod))) return DORMANT_REFUSAL
1065 const a = input<{ channel: unknown }>(e)
1066 const channel = typeof a.channel === 'string' ? a.channel.trim() : ''
1067 if (channel === '') return { result: 'channel is empty; nothing joined', isError: true }
1068 mod.lastActivityMs = await $.clock.now()
1069 const r = await run($, joinArgv(channel))
1070 if (r.exitCode === 0) {
1071 const label = `#${channel.replace(/^[#@]/, '')}`
1072 mod.joined.add(label)
1073 await updateStatus($, s => ({ ...s, channels: [...new Set([...s.channels, label])] }))
1074 }
1075 return toolResult(r, 'attend channel join')
1076 })
1077
1078 on('tool.call', { tool: 'mcp__attend__attend_peers' }, async $ => {
1079 if (!(await isOn($, mod))) return DORMANT_REFUSAL
1080 const r = await run($, PEERS_ARGV)
1081 if (r.exitCode === 0) await updateStatus($, s => ({ ...s, peers: parsePeerCount(r.stdout) }))
1082 return toolResult(r, 'attend peer list')
1083 })
1084
1085 // One row while active, in the shape of the operator's statusline: peers,
1086 // unread (or waiting, while the cache is cold), channels, and the keepalive
1087 // policy's segment while it runs. Name and project are the statusline's.
1088 // Dormant draws the keepalive segment alone while it shows, else nothing.
1089 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1090 if (e.props.hasSurvey) return next(e)
1091 const text = rowText(await readStatus($), await $.clock.now())
1092 if (text === undefined) return next(e)
1093 const { Box, Text } = $.ui.resolve(e)
1094 return (
1095 <Box flexDirection="row">
1096 <Text color={SUBTLE}>{'\uE0B6'}</Text>
1097 <Text color={FG} backgroundColor={SUBTLE}>
1098 {' '}
1099 {text}{' '}
1100 </Text>
1101 <Text color={SUBTLE}>{'\uE0B4'}</Text>
1102 </Box>
1103 )
1104 })
1105
1106 // The human's row for a delivery this plugin submitted: one dim line per
1107 // message. ctrl+o (isExpanded) and rows of any other origin keep the
1108 // engine's drawing. The model still reads the full framed text.
1109 on('ui.render', { component: 'UserMessage' }, ($, e, next) => {
1110 const { origin, isExpanded, text } = e.props
1111 if (isExpanded || origin.kind !== 'plugin' || origin.name !== PLUGIN) return next(e)
1112 const lines = peerLines(text)
1113 if (!lines) return next(e)
1114 const { Box, Text } = $.ui.resolve(e)
1115 return (
1116 <Box flexDirection="column">
1117 {lines.map((l, i) => (
1118 <Text key={String(i)} dimColor wrap="truncate-end">
1119 {l}
1120 </Text>
1121 ))}
1122 </Box>
1123 )
1124 })
1125}
1126types/index.d.ts 73 lines1/** The keepalive policy as the row draws it (ADR-414 item 9). */
2export type KeepaliveRow = {
3 state: 'running' | 'wrapped' | 'stopped'
4 count: number
5 max: number
6 /** Epoch seconds. */
7 nextAt: number | null
8 wrapsAt: string | null
9 wrappedAt: string | null
10 /** Why a running policy has nothing due, from attend's decision. */
11 idle: string | null
12 /** A wrap sent over attend was refused and went to the file instead. */
13 isRefused: boolean
14 /** A dormant session draws the segment from its first keepalive until
15 * the operator's next prompt. */
16 isShown: boolean
17}
18
19/** Why the session ended under a running process (session.end's reason). */
20export type MoveReason = 'clear' | 'resume'
21
22/** A /clear or an in-session /resume whose new session id the mod has not
23 * read yet (hooks/move.ts). */
24export type MoveRecord = {
25 /** Every id that ended during the move; none of them is the one that
26 * goes on. */
27 ended: string[]
28 reason: MoveReason
29 /** The session was listening when it ended. */
30 wasOn: boolean
31}
32
33export type AttendStatus = {
34 /** Dormant: plain Claude Code, nothing polled or drawn. Active: listening
35 * until Claude Code exits (ADR-406 item 2). */
36 mode: 'dormant' | 'active'
37 /** Whether attend has this session listening; false when `attend listen on`
38 * failed, null before it ran. */
39 listening: boolean | null
40 peers: number
41 /** Messages waiting for this session (`attend message unread`), or drained and not
42 * yet delivered where attend has no unread count. */
43 unread: number
44 /** The channels this session receives or joined, as `#name`. */
45 channels: string[]
46 /** Deliveries made so far; the preamble line shows on delivery 0. */
47 deliveries: number
48 /** A compaction happened since the last delivery: the next is full. */
49 afterCompaction: boolean
50 /** Turns since the preamble line last showed. */
51 turnsSinceFull: number
52 /** The cold start's held-back note a poll's drain returned, waiting to
53 * ride the operator's next prompt; null when none waits. Kept here so a
54 * reloaded module still carries it. */
55 heldNote: string | null
56 /** A message that would wake the session waits because the prompt cache
57 * has lapsed: the session is not woken, and what waits rides the
58 * operator's next prompt (ADR-406 item 2). */
59 cacheLapsed: boolean
60 /** The keepalive policy's segment of the row (ADR-414 item 9); null
61 * where the policy does not run. */
62 keepalive: KeepaliveRow | null
63 /** A /clear or a /resume the mod is still following, kept so a reloaded
64 * module takes the watch up; null when none is. */
65 move: MoveRecord | null
66}
67
68declare module 'claude-code' {
69 interface PluginState {
70 attend: { status: AttendStatus }
71 }
72}
73hooks/move.ts 119 lines1// The state of a /clear or an in-session /resume the mod is following to the
2// session id that goes on (ADR-406, ADR-411). Plain data and the rules over
3// it, no `$`: register.tsx drives the watch, since the engine follows `$`
4// only into functions declared in the hooks module's own file.
5//
6// session.end, with reason `clear` or `resume`, says the conversation ended
7// and the process goes on under another session id. That id shows in
8// $.session.id() only once Claude Code's settings SessionStart hooks have
9// run, which can take seconds and, on a host whose organization adds its own
10// hooks, much longer. The watch reads the id on a backoff and never takes an
11// id that ended during the move as the one that goes on. After a give-up the
12// ended ids are kept, and a later main-loop turn under another id settles
13// the move then.
14
15import type { Timer } from 'claude-code'
16
17import type { MoveReason, MoveRecord } from '../types/index.d.ts'
18
19/** The first read waits this long after the hold, the waits double to
20 * MOVE_MAX_MS, and after MOVE_GIVE_UP_MS of waiting the watch stops. */
21export const MOVE_FIRST_MS = 250
22export const MOVE_MAX_MS = 2_000
23export const MOVE_GIVE_UP_MS = 5 * 60_000
24
25/** A move in progress: the record, and the watch's own clock. */
26export type Move = MoveRecord & {
27 /** Waited so far, and the next wait. */
28 waitedMs: number
29 delayMs: number
30 timer: Timer | undefined
31 /** Reads of the id that failed; the first is logged. */
32 failures: number
33}
34
35/** Where the module keeps its one move, and the record of one the watch
36 * gave up on, whose ids a later turn still holds apart. */
37export type MoveSlot = { move: Move | undefined; gaveUp: MoveRecord | undefined }
38
39/** What a read of the id leads to (readOutcome). */
40export type Outcome =
41 | { kind: 'settle'; record: MoveRecord }
42 | { kind: 'wait'; delayMs: number }
43 | { kind: 'give-up'; record: MoveRecord }
44 | { kind: 'gone' }
45
46export function recordOf(m: Move): MoveRecord {
47 return { ended: [...m.ended], reason: m.reason, wasOn: m.wasOn }
48}
49
50function fresh(record: MoveRecord): Move {
51 return { ...record, ended: [...record.ended], waitedMs: 0, delayMs: MOVE_FIRST_MS, timer: undefined, failures: 0 }
52}
53
54/** Records a /clear or a /resume of `endedId`: plain data, so session.end
55 * can call it inside its bound. A move already in progress (a second /clear
56 * before the first id showed) takes the new ended id, stops its timer and
57 * starts its waits again. A move given up on lends its ended ids. */
58export function recordMove(slot: MoveSlot, endedId: string, reason: MoveReason, wasOn: boolean) {
59 const m = slot.move
60 if (!m) {
61 const g = slot.gaveUp
62 slot.gaveUp = undefined
63 const ended = (g?.ended ?? []).filter(id => id !== endedId)
64 slot.move = fresh({ ended: [...ended, endedId], reason, wasOn: wasOn || (g?.wasOn ?? false) })
65 return
66 }
67 m.timer?.cancel()
68 m.timer = undefined
69 if (!m.ended.includes(endedId)) m.ended.push(endedId)
70 m.reason = reason
71 m.wasOn = m.wasOn || wasOn
72 m.waitedMs = 0
73 m.delayMs = MOVE_FIRST_MS
74}
75
76/** Takes up a move a reload found in $.state. */
77export function adoptMove(slot: MoveSlot, record: MoveRecord) {
78 slot.move?.timer?.cancel()
79 slot.move = fresh(record)
80}
81
82/** Ends move `m` under `id` when it is still the slot's and `id` did not
83 * end; the slot is cleared at once, so of the watch and a turn racing for
84 * it, one settles. Returns the record to settle, or undefined. */
85export function claimMove(slot: MoveSlot, m: Move, id: string): MoveRecord | undefined {
86 if (slot.move !== m || m.ended.includes(id)) return undefined
87 slot.move = undefined
88 m.timer?.cancel()
89 m.timer = undefined
90 return recordOf(m)
91}
92
93/** Ends a move the watch gave up on, when `id` did not end. */
94export function claimGaveUp(slot: MoveSlot, id: string): MoveRecord | undefined {
95 const g = slot.gaveUp
96 if (!g || slot.move || g.ended.includes(id)) return undefined
97 slot.gaveUp = undefined
98 return g
99}
100
101/** What one read of the id leads to: `id` undefined is a read that failed,
102 * which counts as no change. A wait doubles up to MOVE_MAX_MS; past
103 * MOVE_GIVE_UP_MS the move goes to `gaveUp`. */
104export function readOutcome(slot: MoveSlot, m: Move, id: string | undefined): Outcome {
105 if (slot.move !== m) return { kind: 'gone' }
106 if (id !== undefined) {
107 const record = claimMove(slot, m, id)
108 if (record) return { kind: 'settle', record }
109 }
110 m.waitedMs += m.delayMs
111 if (m.waitedMs >= MOVE_GIVE_UP_MS) {
112 slot.move = undefined
113 slot.gaveUp = recordOf(m)
114 return { kind: 'give-up', record: slot.gaveUp }
115 }
116 m.delayMs = Math.min(m.delayMs * 2, MOVE_MAX_MS)
117 return { kind: 'wait', delayMs: m.delayMs }
118}
119hooks/lib.ts 896 lines1// Pure pieces of the attend mod (ADR-406): argv building, parsing what the
2// attend and ways CLIs print, framing a delivery, and the timing rules. No `$`
3// here, so the tests exercise them directly.
4
5import type { Timer } from 'claude-code'
6
7import type { AttendStatus, KeepaliveRow, MoveRecord } from '../types/index.d.ts'
8import type { Move } from './move.ts'
9
10export const ATTEND = 'attend'
11/** This mod's version, equal to .claude-plugin/plugin.json's. A mod cannot read
12 * its manifest, so scripts/check-plugins.sh compares the two and
13 * scripts/release.sh bump moves both. The beat sends it to attend, which
14 * tells the operator when the session runs an older mod than the installed
15 * one. */
16export const MOD_VERSION = '0.30.0'
17export const WAYS = 'ways'
18
19// ── argv ─────────────────────────────────────────────────────────────────
20// Every call is an argv array with no shell. A body is one element after
21// `--`, so no quoting rule applies to it and a body that starts with a dash
22// stays a body. attend sends a long body as one message.
23
24/** `attend message send [--channel C] [--to T] -- <message>`: `to` is a session's
25 * name, a person's member id or a project path, and makes it a direct
26 * message; with neither it posts to #open, as `channel` open does. */
27export function sendArgv(message: string, channel?: string, to?: string): string[] {
28 const argv = [ATTEND, 'message', 'send']
29 if (channel) argv.push('--channel', bareChannel(channel))
30 if (to) argv.push('--to', to)
31 argv.push('--', message)
32 return argv
33}
34
35/** `attend message reply [--re <id>] -- <message>`: threads to the newest message
36 * delivered, or to `re`, and goes to that message's sender as a direct
37 * message, or into its channel when it was said in a named channel. attend
38 * refuses a parent whose channel this session left, whose sender session
39 * has exited, or that it cannot find. */
40export function replyArgv(message: string, re?: string): string[] {
41 return re ? [ATTEND, 'message', 'reply', '--re', re, '--', message] : [ATTEND, 'message', 'reply', '--', message]
42}
43
44export function joinArgv(channel: string): string[] {
45 return [ATTEND, 'channel', 'join', bareChannel(channel)]
46}
47
48function bareChannel(channel: string): string {
49 return channel.trim().replace(/^[#@]/, '')
50}
51
52/** `listen on` names the mod as the host, so attend's Stop-hook drain speaks
53 * the mod's format and tools in this session. */
54export const LISTEN_ON_ARGV = [ATTEND, 'listen', 'on', '--host', 'mod'] as const
55export const LISTEN_OFF_ARGV = [ATTEND, 'listen', 'off'] as const
56export const DRAIN_ARGV = [ATTEND, 'message', 'inbox', '--drain', '--json'] as const
57/** The idle poll's drain: it takes nothing unless something pending is
58 * addressed to this session, sent to its project, a reply to a message it
59 * sent, or a post in one of its named channels (ADR-406 item 2). */
60export const WAKE_DRAIN_ARGV = [ATTEND, 'message', 'inbox', '--drain', '--json', '--wake'] as const
61export const UNREAD_ARGV = [ATTEND, 'message', 'unread', '--json'] as const
62/** Touches the session's heartbeat while it listens, and records the mod's
63 * version for the session. The drain touches the heartbeat too, but runs
64 * only between turns and at the poll's interval, which can be longer than
65 * attend's 90 s liveness grace. */
66export const BEAT_ARGV = [ATTEND, 'listen', 'beat', '--mod', MOD_VERSION] as const
67/** The beat for an attend that predates `--mod` and exits 2 on it (a usage
68 * error): the heartbeat without the version. */
69export const PLAIN_BEAT_ARGV = [ATTEND, 'listen', 'beat'] as const
70export const PEERS_ARGV = [ATTEND, 'peer', 'list'] as const
71export const KEEPWARM_CHECK_ARGV = [ATTEND, 'keepwarm', 'check'] as const
72/** The operator prompted at `atS` (epoch seconds): the keepalive count
73 * starts again (ADR-414 item 4). */
74export function resetArgv(atS: number): string[] {
75 return [ATTEND, 'keepwarm', 'reset', '--at', String(Math.floor(atS))]
76}
77
78/** The keepalive policy's judgment, once, with the autocompact gate the mod
79 * read (ADR-414 item 7). */
80export function policyArgv(gate: Gate): string[] {
81 return [ATTEND, 'keepwarm', 'check', '--policy', '--json', '--autocompact', gate]
82}
83
84/** Where the wrap's reply went, for the status card. */
85export function wrappedArgv(outcome: WrapOutcome, detail: string): string[] {
86 return [ATTEND, 'keepwarm', 'wrapped', outcome, '--detail', oneLine(detail)]
87}
88
89/** The wrap's reply sent over attend: one message, its first line the
90 * handoff line attend wrote, to `#name` as a channel post and to anything
91 * else as a direct message (ADR-414 item 6). */
92export function wrapSendArgv(route: WrapRoute, reply: string): string[] {
93 const body = `${oneLine(route.handoff)}\n${reply}`
94 return route.to.startsWith('#') ? sendArgv(body, route.to) : sendArgv(body, undefined, route.to)
95}
96
97/** Whether `to` names `#open`, which reaches every listening session on the
98 * host. attend refuses it as a wrap's recipient; the mod refuses it too. */
99export function isOpenChannel(to: string): boolean {
100 return /^#\s*open\s*$/i.test(to)
101}
102
103/** The resolved `mods.attend` entry, through the ways config layers: the
104 * user file, the target's file, then the project's `.claude/ways.yaml`. */
105export function configArgv(project: string): string[] {
106 return [WAYS, 'settings', 'list', 'mods.attend', '--json', '--effective', '--project', project]
107}
108
109// ── the module's state ─────────────────────────────────────────────────
110
111/** What the module keeps between dispatches. A reload starts it afresh, so
112 * the mode a reload reads is the one in $.state: session.start restores it
113 * from there, and a /clear or a /resume, which empty $.state, has it put
114 * back. Across processes the record in $.store answers instead. */
115export type Mod = {
116 config: ModConfig
117 /** Whether this session may poll: interactive, or allowed by config. */
118 canPoll: boolean
119 isInteractive: boolean
120 cwd: string
121 /** The main loop's turns running now. The poll holds while one runs: the
122 * Stop-hook drain owns delivery at a turn's boundary. */
123 running: Set<string>
124 isPolling: boolean
125 isTicking: boolean
126 ticker: Timer | undefined
127 lastPollMs: number
128 lastPeersMs: number
129 lastKeepwarmMs: number
130 lastBeatMs: number
131 /** attend rejected `--mod`, so beats go without it. */
132 isBeatPlain: boolean
133 /** The last delivery, send, reply, join or turn. */
134 lastActivityMs: number
135 /** Short `~id` handles of delivered messages, to their full ids. */
136 ids: Map<string, string>
137 /** Set on activation; the mode in $.state is the copy a reload reads. */
138 active: boolean
139 /** A drained batch no submit has taken yet. */
140 pending: Listed[]
141 /** `pending` was taken from a prompt the operator made while the cache
142 * had lapsed, and that prompt did not enter. The poll leaves it for the
143 * operator's next prompt instead of starting a turn on the cold cache. */
144 isPendingCold: boolean
145 /** Submits of `pending` that failed. */
146 submitTries: number
147 /** Channels joined through attend_join, shown until attend reports rooms. */
148 joined: Set<string>
149 /** session.start has run; before it, at process start, the engine has not
150 * bound the session and refuses a tool registration. */
151 isStarted: boolean
152 /** A /clear or a /resume moved the session to an id attend has not been
153 * told is listening yet; the poll holds its drain until it has. */
154 isRelistening: boolean
155 /** A /clear or a /resume whose new id the mod has not read yet
156 * (move.ts). */
157 move: Move | undefined
158 /** A move the watch gave up on; the next main-loop turn under another id
159 * settles it. */
160 gaveUp: MoveRecord | undefined
161 /** The move has told attend the session listens, before its new id
162 * showed. */
163 isMoveListened: boolean
164 /** Starts the move's watch on session.start's `$`, whose timers outlive
165 * any one hook: session.end's bound aborts the waits of its own. */
166 startWatch: (() => void) | undefined
167 /** The context fill the last `session.measure` reported, in tokens. */
168 contextTokens: number | undefined
169 /** The cold start's held-back note, from a drain the poll ran. A wake
170 * delivery carries messages alone, so the note rides the operator's next
171 * prompt as context. The module's copy serves a /clear, which empties
172 * $.state; the copy in $.state (`heldNote`) serves a reload. */
173 heldNote: string | undefined
174 /** The keepalive policy's state (ADR-414). */
175 ka: Keepalive
176}
177
178export type Keepalive = {
179 /** keepaliveApplies: an interactive session, keepwarm on, the policy
180 * enabled. Never a -p run or an SDK session. */
181 applies: boolean
182 gate: Gate
183 gateAtMs: number
184 /** The one timer: the next check. */
185 timer: Timer | undefined
186 /** The reset, the check and the wrap's report run one at a time, so a
187 * prompt's reset is never overwritten by a check that read the ledger
188 * before it. */
189 chain: Promise<unknown>
190 /** Moves at each operator prompt and main-loop turn start: a check whose
191 * epoch moved while attend judged submits nothing. */
192 epoch: number
193 /** The operator's last prompt, held while the gate last read on or
194 * unknown; sent to attend when the gate first reads off. */
195 heldPromptMs: number | undefined
196 /** Checks that could not judge since the last turn's end. */
197 retries: number
198 /** A wrap submitted, its text, the main-loop turn that text started, and
199 * the answer of that turn's first step that ended it (`end_turn`): the
200 * wrap itself, whatever a Stop-hook continuation or a notification adds
201 * to the turn after it. */
202 wrap: { route: WrapRoute; text: string; turnId: string | undefined; reply: string | undefined; sawTurn: boolean } | undefined
203}
204
205// ── tools ────────────────────────────────────────────────────────────────
206
207/** The one tool of a dormant session. */
208export const LISTEN_TOOL = {
209 name: 'attend_listen',
210 description:
211 'Turn on attend (peer messaging between Claude sessions and people in attend-chat) for the rest of this session. Call it only when the user asks to use attend. It delivers messages addressed to this session, shows one status row, and adds attend_send, attend_reply, attend_join and attend_peers. It stays on until Claude Code exits.',
212 inputSchema: { type: 'object', properties: {} },
213 isDeferred: false,
214 } as const
215
216/** The tools of an active session. */
217export const ACTIVE_TOOLS = [
218 {
219 name: 'attend_send',
220 description:
221 'Start a new topic over attend. Name someone in `to` to send them a direct message. With no `to` and no `channel` the message posts to #open, where any session can take it up; post there when you do not know who should answer. #open reaches every listening session, in other projects too, so keep chatter about this project to a named channel or a direct message. `channel` posts to a named channel, which wakes its idle members; with `to` as well, the post stays in the channel addressed to them. To answer a message that arrived, use attend_reply. The message is passed as is: no quoting needed, and a long one goes out as one message.',
222 inputSchema: {
223 type: 'object',
224 properties: {
225 message: { type: 'string', description: 'The message body.' },
226 channel: { type: 'string', description: 'A channel name, with or without #. open or #open posts to #open.' },
227 to: {
228 type: 'string',
229 description: "Who the direct message is for: a session's name (such as Chaucer-beta), a person's member id (such as aaron), or a project path for every session there.",
230 },
231 },
232 required: ['message'],
233 },
234 isDeferred: false,
235 },
236 {
237 name: 'attend_reply',
238 description:
239 "Reply to a message that arrived over attend. The reply is a direct message to its sender, an answer to an #open post included; a reply to a post in a named channel stays in that channel. It threads to the newest inbound message, or to the one given as `re` (the `~id` at the end of its line, or a full id). Silence is a valid reply.",
240 inputSchema: {
241 type: 'object',
242 properties: {
243 message: { type: 'string', description: 'The reply body.' },
244 re: { type: 'string', description: 'The message replied to: the `~id` at the end of a delivery line.' },
245 },
246 required: ['message'],
247 },
248 isDeferred: false,
249 },
250 {
251 name: 'attend_join',
252 description: 'Join an attend channel (created if absent), so its messages reach this session.',
253 inputSchema: {
254 type: 'object',
255 properties: { channel: { type: 'string', description: 'The channel name, with or without #.' } },
256 required: ['channel'],
257 },
258 isDeferred: false,
259 },
260 {
261 name: 'attend_peers',
262 description: "List the active Claude Code sessions on this machine and their channels, and who is in each of this session's channels.",
263 inputSchema: { type: 'object', properties: {} },
264 isDeferred: false,
265 },
266] as const
267
268/** A CLI call as a tool's result: its output, or why it failed. */
269export function toolResult(r: { exitCode: number; stdout: string; stderr: string }, what: string) {
270 const text = r.stdout.trim() || r.stderr.trim()
271 return r.exitCode === 0
272 ? { result: text || 'done' }
273 : { result: `${what} failed (${r.exitCode}): ${r.stderr.trim() || r.stdout.trim()}`, isError: true as const }
274}
275
276export const DORMANT_REFUSAL = {
277 result: 'attend is not listening in this session. Call attend_listen first, and only when the user asked to use attend.',
278 isError: true as const,
279}
280
281/** attend_listen's answer, from attend's answer to `listen on`. */
282export function listenResult(r: { exitCode: number; stderr: string }, was: boolean, canPoll: boolean) {
283 const tools = ' attend_send, attend_reply, attend_join and attend_peers are available.'
284 if (r.exitCode !== 0) {
285 return {
286 result: `attend could not set this session listening, so no message will be delivered to it; the tools can still send.${tools}\nattend listen on failed (${r.exitCode}): ${r.stderr.trim()}`,
287 isError: true as const,
288 }
289 }
290 const lead = was ? 'attend was already listening in this session.' : 'attend is listening for the rest of this session.'
291 const poll = canPoll
292 ? ' Messages addressed to this session and posts in its channels arrive as peer-data turns; other #open posts arrive with your next turn.'
293 : ' This session does not poll (a -p or SDK run); messages arrive at the end of a turn.'
294 return { result: `${lead}${poll}${tools}` }
295}
296
297/** Origins that are the operator's own prompt: the terminal, Remote
298 * Control, an SDK host's turn, and the owner's ping from Slack. An
299 * unclassified one is not counted as the operator's. */
300export const OPERATOR_ORIGINS = new Set(['composer', 'bridge', 'sdk', 'slack-ping'])
301
302// ── configuration ────────────────────────────────────────────────────────
303
304export type ModConfig = {
305 /** How a session in this project starts. */
306 listening: 'active' | 'dormant'
307 /** Whether an active session runs attend's keepwarm check (ADR-182). */
308 keepwarm: 'on' | 'off'
309 /** false: the mod is unavailable, nothing is listed. */
310 install: boolean
311 /** The poll interval while awake, in seconds. */
312 pollSeconds: number
313 /** The poll interval once the session has been quiet, in seconds. */
314 slowPollSeconds: number
315 /** Quiet this long and the poll slows, in minutes. */
316 quietMinutes: number
317 /** The preamble shows again once this many turns have passed. */
318 preambleEveryTurns: number
319 /** Whether a `-p` run or an SDK session may poll. */
320 headlessPoll: boolean
321 /** `mods.attend.keepalive.enabled`: the keepalive policy may run (ADR-414). */
322 keepalive: boolean
323 /** `mods.attend.keepalive.margin_minutes`: a keepalive is due this long
324 * before the cache lapses. attend judges; the mod uses it only to set a
325 * dormant session's timer. */
326 marginMinutes: number
327}
328
329/** What the mod runs under when ways cannot answer. The keepalive policy
330 * fails closed: off, as `keepwarm` and `install` fall to their quiet side
331 * in the registry (ADR-414 item 8). */
332export const DEFAULT_CONFIG: ModConfig = {
333 listening: 'dormant',
334 keepwarm: 'on',
335 install: true,
336 pollSeconds: 5,
337 slowPollSeconds: 60,
338 quietMinutes: 20,
339 preambleEveryTurns: 20,
340 headlessPoll: false,
341 keepalive: false,
342 marginMinutes: 10,
343}
344
345/** The notice when `ways settings list mods.attend` exits non-zero: the mod
346 * runs on its defaults, and the usual cause is a ways and an attend mod
347 * from different releases (ADR-512 renamed the section). No alias is
348 * kept, so the fix is the update. `undefined` for a clean exit. */
349export function configNotice(exitCode: number): string | undefined {
350 if (exitCode === 0) return undefined
351 return (
352 `attend: \`ways settings list mods.attend\` exited ${exitCode}, so the mod runs on its defaults ` +
353 `(dormant, keepalive off); update ways and the attend mod together (\`ways manage update --commit\`)`
354 )
355}
356
357/** Reads `ways settings list mods.attend --json --effective`. A key that is
358 * absent or of the wrong type keeps its default, so a ways CLI that is
359 * missing or older than the section leaves the mod dormant. */
360export function parseConfig(stdout: string): ModConfig {
361 let keys: Record<string, { value?: unknown }> = {}
362 try {
363 const doc = JSON.parse(stdout) as { keys?: Record<string, { value?: unknown }> }
364 keys = doc.keys ?? {}
365 } catch {
366 return { ...DEFAULT_CONFIG }
367 }
368 const v = (k: string) => keys[`mods.attend.${k}`]?.value
369 const num = (k: string, d: number) => {
370 const x = v(k)
371 return typeof x === 'number' && Number.isFinite(x) && x > 0 ? x : d
372 }
373 const bool = (k: string, d: boolean) => {
374 const x = v(k)
375 return typeof x === 'boolean' ? x : d
376 }
377 return {
378 listening: v('listening') === 'active' ? 'active' : 'dormant',
379 keepwarm: v('keepwarm') === 'off' ? 'off' : 'on',
380 install: bool('install', DEFAULT_CONFIG.install),
381 pollSeconds: num('poll_seconds', DEFAULT_CONFIG.pollSeconds),
382 slowPollSeconds: num('slow_poll_seconds', DEFAULT_CONFIG.slowPollSeconds),
383 quietMinutes: num('quiet_minutes', DEFAULT_CONFIG.quietMinutes),
384 preambleEveryTurns: num('preamble_every_turns', DEFAULT_CONFIG.preambleEveryTurns),
385 headlessPoll: bool('headless_poll', DEFAULT_CONFIG.headlessPoll),
386 // Only an explicit true: a ways that does not know the key runs none.
387 keepalive: v('keepalive.enabled') === true,
388 marginMinutes: num('keepalive.margin_minutes', DEFAULT_CONFIG.marginMinutes),
389 }
390}
391
392// ── timing ───────────────────────────────────────────────────────────────
393
394/** The interval the next poll waits: the slow one once the session has had
395 * no delivery, no send of its own and no turn for the quiet period. */
396export function pollInterval(c: ModConfig, idleMs: number, isTurnRunning: boolean): number {
397 const quiet = !isTurnRunning && idleMs >= c.quietMinutes * 60_000
398 return (quiet ? c.slowPollSeconds : c.pollSeconds) * 1000
399}
400
401/** The preamble goes with delivery 0, the first after a compaction, and
402 * the first once `every` turns have passed since it last showed. */
403export function isFullPreamble(deliveries: number, afterCompaction: boolean, turnsSinceFull: number, every: number): boolean {
404 return deliveries === 0 || afterCompaction || turnsSinceFull >= every
405}
406
407/** Whether the context window was emptied between two measurements: its
408 * fill fell below half, or reads as absent, which it does until the first
409 * response after a compaction or a /clear. A compaction at the engine's
410 * threshold always falls that far. A first measurement compares with
411 * nothing and is no reset. */
412export function isContextReset(before: number | undefined, after: number | undefined): boolean {
413 if (before === undefined || before <= 0) return false
414 return after === undefined || after < before / 2
415}
416
417/** Whether the keepalive policy may run in a session started with
418 * `isInteractive` under `c` (ADR-414 item 1): never a -p run or an SDK
419 * session, whatever `headless_poll` says; autocompact is judged at each
420 * check. Where it applies, keepalive.tsx drives every cache wake. */
421export function keepaliveApplies(c: ModConfig, isInteractive: boolean): boolean {
422 return isInteractive && c.install && c.keepwarm === 'on' && c.keepalive
423}
424
425/** When the policy's timer asks attend first after a main-loop turn's end: the margin before the hour tier's cache lapses, or ADR-182's
426 * 50 minutes when that comes sooner, which an armed window wakes at. attend
427 * answers with the due point it judged. */
428export function firstCheckMs(c: ModConfig): number {
429 return Math.min(60 - c.marginMinutes, 50) * 60_000
430}
431
432// ── the keepalive policy (ADR-414) ───────────────────────────────────────
433
434/** The autocompact gate: `off` lets the policy run; `unknown` counts as on,
435 * the side that starts no turn the operator did not type. */
436export type Gate = 'on' | 'off' | 'unknown'
437
438/** The gate from `$.session.usage({ breakdown: 'summary' })`, else from
439 * `autoCompactEnabled` in `$.settings.read()`, where only an explicit false
440 * is off and an absent key is Claude Code's default, on. Either read is
441 * undefined when it failed. */
442export function gateFrom(usage: unknown, settings: unknown): Gate {
443 const b = (usage as { context?: { breakdown?: { isAutoCompactEnabled?: unknown } } } | undefined)?.context?.breakdown
444 if (typeof b?.isAutoCompactEnabled === 'boolean') return b.isAutoCompactEnabled ? 'on' : 'off'
445 if (typeof settings !== 'object' || settings === null) return 'unknown'
446 return (settings as { autoCompactEnabled?: unknown }).autoCompactEnabled === false ? 'off' : 'on'
447}
448
449/** Where the wrap's reply goes, as attend resolved it. */
450export type WrapRoute = {
451 dest: 'transcript' | 'file' | 'send' | 'off'
452 /** The expanded `wrap_file`: `file`'s destination and a refused send's fallback. */
453 file: string
454 /** `send`'s recipient; `#name` is a channel. */
455 to: string
456 after: 'lapse' | 'compact'
457 handoff: string
458}
459
460/** What `attend keepwarm check --policy --json` decided. */
461export type Decision = {
462 action: 'none' | 'keepalive' | 'wrap'
463 text: string | null
464 /** When to ask again, in epoch seconds. */
465 nextAt: number | null
466 count: number
467 max: number
468 wrapsAt: string | null
469 wrappedAt: string | null
470 /** Whether the policy runs; false is ADR-182's armed windows alone. */
471 policy: boolean
472 state: 'running' | 'wrapped' | 'stopped' | 'off'
473 reason: string
474 wrap: WrapRoute | null
475 /** attend could not judge (the transcript was unreadable): ask again. */
476 retry: boolean
477 /** Why a running policy has nothing due: `under 50k`, `5m tier`. */
478 idle: string | null
479}
480
481export type WrapOutcome = 'transcript' | 'file' | 'sent' | 'refused' | 'unfinished'
482
483/** The decision; undefined where the output is not one (an attend without
484 * `--policy`, a build without the sensor). */
485export function parseDecision(stdout: string): Decision | undefined {
486 let d: Record<string, unknown>
487 try {
488 const doc = JSON.parse(stdout) as unknown
489 if (typeof doc !== 'object' || doc === null) return undefined
490 d = doc as Record<string, unknown>
491 } catch {
492 return undefined
493 }
494 const action = d.action
495 if (action !== 'none' && action !== 'keepalive' && action !== 'wrap') return undefined
496 const str = (v: unknown) => (typeof v === 'string' ? v : null)
497 const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : null)
498 const states = ['running', 'wrapped', 'stopped', 'off'] as const
499 const state = states.find(x => x === d.state) ?? 'off'
500 const w = d.wrap as Record<string, unknown> | null | undefined
501 const dests = ['transcript', 'file', 'send', 'off'] as const
502 const dest = dests.find(x => x === w?.dest)
503 const wrap: WrapRoute | null =
504 w && dest && typeof w.file === 'string' && typeof w.to === 'string'
505 ? { dest, file: w.file, to: w.to, after: w.after === 'compact' ? 'compact' : 'lapse', handoff: str(w.handoff) ?? 'handoff:' }
506 : null
507 return {
508 action,
509 text: str(d.text),
510 nextAt: num(d.next_at),
511 count: num(d.count) ?? 0,
512 max: num(d.max) ?? 0,
513 wrapsAt: str(d.wraps_at_hm),
514 wrappedAt: str(d.wrapped_at_hm),
515 policy: d.policy === true,
516 state,
517 reason: str(d.reason) ?? '',
518 wrap,
519 retry: d.retry === true,
520 idle: str(d.idle),
521 }
522}
523
524/** The focus a compaction after the wrap keeps: the wrap's closing
525 * `/compact <focus>` line, else the continuation prompt and the task list. */
526export const DEFAULT_COMPACT_FOCUS = 'keep the continuation prompt and the task list'
527
528export function compactFocus(reply: string): string {
529 const lines = reply.split('\n').map(l => l.trim().replace(/^`+|`+$/g, ''))
530 for (let i = lines.length - 1; i >= 0; i--) {
531 const m = /^\/compact\s+(.+)$/.exec(lines[i] ?? '')
532 if (m?.[1]) return m[1].trim()
533 }
534 return DEFAULT_COMPACT_FOCUS
535}
536
537
538/** The row's segment after a decision; null where the policy does not run.
539 * A dormant session shows it from the first turn the policy submits. */
540export function keepaliveRowOf(d: Decision, was: KeepaliveRow | null): KeepaliveRow | null {
541 if (!d.policy || d.state === 'off') return null
542 return {
543 state: d.state,
544 count: d.count,
545 max: d.max,
546 nextAt: d.state === 'running' ? d.nextAt : null,
547 wrapsAt: d.wrapsAt,
548 wrappedAt: d.wrappedAt,
549 idle: d.state === 'running' ? d.idle : null,
550 isRefused: d.state === 'wrapped' && (was?.isRefused ?? false),
551 isShown: (was?.isShown ?? false) || d.action !== 'none',
552 }
553}
554
555/** `⟳ 2/8 · next 41m · wrap ~21:40`, `⟳ 0/1 · idle: under 50k`,
556 * `⟳ wrapped 21:40`, `⟳ stopped`. */
557export function keepaliveSegment(k: KeepaliveRow, nowMs: number): string {
558 if (k.state === 'wrapped') return `⟳ wrapped ${k.wrappedAt ?? ''}`.trimEnd() + (k.isRefused ? ' · handoff refused' : '')
559 if (k.state === 'stopped') return '⟳ stopped'
560 const parts = [`⟳ ${k.count}/${k.max}`]
561 if (k.nextAt !== null) parts.push(`next ${Math.max(0, Math.round((k.nextAt * 1000 - nowMs) / 60_000))}m`)
562 if (k.wrapsAt !== null) parts.push(`wrap ~${k.wrapsAt}`)
563 if (k.idle) parts.push(`idle: ${k.idle}`)
564 return parts.join(' · ')
565}
566
567/** Runs `f` after every earlier call on `h` settled, one at a time. */
568export function serialize<T>(h: { chain: Promise<unknown> }, f: () => Promise<T>): Promise<T> {
569 const next = h.chain.then(f, f)
570 h.chain = next.catch(() => undefined)
571 return next
572}
573
574/** A gate read as on or unknown is reused this long; one read as off is
575 * read again before every check and every submit, since a turn may follow. */
576export const GATE_KEPT_MS = 5 * 60_000
577
578export function gateIsFresh(gate: Gate, gateAtMs: number, nowMs: number): boolean {
579 return gate !== 'off' && nowMs - gateAtMs < GATE_KEPT_MS
580}
581
582/** What one decision asks of the mod: a turn to submit, and when to ask
583 * again. A dormant session submits only the policy's own turns, never an
584 * armed window's wake, which stays a listening session's (ADR-406 item
585 * 13). A retry is the caller's to bound. */
586export type CheckPlan = {
587 submit: { kind: 'keepalive' | 'wrap'; text: string; route: WrapRoute | null } | null
588 armAtMs: number | null
589 retry: boolean
590}
591
592export function planCheck(d: Decision, isListening: boolean): CheckPlan {
593 let submit: CheckPlan['submit'] = null
594 if (d.action === 'keepalive' && d.text && (isListening || d.policy)) submit = { kind: 'keepalive', text: d.text, route: null }
595 if (d.action === 'wrap' && d.text && d.wrap && d.policy) submit = { kind: 'wrap', text: d.text, route: d.wrap }
596 const armAtMs = !d.retry && d.nextAt !== null && (d.policy || isListening) ? d.nextAt * 1000 : null
597 return { submit, armAtMs, retry: d.retry }
598}
599
600/** Whether a planned turn may still go in: no prompt or main-loop turn came
601 * since the check began (the epoch held), none runs now, and for the
602 * policy's own turn the gate, read again, is still off (ADR-414 item 2). */
603export function maySubmit(o: { epochThen: number; epochNow: number; running: number; isPolicy: boolean; gate: Gate }): boolean {
604 return o.epochThen === o.epochNow && o.running === 0 && (!o.isPolicy || o.gate === 'off')
605}
606
607/** A dormant session's retries after a check that could not judge, at most
608 * this many per stretch, this far apart; a listening session asks again on
609 * the plain cadence. */
610export const RETRY_MAX = 3
611export const RETRY_DORMANT_MS = 5 * 60_000
612export const RETRY_LISTENING_MS = 60_000
613
614export function retryAtMs(nowMs: number, isListening: boolean, gate: Gate, retries: number): number | null {
615 if (isListening) return nowMs + RETRY_LISTENING_MS
616 return gate === 'off' && retries < RETRY_MAX ? nowMs + RETRY_DORMANT_MS : null
617}
618
619/** The header Claude Code puts above a prompt a plugin submits without
620 * `asUser`, as `turn.start`'s text carries it (Claude Code 2.1.300):
621 * `The <plugin> plugin sent a message:`, then the prompt, then a closing
622 * paragraph. Only this mod's own name, the manifest's `attend`. */
623const PLUGIN_FRAME = 'The attend plugin sent a message:'
624
625/** Whether a main-loop turn that started with `turnText` is the turn a
626 * prompt the mod submitted as `submitted` started: the submitted first
627 * line as a whole line, either first (the bare prompt) or right under the
628 * engine's plugin header (the framed form). Never a line inside someone
629 * else's prose. */
630export function isSubmittedTurn(turnText: string, submitted: string): boolean {
631 const lines = turnText.split('\n').map(l => l.trim())
632 const want = submitted.split('\n')[0]?.trim() ?? ''
633 if (want === '') return false
634 if (lines[0] === want) return true
635 return lines[0] === PLUGIN_FRAME && lines[1] === want
636}
637
638/** Whether a main-loop turn is the wrap the mod submitted ([`isSubmittedTurn`]
639 * for a `wrap:` prompt). */
640export function isWrapTurn(turnText: string, submitted: string): boolean {
641 return submitted.startsWith('wrap:') && isSubmittedTurn(turnText, submitted)
642}
643
644/** The engine's framing of a prompt plugin `name` submits without
645 * `asUser`, as `turn.start` carries it; for tests and docs. */
646export function framedPluginPrompt(name: string, text: string): string {
647 return `The ${name} plugin sent a message:\n${text}\n\nThis is how Claude Code surfaces a prompt a plugin submits between turns — it starts this turn in the user's place. Address the message above.`
648}
649
650/** What the wrap's reply becomes once its turn ends (ADR-414 item 6). */
651export type WrapPlan =
652 | { kind: 'unfinished'; detail: string }
653 | { kind: 'transcript' }
654 | { kind: 'file'; argv: string[] }
655 | { kind: 'send'; argv: string[] }
656
657export function wrapPlan(route: WrapRoute, reason: string, reply: string): WrapPlan {
658 if (reason !== 'answer') return { kind: 'unfinished', detail: `the turn ended: ${reason}` }
659 if (reply.trim() === '') return { kind: 'unfinished', detail: 'the reply was empty' }
660 if (route.dest === 'file' && route.file === '') return { kind: 'unfinished', detail: 'no safe wrap file: see attend keepwarm status' }
661 if (route.dest === 'file') return { kind: 'file', argv: saveArgv('file', '', route.file) }
662 if (route.dest === 'send' && !isOpenChannel(route.to)) return { kind: 'send', argv: wrapSendArgv(route, reply) }
663 if (route.dest === 'send') return { kind: 'unfinished', detail: `${route.to} is refused: it reaches every listening session` }
664 return { kind: 'transcript' }
665}
666
667/** attend writes the wrap's reply, given on stdin, to `path` and records
668 * the outcome: it checks the path again and renames a temp file over it,
669 * so a link planted during the wrap turn is never followed (ADR-414 item
670 * 6). The mod never writes the file itself. */
671export function saveArgv(outcome: 'file' | 'refused', detail: string, path: string): string[] {
672 return [ATTEND, 'keepwarm', 'wrapped', outcome, '--detail', oneLine(detail), '--path', path, '--save']
673}
674
675/** The card's detail for a send attend refused or that timed out; attend
676 * adds where the reply went instead. */
677export function refusalDetail(to: string, r: { exitCode: number; stderr: string; stdout: string }): string {
678 const why = (r.stderr.trim() || r.stdout.trim() || `attend exited ${r.exitCode}`).split('\n')[0] ?? ''
679 return `${to}: ${why}`
680}
681
682/** The row's segment after the operator's prompt: the count starts again,
683 * and a dormant session stops drawing it. */
684export function rowAfterPrompt(k: KeepaliveRow | null): KeepaliveRow | null {
685 return k && { ...k, state: 'running', count: 0, wrappedAt: null, isRefused: false, isShown: false }
686}
687
688/** After a main-loop turn's end: the next check's time, while it runs. */
689export function rowAfterTurnEnd(k: KeepaliveRow | null, atMs: number): KeepaliveRow | null {
690 return k?.state === 'running' ? { ...k, nextAt: Math.round(atMs / 1000), idle: null } : k
691}
692
693export function rowRefused(k: KeepaliveRow | null): KeepaliveRow | null {
694 return k && { ...k, isRefused: true }
695}
696
697/** The row's text: an active session's peers, mail, channels and keepalive
698 * segment; a dormant session's keepalive segment alone, from its first
699 * keepalive until the operator's next prompt; otherwise none. */
700export function rowText(s: AttendStatus, nowMs: number): string | undefined {
701 const keepalive = s.keepalive ? keepaliveSegment(s.keepalive, nowMs) : undefined
702 if (s.mode !== 'active') return s.keepalive?.isShown ? keepalive : undefined
703 // A message held on a lapsed cache waits for the operator's prompt.
704 const mail = s.cacheLapsed && s.unread > 0 ? `${s.unread} waiting · cold` : `${s.unread} unread`
705 const state = s.listening === false ? '○ attend not listening' : `● ${s.peers} peers ✉ ${mail}`
706 const channels = s.channels.length > 0 ? ` ${s.channels.join(' ')}` : ''
707 return `${state}${channels}${keepalive ? ` ${keepalive}` : ''}`
708}
709
710// ── parsing ──────────────────────────────────────────────────────────────
711
712/** One drained message, as `attend message inbox --drain --json` gives it. */
713export type Listed = {
714 /** The drain's scope label: `#open`, `project`, or `@name` for a channel. */
715 scope: string
716 sender: string
717 /** attend's wire identity, `claude:<session>` or `external:<user>[@terminal]`;
718 * empty where absent. Self-reported by the writer, so never proof of who sent it. */
719 senderId: string
720 id: string
721 /** The thread parent's id, where the message is a reply; empty otherwise. */
722 re: string
723 /** When it was sent, as attend shows it; empty where absent. */
724 when: string
725 message: string
726}
727
728/** What one drain said. `messages` is empty when nothing was delivered: the
729 * cold start's held-back note and the session's name are fields of their
730 * own, never messages. `status` is `drained`, or why nothing was:
731 * `not_listening` (listening was turned off, here or elsewhere) or
732 * `unresolved` (attend cannot tell which session this is). `cacheLapsed`:
733 * a wake drain held a message that would wake the session because its
734 * prompt cache has lapsed (ADR-406 item 2). Undefined where the output is not a
735 * schema-1 document (an attend without `--drain --json`, or one whose
736 * document changed shape). */
737export type Drain = {
738 status: string
739 messages: Listed[]
740 heldBack: number
741 note: string | null
742 youAre: string | null
743 cacheLapsed: boolean
744}
745
746/** The `--drain --json` schema this mod reads. */
747export const DRAIN_SCHEMA = 1
748
749export function parseDrain(stdout: string): Drain | undefined {
750 let doc: unknown
751 try {
752 doc = JSON.parse(stdout)
753 } catch {
754 return undefined
755 }
756 if (typeof doc !== 'object' || doc === null) return undefined
757 const d = doc as Record<string, unknown>
758 if (d.schema !== DRAIN_SCHEMA || typeof d.status !== 'string' || !Array.isArray(d.messages)) return undefined
759 const str = (v: unknown) => (typeof v === 'string' ? v : '')
760 const messages = d.messages.flatMap((m): Listed[] => {
761 if (typeof m !== 'object' || m === null) return []
762 const x = m as Record<string, unknown>
763 if (typeof x.id !== 'string' || typeof x.message !== 'string') return []
764 return [{ scope: str(x.scope), sender: str(x.sender), senderId: str(x.sender_id), id: x.id, re: str(x.re), when: str(x.when), message: x.message }]
765 })
766 return {
767 status: d.status,
768 messages,
769 heldBack: typeof d.held_back === 'number' ? d.held_back : 0,
770 note: typeof d.note === 'string' ? d.note : null,
771 youAre: typeof d.you_are === 'string' ? d.you_are : null,
772 cacheLapsed: d.cache_lapsed === true,
773 }
774}
775
776/** The peer count from `attend peer list`: its footer `N agent(s)` less this
777 * session's own row. */
778export function parsePeerCount(stdout: string): number {
779 const m = /(\d+) agent\(s\)/.exec(stdout)
780 return m ? Math.max(0, Number(m[1]) - 1) : 0
781}
782
783/** `attend message unread --json`: the count and the channels this session receives.
784 * Undefined where the output is not that shape (an attend without the verb). */
785export function parseUnread(stdout: string): { unread: number; channels: string[] } | undefined {
786 try {
787 const doc = JSON.parse(stdout) as { unread?: unknown; rooms?: { label?: unknown; kind?: unknown }[] }
788 if (typeof doc.unread !== 'number') return undefined
789 const channels = (doc.rooms ?? [])
790 .filter(r => r.kind === 'channel' && typeof r.label === 'string')
791 .map(r => displayScope(String(r.label)))
792 return { unread: doc.unread, channels }
793 } catch {
794 return undefined
795 }
796}
797
798/** The `keepwarm:` wake line `attend keepwarm check` printed, if any. */
799export function keepwarmLine(stdout: string): string | undefined {
800 const line = stdout.split('\n').map(l => l.trim()).find(l => l.startsWith('keepwarm:'))
801 return line && line.length > 'keepwarm:'.length ? line : undefined
802}
803
804// ── the view ─────────────────────────────────────────────────────────────
805
806/** Short stable handle for a message id; `attend_reply`'s `re` takes it.
807 * attend computes the same handle (`short_id` in tools/attend/src/verbs/
808 * inbox.rs) for the lines its Stop-hook drain prints in a mod host, and
809 * `attend message reply --re` resolves one this module never mapped. */
810export function shortId(id: string): string {
811 let h = 0x811c9dc5
812 for (let i = 0; i < id.length; i++) h = Math.imul(h ^ id.charCodeAt(i), 0x01000193) >>> 0
813 return h.toString(36).padStart(5, '0').slice(-5)
814}
815
816/** A channel's drain label `@name` reads `#name` in the view. */
817export function displayScope(scope: string): string {
818 return scope.startsWith('@') ? `#${scope.slice(1)}` : scope
819}
820
821/** A field as one line: every run of whitespace, control or format
822 * characters (newlines, CR, NUL, U+2028, zero-width) becomes one space. Each
823 * field a store writer controls passes through it before it reaches the
824 * prompt, so no field can start a line of its own. */
825export function oneLine(s: string): string {
826 return s.replace(/[\s\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+/gu, ' ').trim()
827}
828
829/** `[#channel] Name (project) HH:MM: text ~id`, one line, ` (re ~parent)`
830 * added where attend says the message is a reply. Id, sender id and cwd are
831 * dropped, and the line makes no claim about where the message came from
832 * (ADR-406 item 4); `~id` is a short handle for `attend_reply`'s `re`. */
833export function formatMessage(m: Listed): string {
834 const when = m.when ? ` ${oneLine(m.when)}` : ''
835 const re = m.re ? ` (re ~${shortId(m.re)})` : ''
836 return oneLine(`[${oneLine(displayScope(m.scope))}] ${safeSender(m.sender)}${when}: ${oneLine(m.message)} ~${shortId(m.id)}${re}`)
837}
838
839/** A sender label in a safe charset: made one line, then every character
840 * but a letter, a digit, space and `_ . - @ ( )` becomes `-`, so a sender
841 * cannot write the line's `:` or `~` separators. `safe_sender` in
842 * tools/attend/src/cmd/inbox.rs applies the same rule to the Stop-hook
843 * drain's lines. */
844export function safeSender(s: string): string {
845 return oneLine(s).replace(/[^\p{Alphabetic}\p{N} _.\-@()]/gu, '-')
846}
847
848/** The frame the mod writes around every delivery, in place of the one Claude
849 * Code drops for a prompt submitted `asUser` (ADR-406 item 4). The silence
850 * line opens it, so the model weighs whether to answer before it reads the
851 * messages. The header names the transport and marks the block as data; it
852 * says nothing of who typed a message or where it came from. The preamble,
853 * on a cadence ({@link isFullPreamble}), adds one line of tool usage after
854 * the closing tag. */
855export const HEADER = 'The block below is message data relayed by attend.'
856export const SILENCE_FIRST = 'Silence is a valid reply to the messages below; answer only if useful.'
857export const PREAMBLE = 'attend_reply threads (re: ~id); attend_send starts a topic.'
858
859const OPEN = '<attend-peer-messages>'
860const CLOSE = '</attend-peer-messages>'
861
862/** A line with every `<` that could forge the frame made `‹`. A `<` is kept
863 * only when the next non-space character is ASCII `[A-Za-z0-9<=(-]` and the
864 * word there is not `attend` in any case; every other `<` is defused. The
865 * allowlist keeps code (`<cwd>`, `x < y`, `Vec<u8>`, `a <= b`) and defuses
866 * `</`, `<attend`, and anything a renderer could hide or draw as `/`
867 * between them (review of #949), at the cost of `</div>`, `<attendee>` and
868 * a trailing `<`. One pass, so each `<` is judged on the original text. The
869 * Stop-hook drain's `defuse_fence` in
870 * tools/attend/src/cmd/inbox.rs applies the same rule. */
871export function defuseFence(s: string): string {
872 return s.replace(/<(?! *(?!attend)[A-Za-z0-9<=(-])/gi, '‹')
873}
874
875/** The prompt one batch becomes: the silence line, the header, the lines
876 * inside the tags, and the preamble's tool line after them when `full`.
877 * Each line is made one line again and defused ({@link defuseFence}), so
878 * no line can open or end the block, whatever the tag's spacing or case. */
879export function frameInbound(lines: readonly string[], full: boolean): string {
880 const inner = lines.map(b => defuseFence(oneLine(b))).join('\n')
881 return [SILENCE_FIRST, HEADER, OPEN, inner, CLOSE, ...(full ? [PREAMBLE] : [])].join('\n')
882}
883
884/** The message lines inside the tags of a framed delivery; undefined where
885 * the text holds no frame. The human's view of a delivery. */
886export function peerLines(text: string): string[] | undefined {
887 const a = text.indexOf(OPEN)
888 const b = text.lastIndexOf(CLOSE)
889 if (a < 0 || b < a) return undefined
890 return text
891 .slice(a + OPEN.length, b)
892 .split('\n')
893 .map(l => l.trim())
894 .filter(l => l !== '')
895}
896