SLOPSHOPPER

harnu-companion

Harnu's companion mod: a sensor that reports session facts to the Harnu app on this machine.

bandguardprompttimer
★ 2v0.1.0MITupdated 2026-10-23junielton/harnu/resources/companion
A shopper browsing a rack in a slop shop
README

Harnu

Harnu — Manage every Claude Code session in one place.

A desktop app that turns the sprawl of running and idle Claude Code sessions into a single browsable workspace.

Not affiliated with Anthropic. Harnu is an independent, unofficial project. It is not affiliated with, endorsed by, or sponsored by Anthropic. "Claude" and "Claude Code" are trademarks of Anthropic, PBC.

What it is

Harnu is a cross-platform Electron + Vue 3 desktop app. It reads ~/.claude/projects/, where Claude Code persists every session as JSONL, and renders it as a sidebar of folders with their sessions underneath; folders that are worktrees of the same repo are grouped together. Click a past session to resume it via claude --resume <uuid>; click "new session" to spawn claude in the chosen folder's cwd. Renames issued inside Claude (via /rename) propagate back to the sidebar live through a filesystem watcher. No daemon, no cloud, no account — the app is a faithful UI over files that already exist on disk.

Features

  • Sessions in one place — resume any past Claude Code session or start a new one, grouped by folder and git worktree, with live status (working / needs input / stuck / idle) right in the sidebar.
  • Approval Inbox — every action an agent takes through Harnu's control server surfaces in one rail for your say-so instead of scattered terminal prompts (Claude Code's own permission prompts join it only if you switch the opt-in Interceptor to Active in Settings → Interceptor; it ships in log-only Shadow mode, which never changes a session); grant a whole batch of actions at once or allow a verb durably per folder.
  • Git worktrees — spin up an isolated worktree for a task straight from Harnu, seeded via a repo's own WORKTREE.md manifest so it's usable immediately instead of a bare checkout.
  • Project memory — a per-repo .harnu/memory/ spotlight (hot state, decisions, roadmap) that every session and worktree shares, browsable from a built-in pane.
  • Roadmap board — a kanban for the project's backlog with agent-authored cards, a dispatch manifest gate, and configurable model routing per card kind.
  • Claude Boot — per-folder launch options (model, effort, flags, custom Claude-compatible endpoints).
  • Usage dashboard — plan usage at a glance plus a full history/cost breakdown across sessions.
  • MCP control server — lets a session act on the fleet itself (create sessions/worktrees, read project memory, manage the roadmap) through a typed tool catalog, gated by the Approval Inbox.

See the user guide for how to use all of this — start with Getting started if this is your first time running Harnu.

Status

Still in alpha — no signing, no notarization. The binaries are unsigned on every platform. Expect Gatekeeper (macOS) and SmartScreen (Windows) to block the first launch. See the platform notes below for the bypass per OS.

The data plane, terminal pipeline, shortcuts, and command palette are wired. Auto-update applies silently on AppImage; unsigned macOS/Windows builds get an in-app "Update available" toast linking to the release page instead (the OS won't let an unsigned build apply an update silently). The .deb doesn't auto-update at all.

Requirements

  • Claude Code: the claude CLI installed, on your PATH, and logged in. Harnu runs your own claude; it does not bundle or replace it.
  • git, for the worktree features.
  • GitHub CLI (gh), optional, logged in, for the pull-request features (PR Stack, Review, Cleanup).

Install

Download the build for your platform from the releases page.

Linux

sudo dpkg -i harnu_*_amd64.deb
# or
chmod +x Harnu-*.AppImage
./Harnu-*.AppImage

macOS

Drag the .dmg to Applications. On first launch Gatekeeper will refuse to open it. Either:

xattr -d com.apple.quarantine "/Applications/Harnu.app"

Or right-click the app in Finder and choose Open — macOS then offers a one-time exception.

Windows

Run the .exe installer. SmartScreen will show "Windows protected your PC". Click More info → Run anyway to proceed. Subsequent launches are clean.

Network activity

Harnu is a local-first app — there is no Harnu backend, no account, and no telemetry, analytics, or crash reporting. Every outbound call Harnu (or a tool it runs for you) makes is listed below. Anything that reaches Anthropic goes through your own claude CLI and your own login; Harnu holds no Anthropic credentials of its own. Git and GitHub features run through your own git and gh, so the hosts they contact are whatever your remotes and gh login point at.

Automatic (no action from you):

DestinationPurposeWhen
status.claude.comShows the current Claude service incident state.Always: every 60 s while a window is focused, every 5 min in the background.
raw.githubusercontent.comFetches the official Claude Code changelog and notifies you of new versions.Always: every 30 min, whether or not Settings is open.
Anthropic, via claude -p /usageReads your plan-usage meters for the footer. Sends no prompt content.Immediately on focus, then every 90 s while a window is focused.
GitHub Releases (github.com / objects.githubusercontent.com)Update check. AppImage builds download and apply silently; macOS/Windows builds only show a toast linking to the release page. The .deb is managed by apt and is not replaced in place.Packaged builds only: 5 s after launch, then hourly.
Your git remotes (git ls-remote) and GitHub via your gh (gh pr list)Cleanup (Reaper) scan: which branches and worktrees are merged and safe to clean up. Read-only.Default on, hourly. Change the interval or turn it off in Settings → Cleanup.
GitHub via your gh (gh pr list)Pull-request state for PRs linked to an open Mission.While a Mission with linked PRs is open.

On your action:

DestinationPurposeWhen
Your git remote (git fetch)Fetches a base branch when you create a worktree, and a PR head for the Review pane.When you create a worktree or open a PR in Review.
Your git remote (git push --delete)Cleanup deletes a merged remote branch.Only after you confirm a sweep; can be disabled with neverDeleteRemote.
GitHub via your ghPR Stack, Review pane (including submitting a review), and Cleanup PR lookups.When you open those views or click.
Anthropic, via your claude CLIUsage history Ask sends your question plus aggregated usage figures.When you submit a question.
Anthropic (or your custom endpoint), via your claude CLIThe Claude Code sessions themselves, including Scheduler workers you created and enabled.When you start or resume a session, or a worker you enabled runs.
cdn.jsdelivr.net and huggingface.coOne-time download of the offline voice engine (about 120 MB for the default voice).Only when you click install in Settings → Voice. Afterwards it runs offline.

Opt-in:

DestinationPurposeWhen
Anthropic, via your claude CLIAuto-name sends the first user prompt of a new session to Haiku to name it. Off by default.Once per new session, only if enabled in Settings → Intelligence.
The ntfy topic or webhook URL you configureRemote push notifications. The payload is the notification title and body, which can include the session name or summary. Off by default.Only after you add a channel; goes only to the URL you enter.

Your configuration:

DestinationPurposeWhen
The custom ANTHROPIC_BASE_URL endpoint you setPoints your claude sessions at an alternate Claude-compatible server (Settings → Endpoints). Harnu only sets the environment variable; the CLI makes the call.Only if you set one.

Everything else — reading ~/.claude/projects/, spawning claude, the terminal pipeline — stays on your machine.

Stored credentials

Custom-endpoint auth tokens (for alternate Claude-compatible endpoints) are stored in plaintext in claude-boot.json inside the app's userData directory. They are not encrypted at rest — treat that file as sensitive.

Development

npm install
npm run dev

npm install rebuilds node-pty for the Electron ABI via the postinstall hook. npm run dev starts electron-vite with HMR for the main, preload, and renderer processes.

npm run build       # full production build (typecheck + electron-vite build)
npm run typecheck   # both: typecheck:node and typecheck:web
npm run build:linux # electron-builder for .deb + AppImage
npm run build:mac   # electron-builder for .dmg
npm run build:win   # electron-builder for NSIS .exe

Live-verify a change in the real app (without disturbing a running instance)

To prove a change works end-to-end against the actual app — even while another Harnu (an AppImage or npm run dev) is already running — launch a second, isolated instance (its own --user-data-dir bypasses the single-instance lock; an alternate --remote-debugging-port avoids CDP collisions), drive it over the DevTools Protocol, and inspect what it wrote to disk. Full reproducible recipe (including the is.dev renderer-URL gotcha and safe teardown) is in docs/dev/live-verify-second-instance.md.

Architecture

ARCHITECTURE.md maps the three Electron processes and where code lives. design.md is the visual system, the single source of truth for tokens and components. CHANGELOG.md is the release history, and docs/ holds the user guide, ADRs and engineering notes. CLAUDE.md is the same contract written for AI coding agents working in this repo.

Project layout

src/main/        — Electron main process (PTY, watcher, IPC, MCP control server)
src/preload/     — typed contextBridge API
src/renderer/    — Vue 3 app (sidebar, terminal, dialogs, palette)
tests/           — Vitest unit tests and Playwright e2e
docs/            — user guide, ADRs, lessons, specs
scripts/         — CI gates and generators
build/           — packaging assets (icons, entitlements)
resources/       — runtime assets shipped with the app (icon, bundled skills, templates)

Contributing

Contributions are welcome. Start with CONTRIBUTING.md: it covers setup, the conventions the CI gates enforce, and what a pull request needs. Everyone taking part follows the Code of Conduct. Report security issues privately, as described in SECURITY.md.

The project was developed in a private repository before its public release. That history was not carried over; this repository starts from a single initial commit, and the design decisions it holds are recorded in the ADRs and the changelog.

License

MIT. See LICENSE. Third-party software and assets bundled with the app are listed in THIRD-PARTY-NOTICES.md.

Source 10 files
hooks/register.ts 1555 lines
1import type { EngineInterface, Register } from 'claude-code'
2import {
3  BACKOFF_MAX_MS,
4  BACKOFF_MIN_MS,
5  BYE_BUDGET_MS,
6  DEFAULT_CONFIG,
7  FETCH_HARD_CAP_MS,
8  HEARTBEAT_MS,
9  HELLO_WAIT_MS,
10  DRIFT_CHECK_MIN_MS,
11  PROTOCOL_VERSION,
12  RING_MAX,
13  type ByeRequest,
14  type CmdId,
15  type Command,
16  type CommandResultData,
17  type Config,
18  type Conn,
19  type EndpointName,
20  type EventName,
21  type EventPayloads,
22  type EventsRequest,
23  type ErrorCode,
24  type FeatureId,
25  type HelloRequest,
26  type Sid
27} from './contract'
28import { MOD_VERSION, RENDEZVOUS_PATH } from './coords.gen'
29import {
30  neutralFleet,
31  originOf,
32  sanitizeFleet,
33  snapshotFields,
34  step as fleetStep,
35  type FleetSensorState,
36  type SensorInput
37} from './lib/fleet-sensor'
38import {
39  applyBand,
40  bandFeatures,
41  bandLive,
42  classifyCommand,
43  compactData,
44  forBoot,
45  isHardCapAbort,
46  mapEngineRejection,
47  markResulted,
48  markStarted,
49  parseChannel,
50  parseBandSet,
51  parseBandState,
52  parseCommands,
53  parseConfigUpdate,
54  parseContextAppend,
55  BAND_SWEEP_MS,
56  IMPLEMENTED_COMMANDS,
57  UI_TEXT_MAX,
58  withCursor,
59  type ChannelState
60} from './lib/command-core'
61import { toAdmitted, type Admitted } from './lib/admitted'
62import { createRing } from './lib/ring'
63import { bandView } from './surface'
64import { measurePayload, readPayload } from './lib/usage-sensor'
65import { endpointUrl, parseEndpoint, type Endpoint } from './lib/rendezvous-parse'
66
67/**
68 * The Harnu companion mod: the handshake and the identity facts (spec P1W3) and the fleet
69 * sensors (spec P1W5: turns, attention, subagents; the cores are in `lib/fleet-sensor.ts`).
70 *
71 * Every function that takes `$` is declared here, at the top of the module (MOD-1); helpers under
72 * `lib/` are `$`-free. Every hook body is wrapped and ends in `next(e)`: a failure here must never
73 * show in the session (MOD-2, SEC-1). Nothing is awaited on a turn's path except the first hello
74 * (bounded by HELLO_WAIT_MS) and the one `bye`.
75 */
76
77type Dollar = EngineInterface
78type Timer = { cancel: () => void }
79type Boot = { cwd: string; surface: string | null; isInteractive: boolean }
80type Probes = { classic: boolean; toolCheck: boolean }
81
82const CONN = { plugin: 'harnu-companion', key: 'conn' } as const
83const BOOT_ID = { plugin: 'harnu-companion', key: 'bootId' } as const
84const SID = { plugin: 'harnu-companion', key: 'sid' } as const
85const BOOT = { plugin: 'harnu-companion', key: 'boot' } as const
86const PROBES = { plugin: 'harnu-companion', key: 'probes' } as const
87const FLEET = { plugin: 'harnu-companion', key: 'fleet' } as const
88const PERMISSION_MODE = { plugin: 'harnu-companion', key: 'permissionMode' } as const
89const CHANNEL = { plugin: 'harnu-companion', key: 'channel' } as const
90const BAND = { plugin: 'harnu-companion', key: 'band' } as const
91
92/** The feature an event type belongs to. `null`: reportable whenever the channel is alive. */
93const EVENT_FEATURE: Partial<Record<EventName, FeatureId | null>> = {
94  'session.snapshot': 'sense.identity',
95  'session.rebound': 'sense.identity',
96  'session.end': 'sense.identity',
97  'turn.started': 'sense.turn',
98  'turn.completed': 'sense.turn',
99  'attention.raised': 'sense.attention',
100  'attention.cleared': 'sense.attention',
101  'subagent.started': 'sense.subagent',
102  'subagent.stopped': 'sense.subagent',
103  'usage.measured': 'sense.usage',
104  'mod.admitted': 'sense.mods',
105  'mod.error': null,
106  // The answer to a command is owed whatever the command's own feature says (also FEATURE_DISABLED).
107  'command.result': null
108}
109
110// ---- module state: wiped by a reload; the durable twins live in `$.state` ---------------------
111
112let conn: Conn | null = null
113let bootId: string | null = null
114let proto = PROTOCOL_VERSION
115let enabledSet: FeatureId[] = []
116let config: Config = { ...DEFAULT_CONFIG }
117let sidBound: Sid | null = null
118let boot: Boot | null = null
119let probes: Probes = { classic: false, toolCheck: false }
120let declared: FeatureId[] = []
121let dormant = false
122let inert = false
123/** P4W3: no spawn token, so Harnu did not start this process: the external claim (contract §21). */
124let tokenless = false
125let helloFlight: Promise<void> | null = null
126let retryBlocked = false
127let retryTimer: Timer | null = null
128let backoffMs = BACKOFF_MIN_MS
129let heartbeat: Timer | null = null
130let sentSinceBeat = false
131let driftBlocked = false
132/** The model of the last `usage.measured` read: `/model` has no event, so a beat compares (T577). */
133let lastModel: string | null = null
134let endpoint: Endpoint | null = null
135let pumpFlight: Promise<void> | null = null
136let pumpKick = false
137let registrationErrors: string[] = []
138let ring = createRing(RING_MAX)
139let fleet: FleetSensorState = neutralFleet()
140let fleetLoaded = false
141let lastMode: string | null = null
142/** P2W1: the poll loop's generation; a re-hello starts a new loop and retires the old one. */
143let loopGen = 0
144/** True when this process was spawned by Harnu with a token (the tokenless second lock). */
145let tokenBacked = false
146/** The in-memory twin of `$.state.channel`; null until first read. */
147let channel: ChannelState | null = null
148let stateChain: Promise<unknown> = Promise.resolve()
149/** Command ids a running call of THIS load will answer. */
150const inFlight = new Set<string>()
151/** T257: the highest `ui.band.set` `n` this load has applied; a lower one never overwrites it. */
152let bandN = 0
153let bandTimer: Timer | null = null
154/** Band writes run one at a time, so two commands cannot apply out of order. */
155let bandChain: Promise<unknown> = Promise.resolve()
156
157/** Modules admitted before the hello answered (the usual case: they load before `session.start`). */
158let pendingAdmitted: Admitted[] = []
159
160/** At most this many admissions wait for the first hello; a session loads a handful of mods. */
161const PENDING_ADMITTED_MAX = 64
162
163function resetState(): void {
164  conn = null
165  bootId = null
166  proto = PROTOCOL_VERSION
167  enabledSet = []
168  config = { ...DEFAULT_CONFIG }
169  sidBound = null
170  boot = null
171  probes = { classic: false, toolCheck: false }
172  declared = []
173  dormant = false
174  inert = false
175  tokenless = false
176  helloFlight = null
177  retryBlocked = false
178  retryTimer = null
179  backoffMs = BACKOFF_MIN_MS
180  heartbeat = null
181  sentSinceBeat = false
182  driftBlocked = false
183  endpoint = null
184  pumpFlight = null
185  pumpKick = false
186  registrationErrors = []
187  ring = createRing(RING_MAX)
188  fleet = neutralFleet()
189  fleetLoaded = false
190  lastMode = null
191  loopGen = 0
192  tokenBacked = false
193  channel = null
194  stateChain = Promise.resolve()
195  inFlight.clear()
196  bandN = 0
197  bandTimer = null
198  bandChain = Promise.resolve()
199  pollStale = 0
200  pendingAdmitted = []
201}
202
203// ---- runtime helpers other waves call ---------------------------------------------------------
204
205/** The bound sid of contract §15: what the envelope carries. */
206function boundSid(): Sid | null {
207  return sidBound
208}
209
210/** False when dormant or inert. */
211function enabled(feature: FeatureId): boolean {
212  return !dormant && !inert && conn !== null && enabledSet.includes(feature)
213}
214
215/** Queues into the ring and starts the pump. Never awaited on a turn's path. */
216function emit<N extends EventName>(
217  $: Dollar,
218  ev: { t: N; d: EventPayloads[N]; turnId?: string; agentId?: string }
219): void {
220  if (dormant || inert || conn === null) return
221  const feature = EVENT_FEATURE[ev.t]
222  if (feature === undefined) return
223  if (feature !== null && !enabledSet.includes(feature)) return
224  ring.push({
225    t: ev.t,
226    ts: Date.now(),
227    d: ev.d,
228    ...(ev.turnId !== undefined ? { turnId: ev.turnId } : {}),
229    ...(ev.agentId !== undefined ? { agentId: ev.agentId } : {})
230  })
231  pump($)
232}
233
234/**
235 * Wraps a caught error as `mod.error` (message capped at 512 chars). It needs no `$`: the event
236 * goes into the ring and the next pump or heartbeat sends it (`$` is never stored, MOD-1).
237 */
238function reportModError(where: string, err: unknown, cmd?: CmdId): void {
239  if (dormant || inert || conn === null) return
240  const raw = err instanceof Error ? err.message : String(err)
241  ring.push({
242    t: 'mod.error',
243    ts: Date.now(),
244    d: { where, kind: 'throw', message: raw.slice(0, 512), ...(cmd !== undefined ? { cmd } : {}) }
245  })
246}
247
248// ---- transport --------------------------------------------------------------------------------
249
250type Posted =
251  | { kind: 'answer'; body: Record<string, unknown> }
252  | { kind: 'transport'; aborted?: boolean }
253  | { kind: 'rebooted' }
254
255async function readEndpoint($: Dollar): Promise<Endpoint | null> {
256  try {
257    const raw = await $.fs.read(RENDEZVOUS_PATH)
258    return parseEndpoint(typeof raw === 'string' ? raw : '', RENDEZVOUS_PATH)
259  } catch {
260    return null
261  }
262}
263
264/**
265 * One POST. The endpoint is cached only until the first failure (contract §2.5: never cache
266 * coordinates across a failure). A changed `bootId` read after a failure means the host restarted:
267 * the caller resumes, exactly as for STALE_CONN.
268 */
269async function post(
270  $: Dollar,
271  route: EndpointName,
272  body: unknown,
273  ignoreBoot: boolean
274): Promise<Posted> {
275  let ep = endpoint
276  if (ep === null) {
277    ep = await readEndpoint($)
278    if (ep === null) return { kind: 'transport' }
279    if (!ignoreBoot && bootId !== null && ep.bootId !== bootId) {
280      endpoint = ep
281      return { kind: 'rebooted' }
282    }
283    endpoint = ep
284  }
285  try {
286    const res = await $.http.fetch(endpointUrl(ep, route), {
287      method: 'POST',
288      headers: { 'content-type': 'application/json', authorization: `Bearer ${ep.token}` },
289      body: JSON.stringify(body),
290      ...(ep.socketPath !== undefined ? { socketPath: ep.socketPath } : {})
291    })
292    if (res.status !== 200) {
293      endpoint = null
294      return { kind: 'transport' }
295    }
296    const parsed: unknown = JSON.parse(res.text)
297    if (
298      typeof parsed !== 'object' ||
299      parsed === null ||
300      typeof (parsed as { ok?: unknown }).ok !== 'boolean'
301    ) {
302      endpoint = null
303      return { kind: 'transport' }
304    }
305    return { kind: 'answer', body: parsed as Record<string, unknown> }
306  } catch (err) {
307    // The engine's 30 s fetch cap on a held poll is a normal reconnect: the coordinates are fine.
308    if (isHardCapAbort(err)) return { kind: 'transport', aborted: true }
309    endpoint = null
310    return { kind: 'transport' }
311  }
312}
313
314/** Resolves when `p` settles or after `ms`, whichever comes first. `p` is never cancelled. */
315function raceWithTimer($: Dollar, p: Promise<unknown>, ms: number): Promise<void> {
316  return new Promise<void>((resolve) => {
317    let timer: Timer | null = null
318    const finish = (): void => {
319      timer?.cancel()
320      resolve()
321    }
322    timer = $.clock.after(ms, () => resolve())
323    p.then(finish, finish)
324  })
325}
326
327/** Arms one retry timer. Retries are driven by this timer, by the next hook and by the heartbeat. */
328function scheduleRetry($: Dollar, afterMs?: number): void {
329  endpoint = null
330  retryBlocked = true
331  const wait = Math.min(Math.max(afterMs ?? backoffMs, 0), 60_000)
332  backoffMs = Math.min(backoffMs * 2, BACKOFF_MAX_MS)
333  retryTimer?.cancel()
334  retryTimer = $.clock.after(wait, () => {
335    retryBlocked = false
336    retryTimer = null
337    resumeWork($)
338  })
339}
340
341function resumeWork($: Dollar): void {
342  if (dormant || inert) return
343  if (conn === null) void ensureHello($)
344  else pump($)
345}
346
347function goDormant(): void {
348  dormant = true
349  retryTimer?.cancel()
350  retryTimer = null
351  heartbeat?.cancel()
352  heartbeat = null
353  ring.clear()
354  pendingAdmitted = []
355}
356
357// ---- hello ------------------------------------------------------------------------------------
358
359const DORMANT_CODES: ReadonlySet<string> = new Set([
360  'PROTO_UNSUPPORTED',
361  'UNAUTHORIZED',
362  'UNKNOWN_SESSION',
363  'FEATURE_DISABLED'
364])
365
366function snapshot($: Dollar, reason: EventPayloads['session.snapshot']['reason']): void {
367  emit($, {
368    t: 'session.snapshot',
369    d: {
370      reason,
371      ...snapshotFields(fleet),
372      probes: { classic: probes.classic, toolCheck: probes.toolCheck }
373    }
374  })
375  // A state re-send after a hello, a resync or a flush (`sense.usage`, P1W6 §7.1). Un-awaited.
376  if (reason !== 'probe') void readUsage($)
377}
378
379/**
380 * `$.session.usage()` and `$.session.model()` as one `usage.measured {source: 'read'}`. Never on a
381 * turn's path (MOD-6): callers do not await it. A rejected call is a `mod.error`, not a retry.
382 */
383async function readUsage($: Dollar): Promise<void> {
384  if (!enabled('sense.usage')) return
385  try {
386    // The model is noted as soon as it is known, even if the usage read then throws: the
387    // watcher must not turn one rejected read into a read on every beat.
388    const modelRead = $.session.model().then((m) => {
389      if (typeof m === 'string' && m !== '') lastModel = m
390      return m
391    })
392    const [usage, model] = await Promise.all([$.session.usage(), modelRead])
393    emit($, { t: 'usage.measured', d: readPayload(usage, model) })
394  } catch (err) {
395    reportModError('session.usage', err)
396  }
397}
398
399/**
400 * One heartbeat's look at `$.session.model()`. No hook fires on `/model` (`session.measure` moves
401 * on context, rate limits and cost only), so a changed model is sent as a full read and the footer
402 * follows within one beat instead of waiting for the next turn. Never on a turn's path (MOD-6).
403 */
404async function watchModel($: Dollar): Promise<void> {
405  if (!enabled('sense.usage')) return
406  try {
407    const model = await $.session.model()
408    if (typeof model !== 'string' || model === '' || model === lastModel) return
409    await readUsage($)
410  } catch {
411    // advisory, like the drift check: a failed look changes nothing and is not reported every beat
412  }
413}
414
415// ---- fleet sensors (P1W5) ---------------------------------------------------------------------
416
417const noop = (): void => undefined
418
419/** Once per load: what a reload left in `$.state`, made safe. In-memory changes always win. */
420async function loadFleet($: Dollar): Promise<void> {
421  if (fleetLoaded) return
422  fleetLoaded = true
423  try {
424    const saved = await $.state.get(FLEET)
425    fleet = sanitizeFleet(saved.value)
426  } catch {
427    // an unreadable key reads as the neutral state
428  }
429}
430
431function persistFleet($: Dollar): void {
432  void Promise.resolve($.state.set(FLEET, fleet)).catch(noop)
433}
434
435/** True while at least one of the three sensor features is enabled. */
436function senseOn(): boolean {
437  return enabled('sense.turn') || enabled('sense.attention') || enabled('sense.subagent')
438}
439
440/** Runs one step of the core and emits what it returns. A throw is the caller's to catch (MOD-2). */
441function feed($: Dollar, input: SensorInput): void {
442  if (!senseOn()) return
443  const before = JSON.stringify(fleet)
444  const out = fleetStep(fleet, input)
445  fleet = out.state
446  if (JSON.stringify(fleet) !== before) persistFleet($)
447  for (const ev of out.events) emit($, ev as never)
448}
449
450/** The first step of every `classic.*` body: the probe, and the last `permission_mode` (§11.4). */
451function noteClassic($: Dollar, e: { permission_mode?: string }): void {
452  if (!probes.classic) {
453    probes = { ...probes, classic: true }
454    void Promise.resolve($.state.set(PROBES, probes)).catch(noop)
455    if (conn !== null) snapshot($, 'probe')
456  }
457  const mode = e.permission_mode
458  if (typeof mode === 'string' && mode !== '' && mode !== lastMode) {
459    lastMode = mode
460    void Promise.resolve($.state.set(PERMISSION_MODE, mode)).catch(noop)
461  }
462}
463
464/** `tool.check` was dispatched for a real call (one with an id), whatever its verdict. */
465function noteToolCheck($: Dollar): void {
466  if (probes.toolCheck) return
467  probes = { ...probes, toolCheck: true }
468  void Promise.resolve($.state.set(PROBES, probes)).catch(noop)
469  if (conn !== null) snapshot($, 'probe')
470}
471
472/** Sends what waited for the hello, when `sense.mods` is enabled; otherwise forgets it. */
473function flushAdmitted($: Dollar): void {
474  const held = pendingAdmitted
475  pendingAdmitted = []
476  if (!enabledSet.includes('sense.mods')) return
477  for (const d of held) emit($, { t: 'mod.admitted', d })
478}
479
480/**
481 * One module the engine admitted after this one. Sent at once when the channel is already up,
482 * otherwise held for the first hello. Never throws and never needs a conn.
483 */
484function noteAdmitted($: Dollar, input: unknown): void {
485  if (dormant || inert) return
486  const d = toAdmitted(input)
487  if (d === null) return
488  if (conn !== null) {
489    emit($, { t: 'mod.admitted', d })
490    return
491  }
492  pendingAdmitted = pendingAdmitted.filter((p) => p.root !== d.root)
493  pendingAdmitted.push(d)
494  if (pendingAdmitted.length > PENDING_ADMITTED_MAX) pendingAdmitted.shift()
495}
496
497async function persistConn($: Dollar): Promise<void> {
498  if (conn === null) return
499  try {
500    await $.state.set(CONN, conn)
501    if (bootId !== null) await $.state.set(BOOT_ID, bootId)
502    if (sidBound !== null) await $.state.set(SID, sidBound)
503  } catch {
504    // a failed write only costs a reload its resume: it then goes dormant (OQ-6)
505  }
506}
507
508function startHeartbeatOnce($: Dollar): void {
509  if (heartbeat !== null) return
510  heartbeat = $.clock.every(Math.max(1, config.heartbeatMs || HEARTBEAT_MS), () => void beat($))
511}
512
513/**
514 * Single flight. `resumeConn` is the conn a STALE_CONN just invalidated; `fresh` skips every
515 * resume (a tokenless claim after the host forgot us). Never rejects.
516 */
517async function doHello($: Dollar, resumeConn?: Conn, fresh = false): Promise<void> {
518  try {
519    let resume: Conn | undefined = fresh ? undefined : resumeConn
520    if (boot === null) {
521      const b = await $.state.get(BOOT)
522      if (b.value) boot = b.value
523    }
524    // Who claims (contract §21 item 1): decided once per load, from the env and `isInteractive`.
525    const token = await $.env.get('HARNU_SPAWN_TOKEN')
526    tokenless = typeof token !== 'string' || token === ''
527    if (tokenless && boot !== null && !boot.isInteractive) {
528      // Harnu's own `claude -p` probes, CI and scripts: not one request, and no delay at exit
529      // (smoke C2, ADR C6).
530      goDormant()
531      return
532    }
533    tokenBacked = !tokenless
534    await loadFleet($) // a reload re-sends a correct snapshot (MOD-4)
535    if (resume === undefined && !fresh) {
536      const saved = await $.state.get(CONN)
537      if (saved.value) resume = saved.value
538    }
539    const request: Partial<HelloRequest> = {}
540    let sid: Sid | null
541    if (resume !== undefined) {
542      sid = sidBound ?? (await $.state.get(SID)).value ?? null
543      if (sid === null) sid = await $.session.id()
544      const p = await $.state.get(PROBES)
545      if (p.value)
546        probes = {
547          classic: probes.classic || p.value.classic,
548          toolCheck: probes.toolCheck || p.value.toolCheck
549        }
550      request.resume = { conn: resume }
551    } else {
552      if (tokenless) {
553        // The external claim: neither `spawn` nor `resume`. A claim proves nothing; the host
554        // shows it only once its own watchers corroborate the session.
555        sid = await $.session.id()
556      } else {
557        sid = await $.session.id()
558        request.spawn = token as `sp_${string}`
559      }
560    }
561    if (boot === null) return // no session.start yet: the next hook tries again
562    // The headless guard again, now that `boot` is known for certain: `classic.SessionStart`
563    // dispatches BEFORE `session.start` on a real CLI, so an early `doHello` can pass the first
564    // check with `boot` still null and find it set by the time it reaches the network.
565    if (tokenless && !boot.isInteractive) {
566      goDormant()
567      return
568    }
569    const cli = await $.session.version()
570    const hello: HelloRequest = {
571      protoMin: PROTOCOL_VERSION,
572      protoMax: PROTOCOL_VERSION,
573      sid,
574      ...request,
575      cli: { version: cli.version },
576      mod: { version: MOD_VERSION },
577      surface: boot.surface,
578      isInteractive: boot.isInteractive,
579      cwd: boot.cwd,
580      declared: [...declared],
581      sentAt: Date.now()
582    }
583    const r = await post($, 'hello', hello, true)
584    if (r.kind !== 'answer') {
585      scheduleRetry($)
586      return
587    }
588    const b = r.body
589    if (b.ok !== true) {
590      const code = typeof b.code === 'string' ? b.code : ''
591      if (tokenless && code === 'UNKNOWN_SESSION' && request.resume !== undefined) {
592        // Harnu restarted (it does on every update): a tokenless mod has no token to protect, so
593        // it claims again, once, instead of going dormant (contract §21 item 7).
594        await $.state.set(CONN, undefined as never).catch(() => undefined)
595        return doHello($, undefined, true)
596      }
597      // An invalid claim never becomes valid: stop asking (SEC-3c).
598      if (DORMANT_CODES.has(code) || (tokenless && code === 'BAD_ENVELOPE')) {
599        goDormant()
600        return
601      }
602      scheduleRetry($, typeof b.retryAfterMs === 'number' ? b.retryAfterMs : undefined)
603      return
604    }
605    if (
606      typeof b.conn !== 'string' ||
607      typeof b.bootId !== 'string' ||
608      typeof b.proto !== 'number' ||
609      !Array.isArray(b.enable)
610    ) {
611      scheduleRetry($)
612      return
613    }
614    conn = b.conn as Conn
615    bootId = b.bootId
616    proto = b.proto
617    enabledSet = (b.enable as unknown[]).filter((f): f is string => typeof f === 'string')
618    config = { ...DEFAULT_CONFIG, ...pickConfig(b.config) }
619    sidBound = sid
620    backoffMs = BACKOFF_MIN_MS
621    retryBlocked = false
622    ring.renumber()
623    await persistConn($)
624    if (enabledSet.length === 0) {
625      // inert: behave as if no feature exists, keep `conn` so a revoked one can resume
626      inert = true
627      retryTimer?.cancel()
628      retryTimer = null
629      heartbeat?.cancel()
630      heartbeat = null
631      ring.clear()
632      pendingAdmitted = []
633      return
634    }
635    for (const where of registrationErrors.splice(0)) {
636      emit($, {
637        t: 'mod.error',
638        d: { where, kind: 'registration', message: 'hook registration failed' }
639      })
640    }
641    snapshot($, 'hello')
642    flushAdmitted($)
643    startHeartbeatOnce($)
644    pump($)
645    // P2W1: the cursor belongs to this boot; the loop starts (or restarts) under a new generation.
646    const prior = await ensureChannel($)
647    channel = forBoot(prior, bootId)
648    // A new boot numbers its commands from 1 again: what this load remembers of the old one (the
649    // highest `n`, the standing line) belongs to a queue that no longer exists.
650    if (channel !== prior) resetBand($)
651    void writeChannel($)
652    restartPollLoop($)
653    await acceptCommands($, parseCommands(b.commands))
654  } catch (err) {
655    scheduleRetry($)
656    void err
657  }
658}
659
660function pickConfig(raw: unknown): Partial<Config> {
661  const out: Partial<Config> = {}
662  if (typeof raw !== 'object' || raw === null) return out
663  for (const k of Object.keys(DEFAULT_CONFIG) as (keyof Config)[]) {
664    const v = (raw as Record<string, unknown>)[k]
665    if (typeof v === 'number' && Number.isFinite(v) && v > 0) out[k] = v
666  }
667  return out
668}
669
670/** At the head of every hook. A no-op with a conn in memory; bounded when it has to ask. */
671async function ensureHello($: Dollar): Promise<void> {
672  if (dormant || inert) return
673  if (conn !== null) {
674    await maybeDriftCheck($)
675    return
676  }
677  if (helloFlight !== null) return raceWithTimer($, helloFlight, HELLO_WAIT_MS)
678  if (retryBlocked) return
679  helloFlight = doHello($).finally(() => {
680    helloFlight = null
681  })
682  return raceWithTimer($, helloFlight, HELLO_WAIT_MS)
683}
684
685/** A STALE_CONN or a changed bootId: forget the conn and say hello again with `resume`. */
686async function rehello($: Dollar): Promise<void> {
687  const lost = conn
688  conn = null
689  endpoint = null
690  if (helloFlight !== null) return helloFlight
691  helloFlight = doHello($, lost ?? undefined).finally(() => {
692    helloFlight = null
693  })
694  return helloFlight
695}
696
697// ---- events pump ------------------------------------------------------------------------------
698
699/** Single flight; never awaited by a hook. With `beat`, an empty batch is sent as a heartbeat. */
700function pump($: Dollar, beat = false): void {
701  if (conn === null || dormant || inert) return
702  if (pumpFlight !== null) {
703    // an event pushed while the loop is on its way out would wait for the heartbeat: ask for one
704    // more pass once the flight is over (found by the Esc trace of P1W5: `turn.completed` is the
705    // event the sidebar waits for)
706    pumpKick = true
707    return
708  }
709  if (ring.size() === 0 && !beat) return
710  if (retryBlocked) return
711  pumpFlight = pumpLoop($, beat)
712    .catch(() => scheduleRetry($))
713    .finally(() => {
714      pumpFlight = null
715      if (pumpKick) {
716        pumpKick = false
717        pump($)
718      }
719    })
720}
721
722async function pumpLoop($: Dollar, beat: boolean): Promise<void> {
723  let first = true
724  let maxEvents = config.batchMaxEvents
725  let stale = 0
726  while (conn !== null && sidBound !== null && !dormant && !inert) {
727    const batch = ring.batch(maxEvents, config.batchMaxBytes)
728    if (batch.length === 0 && !(beat && first)) return
729    first = false
730    const dropped = ring.dropped()
731    const lastSeq = batch.at(-1)?.seq ?? 0
732    const request: EventsRequest = {
733      v: proto,
734      sid: sidBound,
735      conn,
736      sentAt: Date.now(),
737      events: batch,
738      ...(dropped > 0 ? { dropped } : {}),
739      // A profile that does not poll receives its commands on this response (contract §5.2, §21 item 4).
740      ...((boot?.isInteractive === false || tokenless) && bootId !== null
741        ? { bootId: bootId as EventsRequest['bootId'], cursor: (await ensureChannel($)).cursor }
742        : {})
743    }
744    sentSinceBeat = true
745    const r = await post($, 'events', request, false)
746    if (r.kind === 'transport') {
747      scheduleRetry($)
748      return
749    }
750    if (r.kind === 'rebooted') {
751      if (++stale > 2) return scheduleRetry($)
752      await rehello($)
753      continue
754    }
755    const body = r.body
756    if (body.ok === true && typeof body.ackSeq === 'number') {
757      ring.ack(Math.min(body.ackSeq, lastSeq))
758      ring.settleDropped(dropped)
759      backoffMs = BACKOFF_MIN_MS
760      if (body.resync === true) snapshot($, 'resync')
761      await acceptCommands($, parseCommands(body.commands))
762      // no progress (the host acknowledged nothing we sent): do not spin
763      if (batch.length > 0 && ring.batch(1, Infinity)[0]?.seq === batch[0]?.seq) return
764      continue
765    }
766    const code = typeof body.code === 'string' ? body.code : ''
767    if (code === 'STALE_CONN') {
768      if (++stale > 2) return scheduleRetry($)
769      await rehello($)
770      continue
771    }
772    if (code === 'BAD_ENVELOPE' || (code === 'TOO_LARGE' && batch.length <= 1)) {
773      ring.ack(lastSeq) // this batch can never be accepted: drop it and say so
774      reportModError('events', new Error(code))
775      continue
776    }
777    if (code === 'TOO_LARGE') {
778      maxEvents = Math.max(1, Math.floor(batch.length / 2))
779      continue
780    }
781    if (DORMANT_CODES.has(code)) return goDormant()
782    return scheduleRetry($, typeof body.retryAfterMs === 'number' ? body.retryAfterMs : undefined)
783  }
784}
785
786/** The heartbeat tick: retry a pending hello, run the drift check, renew the lease. */
787async function beat($: Dollar): Promise<void> {
788  try {
789    if (dormant || inert) return
790    if (conn === null) {
791      await ensureHello($)
792      return
793    }
794    await maybeDriftCheck($)
795    void watchModel($) // un-awaited: a slow read never delays the pump or the lease renewal
796    if (ring.size() > 0) pump($)
797    else if (!sentSinceBeat) pump($, true)
798    sentSinceBeat = false
799  } catch (err) {
800    void err
801  }
802}
803
804// ---- identity: rebound ------------------------------------------------------------------------
805
806/** At most once per DRIFT_CHECK_MIN_MS, only while no `classic.*` hook has ever been dispatched. */
807async function maybeDriftCheck($: Dollar): Promise<void> {
808  if (probes.classic || driftBlocked || conn === null || sidBound === null) return
809  driftBlocked = true
810  $.clock.after(DRIFT_CHECK_MIN_MS, () => {
811    driftBlocked = false
812  })
813  try {
814    const cur = await $.session.id()
815    if (typeof cur === 'string' && cur !== '' && cur !== sidBound) await rebound($, cur, 'unknown')
816  } catch {
817    // the engine's answer is advisory: a failed read changes nothing
818  }
819}
820
821async function rebound(
822  $: Dollar,
823  sid: Sid,
824  cause: EventPayloads['session.rebound']['cause']
825): Promise<void> {
826  const prev = sidBound
827  if (prev === null || prev === sid) return
828  sidBound = sid // the payload is the source of truth; `$.session.id()` can be stale (C10)
829  emit($, { t: 'session.rebound', d: { prevSid: prev, sid, cause } })
830  await persistConn($) // CQ3: written again after every rebound
831}
832
833// ---- bye --------------------------------------------------------------------------------------
834
835/** Best effort and never retried: the ring's contents plus `session.end`, within BYE_BUDGET_MS. */
836async function sayBye($: Dollar, reason: string): Promise<void> {
837  loopGen++ // the poll loop ends with the session
838  if (dormant || inert || conn === null || sidBound === null) return
839  ring.push({ t: 'session.end', ts: Date.now(), d: { reason } })
840  const request: ByeRequest = {
841    v: proto,
842    sid: sidBound,
843    conn,
844    sentAt: Date.now(),
845    reason,
846    events: ring.batch(config.ringMax, 512 * 1024)
847  }
848  await raceWithTimer($, post($, 'bye', request, false), BYE_BUDGET_MS)
849}
850
851/** A sensor body: never throws, never awaited beyond the first hello (and the first state read). */
852async function sense($: Dollar, where: string, run: () => void): Promise<void> {
853  try {
854    await ensureHello($)
855    await loadFleet($)
856    run()
857  } catch (err) {
858    reportModError(where, err)
859  }
860}
861
862/** `classic.*` bodies start with the probe and the permission mode, then sense (§11.4). */
863async function classic(
864  $: Dollar,
865  where: string,
866  e: { permission_mode?: string },
867  run: () => void
868): Promise<void> {
869  try {
870    noteClassic($, e)
871  } catch (err) {
872    reportModError(where, err)
873  }
874  await sense($, where, run)
875}
876
877/** `classic.PostToolUse` and the optional `classic.PostToolUseFailure`: a tool settled. */
878function settled(
879  $: Dollar,
880  failed: boolean,
881  e: { permission_mode?: string; tool_use_id: string; tool_name: string; agent_id?: string }
882): Promise<void> {
883  return classic($, failed ? 'classic.PostToolUseFailure' : 'classic.PostToolUse', e, () =>
884    feed($, {
885      k: 'post-tool',
886      toolUseId: e.tool_use_id,
887      tool: e.tool_name,
888      failed,
889      ...(e.agent_id !== undefined ? { agentId: e.agent_id } : {})
890    })
891  )
892}
893
894// ---- command channel (P2W1) ---------------------------------------------------------------------
895
896/** What a command handler answers; the executor wraps it in the one `command.result`. */
897type HandlerResult =
898  { ok: true; data?: unknown } | { ok: false; code: ErrorCode; message?: string; data?: unknown }
899/** What a command handler returns (the executor wraps it in the one `command.result`). */
900type Handled = HandlerResult | Promise<HandlerResult>
901
902/** A poll answered faster than this with nothing is not a hold: wait before asking again. */
903const IMMEDIATE_MS = 200
904let pollStale = 0 // consecutive STALE_CONN answers across loops: a host that keeps refusing
905
906const okResult = (data?: unknown): HandlerResult =>
907  data === undefined ? { ok: true } : { ok: true, data }
908const precondition = (message: string): HandlerResult => ({
909  ok: false,
910  code: 'CMD_PRECONDITION',
911  message
912})
913
914async function ensureChannel($: Dollar): Promise<ChannelState> {
915  if (channel !== null) return channel
916  const saved = await $.state.get(CHANNEL)
917  if (channel !== null) return channel // another caller read it while this one waited
918  channel = parseChannel(saved.value)
919  return channel
920}
921
922/** Writes the mirror to `$.state`, in order; a failed write only costs a reload its dedupe. */
923function writeChannel($: Dollar): Promise<unknown> {
924  if (channel === null || channel.bootId === null) return Promise.resolve()
925  const snap = {
926    ...channel,
927    bootId: channel.bootId,
928    started: [...channel.started],
929    resulted: [...channel.resulted]
930  }
931  stateChain = stateChain.then(() => $.state.set(CHANNEL, snap)).catch(() => undefined)
932  return stateChain
933}
934
935/**
936 * The cursor is written BEFORE a command starts (delivery), the `started` id before its `$` call
937 * (execution), and the loop never awaits a command (MOD-6, contract §6).
938 */
939async function acceptCommands($: Dollar, commands: Command[]): Promise<void> {
940  for (const c of commands) {
941    channel = withCursor(await ensureChannel($), c.n)
942    await writeChannel($)
943    void runCommand($, c)
944  }
945}
946
947function sendResult($: Dollar, c: Command, r: HandlerResult): void {
948  channel = markResulted(channel ?? parseChannel(null), c.cmd)
949  emit($, {
950    t: 'command.result',
951    d: {
952      cmd: c.cmd,
953      ok: r.ok,
954      ...(r.ok ? {} : { code: r.code }),
955      ...(r.ok ? {} : r.message !== undefined ? { message: r.message } : {}),
956      ...(r.data !== undefined
957        ? { data: r.data as CommandResultData[keyof CommandResultData] }
958        : {})
959    }
960  })
961  void writeChannel($)
962}
963
964/** Exactly one `command.result` per `cmd` (spec §7.7 executor table). Never rejects. */
965async function runCommand($: Dollar, c: Command): Promise<void> {
966  try {
967    const state = await ensureChannel($)
968    const d = classifyCommand(c, {
969      state,
970      inFlight,
971      now: await $.clock.now(),
972      tokenBacked,
973      featureEnabled: enabled,
974      known: (name) => IMPLEMENTED_COMMANDS.has(name)
975    })
976    if (d.kind === 'skip') return
977    if (d.kind === 'answer') {
978      sendResult($, c, {
979        ok: false,
980        code: d.code,
981        ...(d.message !== undefined ? { message: d.message } : {}),
982        ...(d.data !== undefined ? { data: d.data } : {})
983      })
984      return
985    }
986    // Everything from here to the `$` call is synchronous: two deliveries of one `cmd` cannot both pass.
987    channel = markStarted(state, c.cmd)
988    inFlight.add(c.cmd)
989    await writeChannel($)
990    let out: HandlerResult
991    try {
992      out = await runHandler($, c)
993    } catch (err) {
994      out = { ok: false, ...mapEngineRejection(err) }
995    }
996    inFlight.delete(c.cmd)
997    sendResult($, c, out)
998  } catch (err) {
999    inFlight.delete(c.cmd)
1000    reportModError('command', err, c.cmd)
1001  }
1002}
1003
1004function runFlush($: Dollar): Handled {
1005  snapshot($, 'flush')
1006  return okResult()
1007}
1008
1009function runConfigUpdate($: Dollar, c: Command<'config.update'>): Handled {
1010  const next = parseConfigUpdate(c.args)
1011  if (next === null) return precondition('a config value is outside its bounds')
1012  const beat = config.heartbeatMs
1013  config = { ...config, ...next }
1014  if (next.heartbeatMs !== undefined && next.heartbeatMs !== beat) {
1015    heartbeat?.cancel()
1016    heartbeat = null
1017    startHeartbeatOnce($)
1018  }
1019  return okResult()
1020}
1021
1022async function runTurnAbort($: Dollar, c: Command<'turn.abort'>): Promise<HandlerResult> {
1023  const own = typeof c.args.turnId === 'string' && c.args.turnId !== '' ? c.args.turnId : null
1024  const turnId = own ?? channel?.turnId ?? null
1025  if (turnId === null) return precondition('no turn id is known')
1026  await $.turn.abort({ turnId }) // an engine rejection is mapped by the executor
1027  return okResult()
1028}
1029
1030async function runCompact($: Dollar): Promise<HandlerResult> {
1031  const r = await $.session.compact()
1032  return okResult(compactData(r))
1033}
1034
1035function runToast($: Dollar, c: Command<'ui.toast'>): Handled {
1036  const text = c.args.text
1037  if (typeof text !== 'string' || text === '' || text.length > UI_TEXT_MAX) {
1038    return precondition('toast text must be 1 to 200 characters')
1039  }
1040  $.ui.toast(text)
1041  return okResult()
1042}
1043
1044function runStatus($: Dollar, c: Command<'ui.status'>): Handled {
1045  const text = c.args.text
1046  if (text !== null && (typeof text !== 'string' || text.length > UI_TEXT_MAX)) {
1047    return precondition('status text must be at most 200 characters, or null')
1048  }
1049  $.ui.status(text === null ? undefined : text)
1050  return okResult()
1051}
1052
1053/**
1054 * T257 `context.append`: one hidden user-role row through `$.session.append`. The mod keeps no copy
1055 * of it (`durable: false`). The poll loop never awaits this call (`runCommand` is `void`ed), so a
1056 * slow append delays only its own `command.result`.
1057 */
1058async function runContextAppend($: Dollar, c: Command<'context.append'>): Promise<HandlerResult> {
1059  const a = parseContextAppend(c.args)
1060  if (!a.ok) return precondition(a.message)
1061  const r = await $.session.append({
1062    message: { type: 'user', content: [{ type: 'text', text: a.text }] }
1063  })
1064  if (typeof r.deny === 'string') {
1065    return { ok: false, code: 'CMD_FAILED', message: `refused: ${r.deny}`.slice(0, 512) }
1066  }
1067  return okResult()
1068}
1069
1070function stopBandTimer(): void {
1071  bandTimer?.cancel()
1072  bandTimer = null
1073}
1074
1075/**
1076 * Asks the engine to draw `ui.render` again after the band state changed (T257): reading the key in
1077 * the hook subscribes it, but a hook that returned early may never have read it, and a redraw that
1078 * depends on that is a redraw that sometimes does not come. An engine without the call keeps the
1079 * state; the next render reads it.
1080 */
1081async function redrawBand($: Dollar): Promise<void> {
1082  try {
1083    await $.ui.invalidate('ui.render')
1084  } catch {
1085    // best effort: the band state is the truth, the redraw is a courtesy
1086  }
1087}
1088
1089/** A new host boot: forget the old queue's numbering and any line it left standing. */
1090function resetBand($: Dollar): void {
1091  const run = bandChain.then(async () => {
1092    bandN = 0
1093    const stored = parseBandState((await $.state.get(BAND)).value)
1094    if (stored === null) return
1095    stopBandTimer()
1096    await $.state.set(BAND, null)
1097    await redrawBand($)
1098  })
1099  bandChain = run.catch(() => undefined)
1100}
1101
1102/** Clears a band whose `expiresAt` has passed, so a dead host cannot leave a stale line (P4W2 §7.4). */
1103function sweepBand($: Dollar): void {
1104  const run = bandChain.then(async () => {
1105    const stored = parseBandState((await $.state.get(BAND)).value)
1106    if (stored !== null && bandLive(stored, await $.clock.now())) return
1107    if (stored !== null) {
1108      await $.state.set(BAND, null)
1109      await redrawBand($)
1110    }
1111    stopBandTimer()
1112  })
1113  bandChain = run.catch(() => undefined)
1114}
1115
1116function startBandTimer($: Dollar): void {
1117  if (bandTimer !== null) return
1118  bandTimer = $.clock.every(BAND_SWEEP_MS, () => sweepBand($))
1119}
1120
1121/** T257 `ui.band.set`: stores the band under `$.state.band`; the `ui.render` hook draws it. */
1122async function runBandSet($: Dollar, c: Command<'ui.band.set'>): Promise<HandlerResult> {
1123  const req = parseBandSet(c.args)
1124  if (req === null) return precondition('the band parts are missing, empty or over a limit')
1125  let applied = false
1126  const run = bandChain.then(async () => {
1127    const stored = parseBandState((await $.state.get(BAND)).value)
1128    const d = applyBand(req, c.n, await $.clock.now(), stored, bandN)
1129    if (!d.apply) return
1130    applied = true
1131    bandN = c.n
1132    await $.state.set(BAND, d.next)
1133    if (d.next === null) stopBandTimer()
1134    else startBandTimer($)
1135    await redrawBand($)
1136  })
1137  bandChain = run.catch(() => undefined)
1138  await run
1139  // A set the mod refused as older changed nothing, and the audit must not say it did.
1140  return applied ? okResult() : precondition('an older band set: a newer one is already applied')
1141}
1142
1143/**
1144 * The closed switch (SEC-5, contract §9): the only place a command name becomes a `$` call. The
1145 * engine refuses a `$` passed through a dynamic callee, so a later wave adds its `case` here, and
1146 * its name to `IMPLEMENTED_COMMANDS`, instead of registering a function.
1147 */
1148function runHandler($: Dollar, c: Command): Handled {
1149  switch (c.name) {
1150    case 'flush':
1151      return runFlush($)
1152    case 'config.update':
1153      return runConfigUpdate($, c as Command<'config.update'>)
1154    case 'turn.abort':
1155      return runTurnAbort($, c as Command<'turn.abort'>)
1156    case 'session.compact':
1157      return runCompact($)
1158    case 'ui.toast':
1159      return runToast($, c as Command<'ui.toast'>)
1160    case 'ui.status':
1161      return runStatus($, c as Command<'ui.status'>)
1162    case 'context.append':
1163      return runContextAppend($, c as Command<'context.append'>)
1164    case 'ui.band.set':
1165      return runBandSet($, c as Command<'ui.band.set'>)
1166    default:
1167      return { ok: false, code: 'CMD_UNSUPPORTED' }
1168  }
1169}
1170
1171// ---- the poll loop ------------------------------------------------------------------------------
1172
1173function pollEligible(): boolean {
1174  return (
1175    !dormant &&
1176    !inert &&
1177    conn !== null &&
1178    boot?.isInteractive === true &&
1179    enabledSet.includes('act.channel')
1180  )
1181}
1182
1183/**
1184 * Starts a poll loop under a new generation and retires the old one: a hello (the first, or a
1185 * re-hello) is the only caller, so there is one loop per load, never awaited by a hook.
1186 */
1187function restartPollLoop($: Dollar): void {
1188  const gen = ++loopGen
1189  if (pollEligible()) void pollLoop($, gen)
1190}
1191
1192async function pollLoop($: Dollar, gen: number): Promise<void> {
1193  let backoff = BACKOFF_MIN_MS
1194  try {
1195    while (gen === loopGen && pollEligible()) {
1196      const sid = sidBound
1197      const boot0 = bootId
1198      if (sid === null || conn === null || boot0 === null) return
1199      channel = forBoot(await ensureChannel($), boot0)
1200      const cursor = channel.cursor
hooks/contract.ts 515 lines
1/**
2 * Harnu mod protocol 1: the wire contract between the mod (running inside `claude`) and the host
3 * (the companion server in Harnu main). Types and constants only, ZERO imports: the mod imports
4 * this file by a relative path inside the plugin dir, the host through
5 * `src/main/companion/contract.ts` (a re-export).
6 *
7 * The normative prose is `docs/specs/T389-companion-mod/01-contract.md`. When this file and that
8 * document disagree, that is a defect in both: fix them together (DOC-7).
9 */
10
11// ---- §4 Ids ---------------------------------------------------------------------------------
12
13/** The CLI session uuid (equals the transcript file name). */
14export type Sid = string
15/** `sp_<uuid>`, minted by the host, one per PTY spawn or scheduler tick. */
16export type SpawnToken = `sp_${string}`
17/** `c_<32 hex>`, minted by the host per connection. Correlation, not authentication. */
18export type Conn = `c_${string}`
19/** `b_<uuid>`, changes on every host boot. */
20export type BootId = `b_${string}`
21/** `cmd_<ulid>`, minted by the host. */
22export type CmdId = `cmd_${string}`
23/** `ask_...`, minted by the mod. */
24export type AskId = string
25/** Dotted lower-case `<class>.<name>` (§11). */
26export type FeatureId = string
27/** The closed set of context keys, as a runtime value so a test can pin it. */
28export const CONTEXT_KEYS = [
29  'harnu.orchestrator',
30  'harnu.mission',
31  'harnu.review-selection'
32] as const
33export type ContextKey = (typeof CONTEXT_KEYS)[number]
34
35// ---- §7 Constants ---------------------------------------------------------------------------
36
37export const PROTOCOL_VERSION = 1
38
39export const FETCH_HARD_CAP_MS = 30_000
40export const POLL_HOLD_MS = 25_000
41export const ASK_TRANCHE_MS = 20_000
42export const HELLO_SLA_MS = 2_000
43export const HELLO_WAIT_MS = 2_500
44export const SPAWN_REDEEM_WINDOW_MS = 600_000
45export const DRIFT_CHECK_MIN_MS = 1_000
46export const BYE_BUDGET_MS = 1_000
47export const LEASE_TTL_MS = 20_000
48export const LEASE_SWEEP_MS = 5_000
49export const HEARTBEAT_MS = 10_000
50export const FLUSH_MS = 250
51export const BATCH_MAX_EVENTS = 32
52export const BATCH_MAX_BYTES = 65_536
53export const RING_MAX = 256
54export const BODY_MAX_BYTES = 1_048_576
55export const SOCKET_PATH_MAX_BYTES = 90
56export const RATE_WINDOW_MS = 10_000
57export const RATE_MAX_REQUESTS = 200
58export const BACKOFF_MIN_MS = 500
59export const BACKOFF_MAX_MS = 15_000
60export const HOOK_BUDGET_MS = 10_000
61export const WEDGE_MS = 5_000
62
63export const CMD_TTL_MS = 30_000
64export const CMD_QUEUE_MAX = 64
65/** Largest `context.append.text`, durable or not (contract §9). */
66export const CONTEXT_MAX_CHARS = 20_000
67/** The mod clears a band line this long after it was set (contract §9, P4W2). */
68export const BAND_TTL_MS = 90_000
69/** Host keep-alive re-send of a standing band line. Under `BAND_TTL_MS`, so a live line never lapses. */
70export const BAND_REFRESH_MS = 60_000
71/** Host debounce before a changed band line is sent. */
72export const BAND_DEBOUNCE_MS = 500
73/** `BandParts` length caps. The host checks them and the mod checks them again. */
74export const BAND_LEAD_MAX = 32
75export const BAND_DETAIL_MAX = 48
76export const BAND_HINT_MAX = 32
77export const CMD_DONE_MAX = 64
78/** Host wait for a result after `expiresAt`, unless the command has its own (§7.2). */
79export const CMD_RESULT_GRACE_DEFAULT_MS = 5_000
80/**
81 * Per command name: an idle compaction answers after 14 to 37 s (smoke C2), and the engine may be
82 * slower on a long session. Commands not listed use `CMD_RESULT_GRACE_DEFAULT_MS`.
83 */
84export const CMD_RESULT_GRACE_MS: Readonly<Partial<Record<CommandName, number>>> = {
85  'session.compact': 120_000
86}
87export const ASK_ORPHAN_MS = 45_000
88export const STAMP_NONCE_RING = 512
89export const ASK_RECORD_MAX = 64
90export const PLAN_USAGE_STALE_MS = 90_000
91/** Live external bindings the host keeps; a tokenless hello over it is SLOW_DOWN (§21 item 2). */
92export const EXTERNAL_MAX_BINDINGS = 32
93/** An external binding not corroborated this long after its first `turn.started` is dropped (§21 item 6). */
94export const EXTERNAL_CORROBORATE_MS = 30_000
95
96export const STAMP_ARG = '_harnuCaller'
97export const STAMP_PROOF_VERSION = 'v1'
98
99export interface Config {
100  flushMs: number
101  batchMaxEvents: number
102  batchMaxBytes: number
103  ringMax: number
104  pollHoldMs: number
105  askHoldMs: number
106  heartbeatMs: number
107}
108
109/** What `hello.config` carries when nothing overrides it. */
110export const DEFAULT_CONFIG: Readonly<Config> = {
111  flushMs: FLUSH_MS,
112  batchMaxEvents: BATCH_MAX_EVENTS,
113  batchMaxBytes: BATCH_MAX_BYTES,
114  ringMax: RING_MAX,
115  pollHoldMs: POLL_HOLD_MS,
116  askHoldMs: ASK_TRANCHE_MS,
117  heartbeatMs: HEARTBEAT_MS
118}
119
120/** Bounds for `config.update`; a value outside them is CMD_PRECONDITION (P2W1). */
121export const CONFIG_BOUNDS: Readonly<Record<keyof Config, readonly [min: number, max: number]>> = {
122  flushMs: [50, 5_000],
123  batchMaxEvents: [1, 256],
124  batchMaxBytes: [1_024, 524_288],
125  ringMax: [32, 1_024],
126  pollHoldMs: [1_000, 25_000],
127  askHoldMs: [1_000, 20_000],
128  heartbeatMs: [2_000, 15_000]
129}
130
131// ---- §12 Errors -----------------------------------------------------------------------------
132
133export type ErrorCode =
134  // host → mod, in a Failure
135  | 'PROTO_UNSUPPORTED'
136  | 'UNAUTHORIZED'
137  | 'UNKNOWN_SESSION'
138  | 'STALE_CONN'
139  | 'BAD_ENVELOPE'
140  | 'TOO_LARGE'
141  | 'SLOW_DOWN'
142  | 'FEATURE_DISABLED'
143  | 'HOST_SHUTTING_DOWN'
144  // mod → host, in command.result
145  | 'CMD_EXPIRED'
146  | 'CMD_UNSUPPORTED'
147  | 'CMD_PRECONDITION'
148  | 'CMD_FAILED'
149
150export type Failure = { ok: false; code: ErrorCode; message?: string; retryAfterMs?: number }
151
152// ---- §2 Transport and rendezvous ------------------------------------------------------------
153
154export type EndpointName = 'hello' | 'events' | 'poll' | 'ask' | 'bye'
155
156/** The five routes, `POST /v1/<endpoint>`. */
157export const ENDPOINT_NAMES: readonly EndpointName[] = ['hello', 'events', 'poll', 'ask', 'bye']
158
159/** <userData>/companion/endpoint.json */
160export interface EndpointFile {
161  v: 1
162  transport: 'unix' | 'tcp'
163  socketPath?: string // transport 'unix'
164  port?: number // transport 'tcp', always 127.0.0.1
165  token: string // endpoint token; defence in depth only (§17)
166  bootId: BootId // changes on every host boot
167  protoMin: number
168  protoMax: number
169  writtenAt: number // epoch ms
170}
171
172// ---- §5 Endpoints ---------------------------------------------------------------------------
173
174/** Carried by every request except hello. */
175export interface Envelope {
176  v: number // negotiated protocol version
177  sid: Sid // the mod's bound session id (§15)
178  conn: Conn
179  sentAt: number // epoch ms, mod clock
180}
181
182export interface HelloRequest {
183  protoMin: number
184  protoMax: number
185  sid: Sid
186  spawn?: SpawnToken // first hello of a Harnu-spawned process
187  resume?: { conn: Conn } // re-hello
188  cli: { version: string }
189  mod: { version: string }
190  surface: string | null // session.start.surface; null for -p and the SDK
191  isInteractive: boolean
192  cwd: string
193  declared: FeatureId[] // only features whose hooks actually registered (§11)
194  sentAt: number
195}
196
197export type HelloProfile = 'interactive' | 'headless' | 'external'
198
199export type HelloResponse =
200  | {
201      ok: true
202      proto: number
203      conn: Conn
204      bootId: BootId
205      sessionKey: string | null
206      profile: HelloProfile
207      enable: FeatureId[] // subset of `declared`
208      config: Config
209      opts?: ModOptions
210      commands?: Command[]
211    }
212  | Failure
213
214/** Per-hello options the mod cannot derive from `enable`. Additive; unknown keys are ignored. */
215export interface ModOptions {
216  compactSummary?: boolean // P4W5
217}
218
219export interface EventsRequest extends Envelope {
220  events: WireEvent[] // may be empty (heartbeat)
221  dropped?: number // events the mod discarded since the last accepted batch
222  bootId?: BootId // non-polling profiles only
223  cursor?: number // non-polling profiles only: highest Command.n recorded
224}
225
226export interface WireEvent<N extends EventName = EventName> {
227  seq: number // monotonic per conn, starts at 1
228  t: N
229  ts: number // epoch ms, when the CLI event fired
230  turnId?: string // MUST be set on turn.started and turn.completed
231  agentId?: string // present for a subagent's event
232  d: EventPayloads[N]
233}
234
235export type EventsResponse =
236  { ok: true; ackSeq: number; resync?: boolean; commands?: Command[] } | Failure
237
238export interface PollRequest extends Envelope {
239  bootId: BootId // the boot the cursor belongs to
240  cursor: number // highest Command.n the mod has recorded for that boot
241}
242
243export type PollResponse = { ok: true; commands: Command[]; resync?: boolean } | Failure
244
245export interface Command<N extends CommandName = CommandName> {
246  cmd: CmdId
247  n: number // ordinal per binding and boot, starts at 1
248  name: N
249  args: CommandArgs[N]
250  issuedAt: number
251  expiresAt: number
252}
253
254export interface AskRequest<K extends AskKind = AskKind> extends Envelope {
255  askId: AskId
256  kind: K
257  d?: AskPayloads[K] // MUST be present on the first tranche; MAY be omitted afterwards
258}
259
260export type ReleaseReason = 'abstain' | 'shadow' | 'settled' | 'expired' | 'host-shutdown'
261
262export type AskResponse<K extends AskKind = AskKind> =
263  | { ok: true; state: 'pending' }
264  | { ok: true; state: 'decided'; decision: AskDecisions[K] }
265  | { ok: true; state: 'released'; reason: ReleaseReason }
266  | Failure
267
268export interface ByeRequest extends Envelope {
269  reason: string // session.end.reason
270  events?: WireEvent[] // the final flush, including `session.end`
271}
272
273export type ByeResponse = { ok: true } | Failure
274
275// ---- §8 Events (mod → host) -----------------------------------------------------------------
276
277export type AttentionKind = 'permission' | 'idle' | 'input'
278
279/** A model request's token counts. Fork, complete and compaction results carry no model. */
280export interface AuxUsage {
281  inputTokens: number
282  outputTokens: number
283  cacheReadTokens: number
284  cacheCreationTokens: number
285}
286
287export interface TurnUsage extends AuxUsage {
288  model: string
289}
290
291export interface EventPayloads {
292  'session.snapshot': {
293    reason: 'hello' | 'resync' | 'flush' | 'probe'
294    activeTurnId: string | null
295    openAttention: { kind: AttentionKind; toolUseId?: string }[]
296    runningSubagents: number
297    probes: { classic: boolean; toolCheck: boolean }
298  }
299  'session.rebound': { prevSid: Sid; sid: Sid; cause: 'clear' | 'resume' | 'unknown' }
300  'session.end': { reason: string }
301  'mod.error': {
302    where: string
303    kind: 'throw' | 'timeout' | 'abort' | 'registration'
304    message: string
305    cmd?: CmdId
306  }
307  'turn.started': { origin: 'human' | 'plugin' | 'peer' | 'unknown'; cmd?: CmdId }
308  'turn.completed': {
309    reason: 'answer' | 'aborted' | 'refusal' | 'error'
310    isAborted: boolean
311    durationMs: number
312    usage?: TurnUsage
313    backgroundTasks?: number
314    backgroundSubagents?: number
315    failure?: { type: string }
316  }
317  'attention.raised': {
318    kind: AttentionKind
319    source: 'check' | 'request' | 'notification'
320    toolUseId?: string
321    tool?: string
322  }
323  'attention.cleared': {
324    kind: AttentionKind
325    toolUseId?: string
326    cause: 'tool-settled' | 'ask-resolved' | 'turn-completed' | 'prompt'
327  }
328  'subagent.started': { agentType: string; agentId?: string }
329  'subagent.stopped': { agentType: string; agentId?: string }
330  'usage.measured': {
331    source: 'measure' | 'read'
332    context?: { window: number; tokens?: number; percent?: number }
333    rateLimits: { kind: string; percentUsed: number; resetsAt?: string }[]
334    costUsd?: number
335    changed: ('context' | 'rateLimits' | 'cost')[]
336    startedAt?: number
337    model?: string
338  }
339  'command.result': {
340    cmd: CmdId
341    ok: boolean
342    code?: ErrorCode
343    message?: string
344    data?: CommandResultData[keyof CommandResultData]
345  }
346  'message.sent': {
347    origin: 'model' | 'plugin'
348    plugin?: string
349    to: string
350    delivered: boolean
351    reason?: string
352    bytes: number
353    hash?: string
354  }
355  'message.received': {
356    originKind: string
357    plugin?: string
358    fromName?: string
359    from?: string
360    bytes: number
361    hash?: string
362    outcome: 'queued' | 'consumed' | 'rewritten'
363  }
364  'guard.denied': { tool: string; path: string; toolUseId?: string }
365  'guard.evaluated': {
366    tool: string
367    path: string
368    subagent: boolean
369    decision: 'allow' | 'deny'
370    exempt?: 'harnu' | 'scratch' | 'memory'
371    toolUseId?: string
372  }
373  'ask.settled': { askId: AskId; cause: 'tool-ran' | 'tool-failed' | 'aborted' | 'turn-ended' }
374  'ui.action': { name: 'open' }
375  'compact.done': {
376    trigger: 'manual' | 'auto' | 'plugin'
377    via: 'hook' | 'command' | 'classic'
378    tokensBefore?: number
379    tokensAfter?: number
380    usage?: AuxUsage
381    summary?: string
382    summaryTruncated?: boolean
383    summaryChars: number
384    reinjected: number
385  }
386  'mod.admitted': {
387    name: string
388    tier: 'prepend' | 'user' | 'append' | 'builtin'
389    root: string
390    version?: string
391    provenance: string
392    uses: {
393      events: string[]
394      calls: string[]
395      env: { reads: string[]; writes: string[] }
396      state: { reads: { plugin: string; key: string }[]; writes: { plugin: string; key: string }[] }
397    }
398  }
399}
400
401export type EventName = keyof EventPayloads
402
403// ---- §9 Commands (host → mod) ---------------------------------------------------------------
404
405export interface BandParts {
406  lead: string // at most 32 chars
407  detail?: string // at most 48 chars
408  hint?: string // at most 32 chars
409}
410
411export interface BandLink {
412  label: string // at most 16 chars
413  href: string // http://localhost:<port>/o/<Ticket> only
414}
415
416export interface CommandArgs {
417  flush: Record<string, never>
418  'config.update': { config: Partial<Config> }
419  'turn.abort': { turnId?: string }
420  'session.compact': Record<string, never>
421  'ui.toast': { text: string }
422  'ui.status': { text: string | null }
423  'prompt.submit': {
424    text: string
425    asUser: boolean
426    via: 'prompt' | 'command'
427    command?: string
428    args?: string
429  }
430  'message.deliver': { msgId: string; from: { name: string; sessionKey?: string }; text: string }
431  'context.append': { key: ContextKey; text: string; durable: boolean; retainOnly?: boolean }
432  'context.drop': { key: ContextKey }
433  'guard.set': { armed: boolean; enforce?: boolean }
434  'sentinel.set': { tools: string[] }
435  'ui.band.set': { line: string | null; parts?: BandParts; link?: BandLink }
436  'plan.capture': { title?: boolean }
437}
438
439export type CommandName = keyof CommandArgs
440
441export interface SubmitResultData {
442  submitted: true | false | 'unknown'
443}
444
445export interface PlanCaptureData {
446  text: string | null
447  reason?: 'nothing-to-fork' | 'api-error' | 'empty-reply' | 'aborted'
448  status?: number | null
449  usage?: AuxUsage
450  title?: string | null
451  titleUsage?: AuxUsage
452  ms: number
453}
454
455/** `command.result.data`, keyed by command name. Commands not listed carry no data. */
456export interface CommandResultData {
457  'session.compact': { tokensBefore?: number; tokensAfter?: number } | { skipped: true }
458  'prompt.submit': SubmitResultData
459  'message.deliver': SubmitResultData & { reason?: 'permission-mode' }
460  'guard.set': { armed: boolean }
461  'plan.capture': PlanCaptureData
462}
463
464// ---- §10 Asks (mod → host) ------------------------------------------------------------------
465
466export type AskKind = 'permission' | 'sentinel' | 'status'
467
468export interface AskPayloads {
469  permission: {
470    tool: string
471    input: unknown
472    inputTruncated?: boolean
473    toolUseId?: string
474    ambiguous?: boolean
475    askedBy?: 'engine' | 'hook'
476    hook?: string
477    agentId?: string
478    agentType?: string
479    permissionMode: string
480    cwd: string
481    suggestions?: unknown
482  }
483  sentinel: {
484    tool: string
485    input: unknown
486    inputTruncated?: boolean
487    toolUseId: string
488    verdict: 'allow' | 'ask' | 'deny'
489    cwd: string
490  }
491  status: { columns: number; isFullscreen: boolean }
492}
493
494/** Enums and integers only: the mod builds closed-vocabulary text from it. */
495export interface StatusReport {
496  companion: 'live' | 'shadow'
497  profile: 'interactive' | 'external'
498  coverage: 'gated' | 'contested' | 'not-gated'
499  held: number
500  mission: {
501    from: number
502    to: number
503    of: number
504    complete: boolean
505    verified: number
506    waitingOnOperator: number
507  } | null
508}
509
510export interface AskDecisions {
511  permission: { behavior: 'allow' } | { behavior: 'deny'; message: string }
512  sentinel: { behavior: 'deny'; message: string }
513  status: StatusReport
514}
515
hooks/lib/fleet-sensor.ts 455 lines
1import { ASK_RECORD_MAX, type AttentionKind, type EventPayloads } from '../contract'
2
3/**
4 * The fleet sensors' core (T389 P1W5 §7.1): turns, attention and subagents. Pure: no `$`, no
5 * clock, no imports beyond the contract (MOD-1). `register.ts` feeds it what each hook saw and
6 * emits what it returns; the state is mirrored to `$.state` (key `fleet`, contract §22), so a hot
7 * reload re-derives a correct `session.snapshot` (MOD-4).
8 *
9 * Nothing here alters a verdict (MOD-8), and nothing carries tool input, prompt text, a message
10 * or a task description (SEC-8): tool names and ids only.
11 */
12
13type Origin = EventPayloads['turn.started']['origin']
14
15export interface OpenItem {
16  kind: AttentionKind
17  toolUseId?: string
18  tool?: string
19  agentId?: string
20}
21
22/** The one shared record list of contract §22 (`tool.check` → `ask`); P3W1 fills `inputKey`, `claimedBy`. */
23export interface CheckRecord {
24  toolUseId: string
25  tool: string
26  inputKey?: string
27  at: number
28  claimedBy?: string
29  agentId?: string
30  hook?: string
31}
32
33export interface FleetSensorState {
34  activeTurnId: string | null
35  nextOrigin: Origin
36  open: OpenItem[]
37  checks: CheckRecord[]
38  runningSubagents: number
39  lastStop: { all: number; subagents: number } | null
40  pendingFailure: string | null
41  /** Per-agent facts, keyed on the agent id: the subagents this sensor counted. */
42  agents: Record<string, string>
43  /**
44   * The ids of subagents that already stopped (the newest `STOPPED_MAX`). The CLI still lists a
45   * finished agent as `running` in the `background_tasks` of the next main `Stop` (observed on
46   * 2.1.291: the task id is the agent id), so a hold must not count it.
47   */
48  stopped: string[]
49}
50
51export type SensorInput =
52  | { k: 'prompt'; originKind: unknown }
53  | { k: 'turn.start'; turnId: string }
54  | {
55      k: 'tool.check'
56      tool: string
57      decision: string
58      toolUseId?: string
59      agentId?: string
60      hook?: string
61      at: number
62    }
63  | { k: 'permission.request'; tool: string; agentId?: string }
64  | { k: 'notification'; type: string }
65  | { k: 'post-tool'; toolUseId?: string; tool?: string; agentId?: string; failed: boolean }
66  | { k: 'stop'; tasks: readonly { type: string; status?: string; id?: string }[] | undefined }
67  | { k: 'stop-failure'; error: string }
68  | {
69      k: 'turn.complete'
70      turnId: string
71      reason: EventPayloads['turn.completed']['reason']
72      isAborted: boolean
73      durationMs: number
74      usage?: unknown
75      agentId?: string
76    }
77  | { k: 'subagent.start'; agentType: string; agentId?: string }
78  | { k: 'subagent.stop'; agentType: string; agentId?: string }
79  | { k: 'rebound' }
80
81export type OutEvent =
82  | { t: 'turn.started'; d: EventPayloads['turn.started']; turnId: string }
83  | { t: 'turn.completed'; d: EventPayloads['turn.completed']; turnId: string; agentId?: string }
84  | { t: 'attention.raised'; d: EventPayloads['attention.raised']; agentId?: string }
85  | { t: 'attention.cleared'; d: EventPayloads['attention.cleared'] }
86  | { t: 'subagent.started'; d: EventPayloads['subagent.started'] }
87  | { t: 'subagent.stopped'; d: EventPayloads['subagent.stopped'] }
88
89/** The host treats counters as untrusted and clamps at 256 (§9); the sensor never exceeds it. */
90const COUNT_MAX = 256
91const STOPPED_MAX = 64
92
93/** Statuses of a background task that has stopped running (types L641 name the field; Q12 the values). */
94const FINISHED = new Set(['completed', 'failed', 'killed', 'stopped', 'cancelled', 'error'])
95
96export function neutralFleet(): FleetSensorState {
97  return {
98    activeTurnId: null,
99    nextOrigin: 'unknown',
100    open: [],
101    checks: [],
102    runningSubagents: 0,
103    lastStop: null,
104    pendingFailure: null,
105    agents: {},
106    stopped: []
107  }
108}
109
110/** What `$.state` returned, made safe: a value this sensor did not write reads as the neutral state. */
111export function sanitizeFleet(raw: unknown): FleetSensorState {
112  const out = neutralFleet()
113  if (typeof raw !== 'object' || raw === null) return out
114  const r = raw as Record<string, unknown>
115  if (typeof r.activeTurnId === 'string') out.activeTurnId = r.activeTurnId
116  if (r.nextOrigin === 'human' || r.nextOrigin === 'plugin' || r.nextOrigin === 'peer') {
117    out.nextOrigin = r.nextOrigin
118  }
119  if (Array.isArray(r.open)) {
120    for (const o of r.open) {
121      if (typeof o !== 'object' || o === null) continue
122      const i = o as Record<string, unknown>
123      if (i.kind !== 'permission' && i.kind !== 'idle' && i.kind !== 'input') continue
124      out.open.push({
125        kind: i.kind,
126        ...(typeof i.toolUseId === 'string' ? { toolUseId: i.toolUseId } : {}),
127        ...(typeof i.tool === 'string' ? { tool: i.tool } : {}),
128        ...(typeof i.agentId === 'string' ? { agentId: i.agentId } : {})
129      })
130    }
131  }
132  if (Array.isArray(r.checks)) {
133    for (const c of r.checks.slice(-ASK_RECORD_MAX)) {
134      if (typeof c !== 'object' || c === null) continue
135      const i = c as Record<string, unknown>
136      if (typeof i.toolUseId !== 'string' || typeof i.tool !== 'string') continue
137      out.checks.push({
138        toolUseId: i.toolUseId,
139        tool: i.tool,
140        at: typeof i.at === 'number' ? i.at : 0,
141        ...(typeof i.inputKey === 'string' ? { inputKey: i.inputKey } : {}),
142        ...(typeof i.claimedBy === 'string' ? { claimedBy: i.claimedBy } : {}),
143        ...(typeof i.agentId === 'string' ? { agentId: i.agentId } : {}),
144        ...(typeof i.hook === 'string' ? { hook: i.hook } : {})
145      })
146    }
147  }
148  if (typeof r.runningSubagents === 'number' && Number.isFinite(r.runningSubagents)) {
149    out.runningSubagents = Math.min(COUNT_MAX, Math.max(0, Math.trunc(r.runningSubagents)))
150  }
151  const ls = r.lastStop as { all?: unknown; subagents?: unknown } | null | undefined
152  if (ls && typeof ls.all === 'number' && typeof ls.subagents === 'number') {
153    out.lastStop = { all: ls.all, subagents: ls.subagents }
154  }
155  if (typeof r.pendingFailure === 'string') out.pendingFailure = r.pendingFailure
156  if (typeof r.agents === 'object' && r.agents !== null) {
157    for (const [id, type] of Object.entries(r.agents as Record<string, unknown>)) {
158      if (typeof type === 'string' && Object.keys(out.agents).length < COUNT_MAX) {
159        out.agents[id] = type
160      }
161    }
162  }
163  if (Array.isArray(r.stopped)) {
164    out.stopped = r.stopped.filter((x): x is string => typeof x === 'string').slice(-STOPPED_MAX)
165  }
166  return out
167}
168
169/** `origin.kind` of a `prompt.submit` event → the contract's four origins. */
170export function originOf(kind: unknown): Origin {
171  switch (kind) {
172    case 'composer':
173    case 'bridge':
174    case 'sdk':
175      return 'human'
176    case 'plugin':
177      return 'plugin'
178    case 'peer':
179    case 'peer-send-message':
180    case 'projects-relay':
181    case 'coordinator':
182      return 'peer'
183    default:
184      return 'unknown'
185  }
186}
187
188/** The snapshot's fleet half (contract §8): neutral values before any turn. */
189export function snapshotFields(s: FleetSensorState): {
190  activeTurnId: string | null
191  openAttention: { kind: AttentionKind; toolUseId?: string }[]
192  runningSubagents: number
193} {
194  return {
195    activeTurnId: s.activeTurnId,
196    openAttention: s.open.map((o) => ({
197      kind: o.kind,
198      ...(o.toolUseId !== undefined ? { toolUseId: o.toolUseId } : {})
199    })),
200    runningSubagents: s.runningSubagents
201  }
202}
203
204const cleared = (o: OpenItem, cause: EventPayloads['attention.cleared']['cause']): OutEvent => ({
205  t: 'attention.cleared',
206  d: { kind: o.kind, ...(o.toolUseId !== undefined ? { toolUseId: o.toolUseId } : {}), cause }
207})
208
209function turnUsage(raw: unknown): EventPayloads['turn.completed']['usage'] {
210  if (typeof raw !== 'object' || raw === null) return undefined
211  const u = raw as Record<string, unknown>
212  if (typeof u.model !== 'string') return undefined
213  const n = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) ? v : 0)
214  return {
215    model: u.model,
216    inputTokens: n(u.input_tokens),
217    outputTokens: n(u.output_tokens),
218    cacheReadTokens: n(u.cache_read_input_tokens),
219    cacheCreationTokens: n(u.cache_creation_input_tokens)
220  }
221}
222
223/**
224 * One step. Pure and total over well-formed input; a malformed element of a hook payload may
225 * throw, and the hook that called it turns the throw into one `mod.error` (MOD-2).
226 */
227export function step(
228  s: FleetSensorState,
229  input: SensorInput
230): { state: FleetSensorState; events: OutEvent[] } {
231  const events: OutEvent[] = []
232  const next: FleetSensorState = {
233    ...s,
234    open: [...s.open],
235    checks: [...s.checks],
236    agents: { ...s.agents },
237    stopped: [...s.stopped]
238  }
239
240  switch (input.k) {
241    case 'prompt': {
242      next.nextOrigin = originOf(input.originKind)
243      for (const o of next.open) events.push(cleared(o, 'prompt'))
244      next.open = []
245      break
246    }
247    case 'turn.start': {
248      events.push({
249        t: 'turn.started',
250        d: { origin: next.nextOrigin },
251        turnId: input.turnId
252      })
253      next.activeTurnId = input.turnId
254      next.lastStop = null
255      next.pendingFailure = null
256      next.nextOrigin = 'unknown'
257      break
258    }
259    case 'tool.check': {
260      // only an `ask` with an id is recorded; under `dontAsk` and `-p` no dialog follows (B1.6)
261      if (input.decision !== 'ask' || input.toolUseId === undefined) break
262      const id = input.toolUseId
263      if (next.checks.some((c) => c.toolUseId === id)) break
264      next.checks.push({
265        toolUseId: id,
266        tool: input.tool,
267        at: input.at,
268        ...(input.agentId !== undefined ? { agentId: input.agentId } : {}),
269        ...(input.hook !== undefined ? { hook: input.hook } : {})
270      })
271      if (next.checks.length > ASK_RECORD_MAX)
272        next.checks.splice(0, next.checks.length - ASK_RECORD_MAX)
273      next.open.push({
274        kind: 'permission',
275        toolUseId: id,
276        tool: input.tool,
277        ...(input.agentId !== undefined ? { agentId: input.agentId } : {})
278      })
279      events.push({
280        t: 'attention.raised',
281        d: { kind: 'permission', source: 'check', toolUseId: id, tool: input.tool },
282        ...(input.agentId !== undefined ? { agentId: input.agentId } : {})
283      })
284      break
285    }
286    case 'permission.request': {
287      // FIFO over the unclaimed records of the same tool and agent: the pairing P3W1 reuses
288      const rec = next.checks.find(
289        (c) => c.claimedBy === undefined && c.tool === input.tool && c.agentId === input.agentId
290      )
291      if (rec) rec.claimedBy = 'request'
292      const id = rec?.toolUseId
293      const known = next.open.some(
294        (o) =>
295          o.kind === 'permission' &&
296          (id !== undefined
297            ? o.toolUseId === id
298            : o.toolUseId === undefined && o.tool === input.tool)
299      )
300      if (!known) {
301        next.open.push({
302          kind: 'permission',
303          tool: input.tool,
304          ...(id !== undefined ? { toolUseId: id } : {}),
305          ...(input.agentId !== undefined ? { agentId: input.agentId } : {})
306        })
307      }
308      events.push({
309        t: 'attention.raised',
310        d: {
311          kind: 'permission',
312          source: 'request',
313          tool: input.tool,
314          ...(id !== undefined ? { toolUseId: id } : {})
315        },
316        ...(input.agentId !== undefined ? { agentId: input.agentId } : {})
317      })
318      break
319    }
320    case 'notification': {
321      const kind: AttentionKind | null =
322        input.type === 'permission_prompt' || input.type === 'worker_permission_prompt'
323          ? 'permission'
324          : input.type === 'elicitation_dialog'
325            ? 'input'
326            : input.type === 'idle_prompt'
327              ? 'idle'
328              : null
329      if (kind === null) break
330      // the dialog a check or a request already opened is the same dialog
331      if (!next.open.some((o) => o.kind === kind)) next.open.push({ kind })
332      events.push({
333        t: 'attention.raised',
334        d: { kind, source: 'notification' }
335      })
336      break
337    }
338    case 'post-tool': {
339      const idx = next.open.findIndex((o) => {
340        if (o.kind !== 'permission') return false
341        if (o.agentId !== input.agentId) return false
342        if (o.toolUseId !== undefined) return o.toolUseId === input.toolUseId
343        if (o.tool !== undefined) return o.tool === input.tool
344        return true // a bare notification item: any tool settling means the dialog is over
345      })
346      if (input.toolUseId !== undefined) {
347        next.checks = next.checks.filter((c) => c.toolUseId !== input.toolUseId)
348      }
349      if (idx < 0) break
350      const [item] = next.open.splice(idx, 1)
351      if (item) events.push(cleared(item, 'tool-settled'))
352      break
353    }
354    case 'stop': {
355      const tasks = Array.isArray(input.tasks) ? input.tasks : []
356      next.lastStop = {
357        all: tasks.length,
358        // `type === 'subagent'` only (spec §7.1, Q12). A task that finished, or whose agent this
359        // sensor already saw stop, does not hold: the CLI keeps listing it as `running`
360        subagents: tasks.filter(
361          (t) =>
362            t.type === 'subagent' &&
363            !FINISHED.has(String(t.status)) &&
364            !(typeof t.id === 'string' && next.stopped.includes(t.id))
365        ).length
366      }
367      break
368    }
369    case 'stop-failure': {
370      next.pendingFailure = input.error.slice(0, 64)
371      break
372    }
373    case 'turn.complete': {
374      const usage = turnUsage(input.usage)
375      if (input.agentId !== undefined) {
376        events.push({
377          t: 'turn.completed',
378          d: {
379            reason: input.reason,
380            isAborted: input.isAborted,
381            durationMs: input.durationMs,
382            ...(usage ? { usage } : {})
383          },
384          turnId: input.turnId,
385          agentId: input.agentId
386        })
387        break
388      }
389      for (const o of next.open) events.push(cleared(o, 'turn-completed'))
390      events.push({
391        t: 'turn.completed',
392        d: {
393          reason: input.reason,
394          isAborted: input.isAborted,
395          durationMs: input.durationMs,
396          ...(usage ? { usage } : {}),
397          backgroundTasks: s.lastStop?.all ?? 0,
398          backgroundSubagents: Math.max(s.runningSubagents, s.lastStop?.subagents ?? 0),
399          ...(s.pendingFailure !== null ? { failure: { type: s.pendingFailure } } : {})
400        },
401        turnId: input.turnId
402      })
403      next.open = []
404      next.checks = [] // nothing outstanding survives the end of a main turn
405      next.activeTurnId = null
406      next.lastStop = null
407      next.pendingFailure = null
408      break
409    }
410    case 'subagent.start': {
411      // only a start with an agent type counts; teammates are a distinct kind (contract §8)
412      if (input.agentType === '') break
413      if (input.agentId !== undefined) {
414        if (input.agentId in next.agents) break
415        if (Object.keys(next.agents).length >= COUNT_MAX) break
416        next.agents[input.agentId] = input.agentType
417      }
418      next.runningSubagents = Math.min(COUNT_MAX, next.runningSubagents + 1)
419      events.push({
420        t: 'subagent.started',
421        d: {
422          agentType: input.agentType,
423          ...(input.agentId !== undefined ? { agentId: input.agentId } : {})
424        }
425      })
426      break
427    }
428    case 'subagent.stop': {
429      if (input.agentType === '') break // the stray stop of smoke A4 (MOD-7)
430      let agentType = input.agentType
431      if (input.agentId !== undefined && input.agentId !== '') {
432        const known = next.agents[input.agentId]
433        if (known === undefined) break // an agent this sensor never counted moves nothing
434        agentType = known
435        delete next.agents[input.agentId]
436        next.stopped.push(input.agentId)
437        if (next.stopped.length > STOPPED_MAX)
438          next.stopped.splice(0, next.stopped.length - STOPPED_MAX)
439      }
440      next.runningSubagents = Math.max(0, next.runningSubagents - 1)
441      events.push({
442        t: 'subagent.stopped',
443        d: {
444          agentType,
445          ...(input.agentId !== undefined && input.agentId !== '' ? { agentId: input.agentId } : {})
446        }
447      })
448      break
449    }
450    case 'rebound':
451      return { state: neutralFleet(), events }
452  }
453  return { state: next, events }
454}
455
hooks/lib/command-core.ts 432 lines
1import {
2  BAND_DETAIL_MAX,
3  BAND_HINT_MAX,
4  BAND_LEAD_MAX,
5  BAND_TTL_MS,
6  CMD_DONE_MAX,
7  CONFIG_BOUNDS,
8  CONTEXT_MAX_CHARS,
9  type Command,
10  type CommandName,
11  type Config,
12  type ErrorCode,
13  type FeatureId
14} from '../contract'
15
16/**
17 * The `$`-free half of the command channel (P2W1 §7.7): cursor and dedupe arithmetic, the closed
18 * table of commands, argument bounds, the structural check of an untrusted response and the
19 * mapping of an engine rejection to an error code. `register.ts` owns the loop and the `$` calls.
20 */
21
22/** The `$.state` key `channel` (contract §22). */
23export interface ChannelState {
24  bootId: string | null
25  cursor: number
26  started: string[]
27  resulted: string[]
28  turnId: string | null
29}
30
31export const EMPTY_CHANNEL: Readonly<ChannelState> = {
32  bootId: null,
33  cursor: 0,
34  started: [],
35  resulted: [],
36  turnId: null
37}
38
39/** Keeps the newest `max` ids. */
40export const capIds = (ids: readonly string[], max = CMD_DONE_MAX): string[] =>
41  ids.length > max ? ids.slice(ids.length - max) : [...ids]
42
43const isIdList = (v: unknown): v is string[] =>
44  Array.isArray(v) && v.length <= CMD_DONE_MAX * 4 && v.every((x) => typeof x === 'string')
45
46/** What `$.state` held, read defensively: any other plugin can write it (types L3156). */
47export function parseChannel(raw: unknown): ChannelState {
48  if (typeof raw !== 'object' || raw === null)
49    return { ...EMPTY_CHANNEL, started: [], resulted: [] }
50  const r = raw as Record<string, unknown>
51  return {
52    bootId: typeof r.bootId === 'string' ? r.bootId : null,
53    cursor: Number.isSafeInteger(r.cursor) && (r.cursor as number) >= 0 ? (r.cursor as number) : 0,
54    started: isIdList(r.started) ? capIds(r.started) : [],
55    resulted: isIdList(r.resulted) ? capIds(r.resulted) : [],
56    turnId: typeof r.turnId === 'string' ? r.turnId : null
57  }
58}
59
60/** A cursor belongs to one host boot: a new boot restarts it at 0 (contract §6, commands 6). */
61export function forBoot(state: ChannelState, bootId: string): ChannelState {
62  return state.bootId === bootId ? state : { ...state, bootId, cursor: 0 }
63}
64
65export const withCursor = (state: ChannelState, n: number): ChannelState =>
66  n > state.cursor ? { ...state, cursor: n } : state
67
68export const markStarted = (state: ChannelState, cmd: string): ChannelState => ({
69  ...state,
70  started: capIds([...state.started, cmd])
71})
72
73export const markResulted = (state: ChannelState, cmd: string): ChannelState => ({
74  ...state,
75  resulted: capIds([...state.resulted, cmd])
76})
77
78// ---- the closed table of commands ----------------------------------------------------------------
79
80/** Contract §11.1 and §9: the feature each command needs. */
81export const COMMAND_FEATURE: Readonly<Record<CommandName, FeatureId>> = {
82  flush: 'act.channel',
83  'config.update': 'act.channel',
84  'turn.abort': 'act.turn',
85  'session.compact': 'act.compact',
86  'ui.toast': 'act.ui',
87  'ui.status': 'act.ui',
88  'prompt.submit': 'act.prompt',
89  'message.deliver': 'act.message',
90  'context.append': 'act.context',
91  'context.drop': 'act.context',
92  'guard.set': 'gate.guard',
93  'sentinel.set': 'gate.sentinel',
94  'ui.band.set': 'ui.band',
95  'plan.capture': 'act.plan'
96}
97
98/**
99 * The commands this build of the mod has a `case` for in `runHandler`. A name that is in the
100 * contract but not here is `CMD_UNSUPPORTED`: a later wave adds its name with its `case`.
101 */
102export const IMPLEMENTED_COMMANDS: ReadonlySet<string> = new Set([
103  'flush',
104  'config.update',
105  'turn.abort',
106  'session.compact',
107  'ui.toast',
108  'ui.status',
109  'context.append',
110  'ui.band.set'
111])
112
113/** The tokenless second lock (contract §9): every other command is `CMD_UNSUPPORTED` without a token. */
114export const TOKENLESS_OK: ReadonlySet<string> = new Set(['flush', 'config.update', 'ui.band.set'])
115
116/** A reload after the `$` call is no proof of non-delivery (contract §6, commands 5). */
117const SUBMIT_COMMANDS: ReadonlySet<string> = new Set(['prompt.submit', 'message.deliver'])
118
119export const UI_TEXT_MAX = 200
120const MESSAGE_MAX = 512
121
122export type Disposition =
123  | { kind: 'skip' }
124  | { kind: 'run' }
125  | { kind: 'answer'; code: ErrorCode; message?: string; data?: unknown }
126
127export interface ClassifyContext {
128  state: ChannelState
129  /** Ids a running call in THIS load will answer. */
130  inFlight: ReadonlySet<string>
131  now: number
132  tokenBacked: boolean
133  featureEnabled(feature: FeatureId): boolean
134  /** A handler is registered for this name. Default: the name is in the closed table. */
135  known?(name: string): boolean
136}
137
138/** The executor's table (spec §7.7): exactly one `command.result` per `cmd`. */
139export function classifyCommand(c: Command, ctx: ClassifyContext): Disposition {
140  if (ctx.state.resulted.includes(c.cmd)) return { kind: 'skip' }
141  if (ctx.inFlight.has(c.cmd)) return { kind: 'skip' }
142  if (ctx.state.started.includes(c.cmd)) {
143    return {
144      kind: 'answer',
145      code: 'CMD_FAILED',
146      message: 'interrupted by reload',
147      ...(SUBMIT_COMMANDS.has(c.name) ? { data: { submitted: 'unknown' } } : {})
148    }
149  }
150  if (ctx.now >= c.expiresAt) return { kind: 'answer', code: 'CMD_EXPIRED' }
151  const known = Object.hasOwn(COMMAND_FEATURE, c.name) && (ctx.known?.(c.name) ?? true)
152  if (!known) return { kind: 'answer', code: 'CMD_UNSUPPORTED' }
153  if (!ctx.tokenBacked && !TOKENLESS_OK.has(c.name))
154    return { kind: 'answer', code: 'CMD_UNSUPPORTED' }
155  // A tokenless mod runs its three commands without looking at `enable` (contract §21 item 5): the
156  // external enable set carries no `act.*`, and the host decides what it sends.
157  if (ctx.tokenBacked && !ctx.featureEnabled(COMMAND_FEATURE[c.name]))
158    return { kind: 'answer', code: 'FEATURE_DISABLED' }
159  return { kind: 'run' }
160}
161
162// ---- untrusted input -------------------------------------------------------------------------------
163
164const isRec = (v: unknown): v is Record<string, unknown> =>
165  typeof v === 'object' && v !== null && !Array.isArray(v)
166
167/**
168 * The commands of a response, structurally checked and in `n` order. The host's response is
169 * untrusted (SEC-3d): what is not shaped like a command is dropped, nothing is evaluated.
170 */
171export function parseCommands(raw: unknown): Command[] {
172  if (!Array.isArray(raw)) return []
173  const out: Command[] = []
174  for (const c of raw.slice(0, 64)) {
175    if (!isRec(c)) continue
176    if (typeof c.cmd !== 'string' || !c.cmd.startsWith('cmd_') || c.cmd.length > 128) continue
177    if (typeof c.name !== 'string' || c.name.length === 0 || c.name.length > 64) continue
178    if (!Number.isSafeInteger(c.n) || (c.n as number) < 1) continue
179    if (typeof c.issuedAt !== 'number' || !Number.isFinite(c.issuedAt)) continue
180    if (typeof c.expiresAt !== 'number' || !Number.isFinite(c.expiresAt)) continue
181    out.push({
182      cmd: c.cmd as Command['cmd'],
183      n: c.n as number,
184      name: c.name as CommandName,
185      args: (isRec(c.args) ? c.args : {}) as Command['args'],
186      issuedAt: c.issuedAt,
187      expiresAt: c.expiresAt
188    })
189  }
190  return out.sort((a, b) => a.n - b.n)
191}
192
193/**
194 * `config.update`: every field against `CONFIG_BOUNDS`, all or none. `null` is a precondition
195 * failure (a value outside the bounds, an unknown field, an empty update).
196 */
197export function parseConfigUpdate(args: unknown): Partial<Config> | null {
198  if (!isRec(args) || !isRec(args.config)) return null
199  const keys = Object.keys(args.config)
200  if (keys.length === 0) return null
201  const out: Partial<Config> = {}
202  for (const k of keys) {
203    if (!Object.hasOwn(CONFIG_BOUNDS, k)) return null
204    const v = args.config[k]
205    const [min, max] = CONFIG_BOUNDS[k as keyof Config]
206    if (typeof v !== 'number' || !Number.isInteger(v) || v < min || v > max) return null
207    out[k as keyof Config] = v
208  }
209  return out
210}
211
212// ---- context.append (T257 U2a-ii) ------------------------------------------------------------------
213
214/** The one context key this build of the mod appends: the others belong to a later wave (P2W4). */
215export const REVIEW_SELECTION_KEY = 'harnu.review-selection'
216
217/**
218 * `context.append` (second lock, spec T257 §6.3): exactly `{ key, text, durable }`, the review key,
219 * `durable: false` and 1 to `CONTEXT_MAX_CHARS` characters. The mod stores nothing of it: a row is
220 * appended once and is lost with the conversation on a compaction, by design.
221 */
222export function parseContextAppend(
223  args: unknown
224): { ok: true; text: string } | { ok: false; message: string } {
225  if (!isRec(args)) return { ok: false, message: 'the arguments are not an object' }
226  if (Object.keys(args).some((k) => k !== 'key' && k !== 'text' && k !== 'durable'))
227    return { ok: false, message: 'an unknown argument' }
228  if (args.key !== REVIEW_SELECTION_KEY)
229    return { ok: false, message: 'this mod appends only the review selection key' }
230  if (args.durable !== false) return { ok: false, message: 'only a non-durable row is supported' }
231  const text = args.text
232  if (typeof text !== 'string' || text.length === 0)
233    return { ok: false, message: 'the text is empty' }
234  if (text.length > CONTEXT_MAX_CHARS)
235    return { ok: false, message: `the text is over ${CONTEXT_MAX_CHARS} characters` }
236  return { ok: true, text }
237}
238
239// ---- ui.band.set (T257 U2a-ii, P4W2 §7.4) --------------------------------------------------------------
240
241/** The `$.state` key `band`: the one line the view draws. `n` is the `Command.n` that set it. */
242export interface BandState {
243  v: 1
244  lead: string
245  detail?: string
246  hint?: string
247  n: number
248  expiresAt: number
249}
250
251/** C0 and C1 controls, line and paragraph separators, and the bidi overrides a path could carry. */
252// eslint-disable-next-line no-control-regex
253const BAND_UNSAFE = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/g
254const clean = (s: string): string => s.replace(BAND_UNSAFE, '')
255
256/** What `ui.band.set` asks for: clear the band, or set these (already cleaned) parts. */
257export type BandRequest =
258  { kind: 'clear' } | { kind: 'set'; lead: string; detail?: string; hint?: string }
259
260/**
261 * `ui.band.set` (second lock, contract §9): `parts` are cleaned of control characters and checked
262 * against the lengths the host checked; a `link` is dropped and the line is kept (the band carries
263 * no href). `null` is a precondition failure (no parts, an empty or over-long part).
264 */
265export function parseBandSet(args: unknown): BandRequest | null {
266  if (!isRec(args)) return null
267  if (args.line === null) return { kind: 'clear' }
268  if (typeof args.line !== 'string' || !isRec(args.parts)) return null
269  const part = (v: unknown, max: number): string | null | undefined => {
270    if (v === undefined) return undefined
271    if (typeof v !== 'string') return null
272    const s = clean(v)
273    return s.length > max ? null : s
274  }
275  const lead = part(args.parts.lead, BAND_LEAD_MAX)
276  const detail = part(args.parts.detail, BAND_DETAIL_MAX)
277  const hint = part(args.parts.hint, BAND_HINT_MAX)
278  if (lead === undefined || lead === null || lead.trim() === '') return null
279  if (detail === null || hint === null) return null
280  return {
281    kind: 'set',
282    lead,
283    ...(detail !== undefined && detail !== '' ? { detail } : {}),
284    ...(hint !== undefined && hint !== '' ? { hint } : {})
285  }
286}
287
288/** What `$.state` held under `band`, read defensively: any other plugin can write it. */
289export function parseBandState(raw: unknown): BandState | null {
290  if (!isRec(raw) || raw.v !== 1) return null
291  if (typeof raw.lead !== 'string' || raw.lead === '') return null
292  if (!Number.isSafeInteger(raw.n) || typeof raw.expiresAt !== 'number') return null
293  if (!Number.isFinite(raw.expiresAt)) return null
294  return {
295    v: 1,
296    lead: raw.lead,
297    ...(typeof raw.detail === 'string' && raw.detail !== '' ? { detail: raw.detail } : {}),
298    ...(typeof raw.hint === 'string' && raw.hint !== '' ? { hint: raw.hint } : {}),
299    n: raw.n as number,
300    expiresAt: raw.expiresAt
301  }
302}
303
304/** A band stands until its `expiresAt`; the clock is the mod's. */
305export const bandLive = (b: BandState | null, now: number): b is BandState =>
306  b !== null && now < b.expiresAt
307
308/**
309 * The next band state, or `null` for "leave it": a lower `n` never overwrites a higher one, and a
310 * clear is a state too. `known` is the highest `n` this load has applied.
311 */
312export function applyBand(
313  req: BandRequest,
314  n: number,
315  now: number,
316  stored: BandState | null,
317  known: number
318): { apply: true; next: BandState | null } | { apply: false } {
319  if (n < Math.max(known, stored?.n ?? 0)) return { apply: false }
320  if (req.kind === 'clear') return { apply: true, next: null }
321  return {
322    apply: true,
323    next: {
324      v: 1,
325      lead: req.lead,
326      ...(req.detail !== undefined ? { detail: req.detail } : {}),
327      ...(req.hint !== undefined ? { hint: req.hint } : {}),
328      n,
329      expiresAt: now + BAND_TTL_MS
330    }
331  }
332}
333
334/**
335 * The features the band hook buys (contract §11): `act.context` and `ui.band`, only when the
336 * `ui.render` registration took AND the base set (identity, channel) is declared. A CLI without the
337 * hook declares neither, and the host never enables them.
338 */
339export const bandFeatures = (
340  registered: Readonly<Record<string, boolean>>,
341  base: boolean
342): FeatureId[] => (base && registered['ui.render'] === true ? ['act.context', 'ui.band'] : [])
343
344/** The band sweep: how often a standing line is checked against its `expiresAt`. */
345export const BAND_SWEEP_MS = 30_000
346
347/** Below this the band is the compact line (the range alone); at it and above, the full one. */
348export const BAND_MIN_COLUMNS = 40
349const BAND_MARK = '\u25c6 Harnu '
350
351/**
352 * The range at the end of a band lead the host built (`⧉ speech.ts L85–92`, `⧉ speech.ts old L85
353 * – new L92`, `⧉ L85`, `⧉ speech.ts (file)`), or `null` when the lead does not end in one. The host
354 * already puts the range in the lead, so the compact line needs no new field and no contract change.
355 * The longest form is tried first, so a range across both sides is not read as its last half.
356 */
357// Built from strings: the API-surface scan reads a `$` in code as the engine's `$` (MOD-1).
358const RANGE_TAIL = new RegExp(
359  '(?:^| )((?:old|new) L\\d+ \\u2013 (?:old|new) L\\d+|(?:old )?L\\d+(?:\\u2013\\d+)?|\\(file\\))$'
360)
361
362const MIXED_RANGE = new RegExp('^(?:old|new) L(\\d+) \\u2013 (?:old|new) L(\\d+)$')
363
364/**
365 * The compact line, for a pane under {@link BAND_MIN_COLUMNS}: `⧉ L21`, `⧉ L21–24`, `⧉ (file)`, and
366 * for a range across both sides its explicit form `⧉ old L85 – new L92`, shortened to `⧉ L85–L92`
367 * when that does not fit. No mark, no file name. The first form that fits is returned; when none
368 * does (the shortest is 4 columns, `⧉ L9`) nothing is drawn: a cut-off range would name the wrong
369 * lines.
370 */
371function fitCompact(lead: string, columns: number): string | null {
372  const range = RANGE_TAIL.exec(lead)?.[1]
373  if (range === undefined) return null
374  const mixed = MIXED_RANGE.exec(range)
375  const forms = [`\u29c9 ${range}`, ...(mixed ? [`\u29c9 L${mixed[1]}\u2013L${mixed[2]}`] : [])]
376  return forms.find((f) => f.length <= columns) ?? null
377}
378
379/**
380 * The text of the one row, fitted to `bodyColumns` (P4W2 §7.4): under 40 the compact line (range
381 * only, {@link fitCompact}), 40-79 the lead, 80-109 the lead (no link), 110-143 lead and detail, 144
382 * and up lead, detail and hint. A part that is not there leaves no separator. Cut at the width with
383 * an ellipsis, never wider.
384 */
385export function fitBand(b: BandState, columns: number): string | null {
386  if (!Number.isFinite(columns) || columns < 0) return null
387  if (columns < BAND_MIN_COLUMNS) return fitCompact(b.lead, columns)
388  const parts = [b.lead]
389  if (columns >= 110 && b.detail !== undefined) parts.push(b.detail)
390  if (columns >= 144 && b.hint !== undefined) parts.push(b.hint)
391  const row = `${BAND_MARK}${parts.join(' \u00b7 ')}`
392  return row.length <= columns ? row : `${row.slice(0, Math.max(1, columns - 1))}\u2026`
393}
394
395// ---- the engine's rejections ---------------------------------------------------------------------------
396
397const NO_TURN = /no turn is running/i
398const TURN_RUNNING = /a turn is running/i
399const messageOf = (err: unknown): string =>
400  (err instanceof Error ? err.message : String(err)).slice(0, MESSAGE_MAX)
401
402/**
403 * The two rejection texts the smoke runs recorded are preconditions: the engine refused the call,
404 * the channel worked. Anything else is a failure carrying the engine's text (OQ-2).
405 */
406export function mapEngineRejection(err: unknown): { code: ErrorCode; message: string } {
407  const message = messageOf(err)
408  if (NO_TURN.test(message) || TURN_RUNNING.test(message))
409    return { code: 'CMD_PRECONDITION', message }
410  return { code: 'CMD_FAILED', message }
411}
412
413/** The 30 s fetch cap is a normal reconnect, never an error (contract §7 end, D3). */
414export const isHardCapAbort = (err: unknown): boolean =>
415  /no complete answer within \d+\s*ms/i.test(messageOf(err))
416
417const num = (v: unknown): number | undefined =>
418  typeof v === 'number' && Number.isFinite(v) ? v : undefined
419
420/** A skipped compaction is ok with `{ skipped: true }`; the counts are optional (types L10050). */
421export function compactData(
422  r: unknown
423): { skipped: true } | { tokensBefore?: number; tokensAfter?: number } {
424  if (isRec(r) && typeof r.skip === 'string') return { skipped: true }
425  const before = isRec(r) ? num(r.tokensBefore) : undefined
426  const after = isRec(r) ? num(r.tokensAfter) : undefined
427  return {
428    ...(before !== undefined ? { tokensBefore: before } : {}),
429    ...(after !== undefined ? { tokensAfter: after } : {})
430  }
431}
432
hooks/lib/admitted.ts 92 lines
1import type { EventPayloads } from '../contract'
2
3/**
4 * `$`-free mapping of a `plugin.register` input to the `mod.admitted` payload (contract §8,
5 * P4W1 part B). The input is the engine's own, but the mapping is written as if it were not: a
6 * shape it does not recognise is not an admission (the hook then just passes the event on), and
7 * every list and string is bounded so one admission always fits a batch (BATCH_MAX_BYTES).
8 */
9
10export type Admitted = EventPayloads['mod.admitted']
11
12/** At most this many entries per list of `uses`; the rest is dropped, never an error. */
13export const USES_LIST_MAX = 100
14const STR_MAX = 256
15const ROOT_MAX = 1024
16const TIERS: ReadonlySet<string> = new Set(['prepend', 'user', 'append', 'builtin'])
17
18const isRec = (v: unknown): v is Record<string, unknown> =>
19  typeof v === 'object' && v !== null && !Array.isArray(v)
20
21const str = (v: unknown, max: number): string | null =>
22  typeof v === 'string' && v.length > 0 && v.length <= max ? v : null
23
24/** A list of strings; entries that are not short strings are skipped, the list is cut. */
25function strings(v: unknown): string[] | null {
26  if (v === undefined) return []
27  if (!Array.isArray(v)) return null
28  const out: string[] = []
29  for (const item of v) {
30    const s = str(item, STR_MAX)
31    if (s !== null) out.push(s)
32    if (out.length === USES_LIST_MAX) break
33  }
34  return out
35}
36
37function stateRefs(v: unknown): { plugin: string; key: string }[] | null {
38  if (v === undefined) return []
39  if (!Array.isArray(v)) return null
40  const out: { plugin: string; key: string }[] = []
41  for (const item of v) {
42    if (!isRec(item)) continue
43    const plugin = str(item.plugin, STR_MAX)
44    const key = str(item.key, STR_MAX)
45    if (plugin !== null && key !== null) out.push({ plugin, key })
46    if (out.length === USES_LIST_MAX) break
47  }
48  return out
49}
50
51/** `null` when the input is not the shape of contract §8's `mod.admitted`. Never throws. */
52export function toAdmitted(input: unknown): Admitted | null {
53  try {
54    if (!isRec(input)) return null
55    const name = str(input.name, STR_MAX)
56    const root = str(input.root, ROOT_MAX)
57    const provenance = str(input.provenance, STR_MAX)
58    const tier = typeof input.tier === 'string' && TIERS.has(input.tier) ? input.tier : null
59    if (name === null || root === null || provenance === null || tier === null) return null
60    if (!isRec(input.uses)) return null
61    const uses = input.uses
62    const events = strings(uses.events)
63    const calls = strings(uses.calls)
64    if (events === null || calls === null) return null
65    const env = isRec(uses.env) ? uses.env : {}
66    const state = isRec(uses.state) ? uses.state : {}
67    const envReads = strings(env.reads)
68    const envWrites = strings(env.writes)
69    const stateReads = stateRefs(state.reads)
70    const stateWrites = stateRefs(state.writes)
71    if (envReads === null || envWrites === null || stateReads === null || stateWrites === null) {
72      return null
73    }
74    const version = str(input.version, STR_MAX)
75    return {
76      name,
77      tier: tier as Admitted['tier'],
78      root,
79      ...(version !== null ? { version } : {}),
80      provenance,
81      uses: {
82        events,
83        calls,
84        env: { reads: envReads, writes: envWrites },
85        state: { reads: stateReads, writes: stateWrites }
86      }
87    }
88  } catch {
89    return null
90  }
91}
92
hooks/lib/ring.ts 105 lines
1import type { EventName, WireEvent } from '../contract'
2
3/**
4 * The mod's event ring (contract §6): at-least-once delivery. Events stay here until a response
5 * acknowledges them; a `$` call in flight dies with an aborted turn (smoke A4), so nothing is
6 * removed on send. Pure and `$`-free.
7 *
8 * Over `max` the ring drops coalescable events first (`usage.measured`: keep the newest, every
9 * figure in it is cumulative), then the oldest, and counts what it dropped.
10 */
11
12/** Event types whose newest instance supersedes every older one. */
13const COALESCABLE: ReadonlySet<EventName> = new Set<EventName>(['usage.measured'])
14
15export type NewEvent = Omit<WireEvent, 'seq'>
16
17export interface Ring {
18  /** Assigns the next `seq`, stores the event, enforces `max`. */
19  push(ev: NewEvent): WireEvent
20  /** The oldest unacknowledged events, within both limits, always at least one if any exist. */
21  batch(maxEvents: number, maxBytes: number): WireEvent[]
22  /** Removes every event whose `seq` is at or below `seq`. */
23  ack(seq: number): void
24  /** Events dropped by `overflow` and not yet reported as accepted. */
25  dropped(): number
26  /** A batch carrying `n` was accepted: those drops are reported. */
27  settleDropped(n: number): void
28  /** Number of unacknowledged events. */
29  size(): number
30  /** A new `conn` restarts `seq` at 1: renumber what is left, in order. */
31  renumber(): void
32  /** Forget everything (inert, dormant). */
33  clear(): void
34  /** Drops until `size() <= max`: coalescable first, then the oldest. Returns the count dropped. */
35  overflow(): number
36}
37
38export function createRing(max: number): Ring {
39  let events: WireEvent[] = []
40  let nextSeq = 1
41  let droppedCount = 0
42
43  function overflow(): number {
44    let n = 0
45    while (events.length > max) {
46      // keep the newest coalescable event, drop an older one of the same type
47      let victim = -1
48      const seen = new Set<EventName>()
49      for (let i = events.length - 1; i >= 0; i--) {
50        const t = events[i]?.t
51        if (t === undefined || !COALESCABLE.has(t)) continue
52        if (seen.has(t)) {
53          victim = i
54          break
55        }
56        seen.add(t)
57      }
58      if (victim < 0) victim = 0
59      events.splice(victim, 1)
60      n++
61    }
62    droppedCount += n
63    return n
64  }
65
66  return {
67    push(ev) {
68      const full: WireEvent = { ...ev, seq: nextSeq++ }
69      events.push(full)
70      overflow()
71      return full
72    },
73    batch(maxEvents, maxBytes) {
74      const out: WireEvent[] = []
75      let bytes = 0
76      for (const e of events) {
77        if (out.length >= Math.max(1, maxEvents)) break
78        const size = JSON.stringify(e).length
79        if (out.length > 0 && bytes + size > maxBytes) break
80        out.push(e)
81        bytes += size
82      }
83      return out
84    },
85    ack(seq) {
86      events = events.filter((e) => e.seq > seq)
87    },
88    dropped: () => droppedCount,
89    settleDropped(n) {
90      droppedCount = Math.max(0, droppedCount - n)
91    },
92    size: () => events.length,
93    renumber() {
94      events = events.map((e, i) => ({ ...e, seq: i + 1 }))
95      nextSeq = events.length + 1
96    },
97    clear() {
98      events = []
99      nextSeq = 1
100      droppedCount = 0
101    },
102    overflow
103  }
104}
105
hooks/surface.tsx 27 lines
1import type { ElementTable, RenderChildren } from 'claude-code'
2import { fitBand, type BandState } from './lib/command-core'
3
4/**
5 * The band's view (P4W2 §7.4, T257 §8): one dim row above the prompt. A pure builder: it receives
6 * the resolved elements, never `$` (MOD-1), and reads no state. `null` means "draw nothing"; otherwise the row wraps `below`, the tree the rest of the chain
7 * drew, and never replaces it.
8 */
9export function bandView(
10  els: ElementTable<'terminal'>,
11  band: BandState,
12  columns: number,
13  below: RenderChildren
14) {
15  const text = fitBand(band, columns)
16  if (text === null) return null
17  const { Box, Text } = els
18  return (
19    <Box flexDirection="column">
20      <Text dimColor wrap="truncate">
21        {text}
22      </Text>
23      {below}
24    </Box>
25  )
26}
27
hooks/lib/usage-sensor.ts 95 lines
1import type { EventPayloads } from '../contract'
2
3/**
4 * The `sense.usage` sensor, pure and `$`-free (spec P1W6 §7.1): it normalizes what
5 * `session.measure` and `$.session.usage()` carry into the `usage.measured` payload. Figures and
6 * nothing else leave this file: no prompt text, no answer text, no `context.breakdown` (it is
7 * never requested). Numbers are passed through as the CLI gave them; the host validates ranges.
8 */
9
10type Units = EventPayloads['usage.measured']['changed']
11export type UsagePayload = EventPayloads['usage.measured']
12
13/** The part of `SessionContextUsage` the sensor reads. */
14interface ContextShape {
15  window?: unknown
16  tokens?: unknown
17  percent?: unknown
18}
19
20/** The part of `SessionMeasureInput` / `SessionUsage` the sensor reads. */
21export interface UsageShape {
22  context?: ContextShape | null
23  rateLimits?: unknown
24  cost?: { usd?: unknown } | null
25  changed?: unknown
26  startedAt?: unknown
27}
28
29const UNITS: readonly string[] = ['context', 'rateLimits', 'cost']
30
31const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v)
32
33function contextOf(c: ContextShape | null | undefined): UsagePayload['context'] {
34  if (!c || typeof c !== 'object' || !isNum(c.window)) return undefined
35  return {
36    window: c.window,
37    ...(isNum(c.tokens) ? { tokens: c.tokens } : {}),
38    ...(isNum(c.percent) ? { percent: c.percent } : {})
39  }
40}
41
42/** `{ kind, percentUsed, resetsAt? }` per window; an entry that is not that shape is dropped. */
43function limitsOf(raw: unknown): UsagePayload['rateLimits'] {
44  if (!Array.isArray(raw)) return []
45  const out: UsagePayload['rateLimits'] = []
46  for (const r of raw as Record<string, unknown>[]) {
47    if (!r || typeof r.kind !== 'string' || !isNum(r.percentUsed)) continue
48    out.push({
49      kind: r.kind,
50      percentUsed: r.percentUsed,
51      ...(typeof r.resetsAt === 'string' ? { resetsAt: r.resetsAt } : {})
52    })
53  }
54  return out
55}
56
57function unitsIn(raw: unknown): Units {
58  if (!Array.isArray(raw)) return []
59  return raw.filter((u): u is Units[number] => typeof u === 'string' && UNITS.includes(u))
60}
61
62function body(u: UsageShape): Omit<UsagePayload, 'source' | 'changed'> {
63  const context = contextOf(u.context)
64  return {
65    ...(context !== undefined ? { context } : {}),
66    rateLimits: limitsOf(u.rateLimits),
67    ...(u.cost && isNum(u.cost.usd) ? { costUsd: u.cost.usd } : {})
68  }
69}
70
71/** A `session.measure` event: the figures and the units the CLI says moved. */
72export function measurePayload(e: UsageShape): UsagePayload {
73  return { source: 'measure', ...body(e), changed: unitsIn(e.changed) }
74}
75
76/**
77 * The answer of `$.session.usage()` (and `$.session.model()`), sent after a hello, a resync or a
78 * flush. A re-send of state, not a moved unit: `changed` names every unit that has a figure so a
79 * host that lost the earlier readings can rebuild its picture.
80 */
81export function readPayload(u: UsageShape, model: unknown): UsagePayload {
82  const b = body(u)
83  const changed: Units = []
84  if (b.context !== undefined) changed.push('context')
85  if (b.rateLimits.length > 0) changed.push('rateLimits')
86  if (b.costUsd !== undefined) changed.push('cost')
87  return {
88    source: 'read',
89    ...b,
90    changed,
91    ...(isNum(u.startedAt) ? { startedAt: u.startedAt } : {}),
92    ...(typeof model === 'string' && model !== '' ? { model } : {})
93  }
94}
95
hooks/lib/rendezvous-parse.ts 67 lines
1import { PROTOCOL_VERSION, type BootId, type EndpointName } from '../contract'
2
3/**
4 * Validates the content of the rendezvous file before the mod uses it (SEC-4, contract §2). Pure
5 * and `$`-free: the path to the file is baked at staging, and the file itself is untrusted input.
6 * A `socketPath` that is not inside the directory of the rendezvous file is refused.
7 */
8
9export interface Endpoint {
10  transport: 'unix' | 'tcp'
11  socketPath?: string
12  port?: number
13  token: string
14  bootId: BootId
15  protoMin: number
16  protoMax: number
17}
18
19const dirOf = (path: string): string => {
20  const cut = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))
21  return cut <= 0 ? '' : path.slice(0, cut)
22}
23
24/** Absolute, no NUL, no `..` segment, and strictly inside `dir`. */
25export function insideDir(path: string, dir: string): boolean {
26  if (dir === '' || path.includes('\0') || !path.startsWith('/')) return false
27  if (!path.startsWith(`${dir}/`) || path.length === dir.length + 1) return false
28  return !path.split('/').includes('..')
29}
30
31/** `null` for anything the mod must not connect to, and for a host with no protocol overlap. */
32export function parseEndpoint(raw: string, rendezvousPath: string): Endpoint | null {
33  let parsed: unknown
34  try {
35    parsed = JSON.parse(raw)
36  } catch {
37    return null
38  }
39  if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null
40  const f = parsed as Record<string, unknown>
41  if (f.v !== 1) return null
42  if (typeof f.token !== 'string' || f.token.length === 0 || f.token.length > 512) return null
43  if (typeof f.bootId !== 'string' || f.bootId.length === 0 || f.bootId.length > 128) return null
44  const { protoMin, protoMax } = f
45  if (typeof protoMin !== 'number' || typeof protoMax !== 'number') return null
46  if (!Number.isInteger(protoMin) || !Number.isInteger(protoMax) || protoMin > protoMax) return null
47  if (PROTOCOL_VERSION < protoMin || PROTOCOL_VERSION > protoMax) return null
48  const base = { token: f.token, bootId: f.bootId as BootId, protoMin, protoMax }
49  if (f.transport === 'unix') {
50    if (typeof f.socketPath !== 'string') return null
51    if (!insideDir(f.socketPath, dirOf(rendezvousPath))) return null
52    return { ...base, transport: 'unix', socketPath: f.socketPath }
53  }
54  if (f.transport === 'tcp') {
55    const port = f.port
56    if (typeof port !== 'number' || !Number.isInteger(port) || port < 1 || port > 65535) return null
57    return { ...base, transport: 'tcp', port }
58  }
59  return null
60}
61
62/** `http://harnu/v1/<route>` over a Unix socket, `http://127.0.0.1:<port>/v1/<route>` over TCP. */
63export function endpointUrl(ep: Endpoint, route: EndpointName): string {
64  const host = ep.transport === 'unix' ? 'harnu' : `127.0.0.1:${ep.port}`
65  return `http://${host}/v1/${route}`
66}
67
types/index.d.ts 76 lines
1// The plugin's contract. Each wave declares its own `$.state` keys here, in its own change.
2// Self-contained on purpose (no import): the shapes mirror `hooks/contract.ts` (spec 01-contract §22).
3declare module 'claude-code' {
4  interface PluginState {
5    'harnu-companion': {
6      /** P1W3: the host's per-connection id. Correlation, not authentication (contract §3). */
7      conn: `c_${string}`
8      /** P1W3: the host boot the `conn` belongs to. */
9      bootId: string
10      /** P1W3: the id the host has for this binding (the bound sid), not a fresh `$.session.id()`. */
11      sid: string
12      /** P1W3: captured from `session.start`; a resume hello needs it after a reload. */
13      boot: { cwd: string; surface: string | null; isInteractive: boolean }
14      /** P1W3: facts about the process; `classic` flips on the first `classic.*` dispatch. */
15      probes: { classic: boolean; toolCheck: boolean }
16      /** P1W5: the last `permission_mode` of any `classic.*` payload; absent until one is seen. */
17      permissionMode: string
18      /**
19       * P1W5: the fleet sensors' state (contract §22), read back after a reload so the re-sent
20       * `session.snapshot` is correct. Reset to the neutral state by a rebound. `agents` holds the
21       * per-agent facts, keyed on the agent id (the subagents this sensor counted).
22       */
23      fleet: {
24        activeTurnId: string | null
25        nextOrigin: 'human' | 'plugin' | 'peer' | 'unknown'
26        open: {
27          kind: 'permission' | 'idle' | 'input'
28          toolUseId?: string
29          tool?: string
30          agentId?: string
31        }[]
32        checks: {
33          toolUseId: string
34          tool: string
35          inputKey?: string
36          at: number
37          claimedBy?: string
38          agentId?: string
39          hook?: string
40        }[]
41        runningSubagents: number
42        lastStop: { all: number; subagents: number } | null
43        pendingFailure: string | null
44        agents: Record<string, string>
45        /** The ids of subagents that already stopped: the CLI still lists them as `running`. */
46        stopped: string[]
47      }
48      /**
49       * P2W1: the command dedupe (contract §22). `cursor` acknowledges delivery, `resulted` execution;
50       * the two id lists are capped at `CMD_DONE_MAX`; `turnId` is the last `turn.start` id.
51       */
52      channel: {
53        bootId: string
54        cursor: number
55        started: string[]
56        resulted: string[]
57        turnId: string | null
58      }
59      /**
60       * T257 / P4W2: the one line above the prompt, written by `ui.band.set` and read by the
61       * `AbovePrompt` hook. `n` is the `Command.n` that set it (a lower `n` never overwrites a
62       * higher one); `expiresAt` is the mod's clock plus `BAND_TTL_MS` at apply time. Display text
63       * only, no link and no ticket. `null` once cleared or expired.
64       */
65      band: {
66        v: 1
67        lead: string
68        detail?: string
69        hint?: string
70        n: number
71        expiresAt: number
72      } | null
73    }
74  }
75}
76