SLOPSHOPPER

plannotator

Interactive Plan Review: Mark up and refine your plans using a UI, easily share for team collaboration, automatically integrates with plan mode hooks.

guardcommandtoaststatusprompttool
★ 9,669v0.28.31Apache-2.0updated 2026-10-26backnotprop/plannotator/apps/hook
A shopper browsing a rack in a slop shop
README

Plannotator Claude Code Plugin

This directory contains the Claude Code plugin configuration for Plannotator.

Prerequisites

Install the plannotator command so Claude Code can use it:

macOS / Linux / WSL:

curl -fsSL https://plannotator.ai/install.sh | bash

Windows PowerShell:

irm https://plannotator.ai/install.ps1 | iex

Windows CMD:

curl -fsSL https://plannotator.ai/install.cmd -o install.cmd && install.cmd && del install.cmd

Released binaries ship with SHA256 sidecars and SLSA build provenance attestations from v0.17.2 onwards. See the installation docs for version pinning and the verification docs for verification commands.


Plugin Installation · Manual Installation (Hooks) · Obsidian Integration


Plugin Installation

In Claude Code:

/plugin marketplace add backnotprop/plannotator
/plugin install plannotator@plannotator

Important: Restart Claude Code after installing the plugin for the hooks to take effect.

Updating the plugin

Refreshing the marketplace alone does not update an installed plugin. From a terminal:

claude plugin marketplace update plannotator
claude plugin update plannotator@plannotator

Or inside Claude Code: run /plugin marketplace update plannotator, then open /plugin, go to Installed, select plannotator and choose Update now. Then restart Claude Code. Run the install script again to update the plannotator binary.

Manual Installation (Hooks)

If you prefer not to use the plugin system, add this to your ~/.claude/settings.json:

{
  "hooks": {
    "PermissionRequest": [
      {
        "matcher": "ExitPlanMode",
        "hooks": [
          {
            "type": "command",
            "command": "plannotator",
            "timeout": 345600
          }
        ]
      }
    ]
  }
}

How It Works

The Plannotator mod (Claude Code 2.1.287+)

In the interactive terminal on Claude Code 2.1.287 or newer, the plugin runs the Plannotator mod. It is on by default:

  • Plan review, /plannotator-review, /plannotator-annotate and /plannotator-last don't make Claude wait. Claude ends its turn and your decision arrives later as a message. You can keep chatting meanwhile.
  • A revised plan updates the same tab. After you approve, Claude calls ExitPlanMode once more and works from the exact plan text you approved.
  • Claude can open Plannotator itself with its plannotator tool.
  • Ask AI in the review is answered by this Claude session ("Ask this session").

While a plan review is open Claude is not blocked, so if you leave plan mode yourself before you approve, it can start editing.

Turn the mod off with PLANNOTATOR_CLAUDE_MOD=0 or { "claudeCodeMod": false } in ~/.plannotator/config.json (read when Claude Code starts). Older Claude Code, claude -p and SDK runs, and Windows always use the classic hook below.

The classic hook

When Claude Code calls ExitPlanMode, this hook intercepts and waits for your decision (Claude waits too):

  1. Opens Plannotator UI in your browser
  2. Lets you annotate the plan visually
  3. Approve → Claude proceeds with implementation
  4. Request changes → Your annotations are sent back to Claude
  5. On resubmission → Plan Diff shows what changed since the last version

Environment Variables

VariableDescription
PLANNOTATOR_REMOTESet to 1 / true for remote mode, 0 / false for local mode, or leave unset for SSH auto-detection. Uses a fixed port in remote mode; browser-opening behavior depends on the environment.
PLANNOTATOR_PORTFixed port to use. Default: random locally, 19432 for remote sessions.
PLANNOTATOR_BROWSERCustom browser to open plans in. macOS: app name or path. Linux/Windows: executable path. none (also false, 0, off, no, true, 1, :) opens no browser at all; the session URL is always printed.
PLANNOTATOR_SHARE_URLCustom share portal URL for self-hosting. Default: https://share.plannotator.ai.
PLANNOTATOR_CLAUDE_MODThe Plannotator mod is on by default. Set to 0 / false / off / disabled to turn it off and use the classic hook. Read when Claude Code starts.
PLANNOTATOR_MOD_DEBUGSet to 1 before starting Claude Code to write a mod debug log to ~/.plannotator/claude-code-mod/debug.log.

Remote / Devcontainer Usage

When running Claude Code in a remote environment (SSH, devcontainer, WSL), set PLANNOTATOR_REMOTE=1 (or true) and these environment variables:

export PLANNOTATOR_REMOTE=1
export PLANNOTATOR_PORT=9999  # Choose a port you'll forward

This tells Plannotator to:

  • Use a fixed port instead of a random one (so you can set up port forwarding)
  • Use remote-friendly port/browser handling for forwarded environments
  • Print the URL to the terminal for you to access

Port forwarding in VS Code devcontainers: The port should be automatically forwarded. Check the "Ports" tab.

SSH port forwarding: Add to your ~/.ssh/config:

Host your-server
    LocalForward 9999 localhost:9999

Slash Commands

Plannotator's slash commands are installed as Claude Code skills in ~/.claude/skills by the install script (the canonical source is apps/skills/core/). Claude Code skills are user-invocable by directory name, so these three work like slash commands inside your session:

CommandDescription
`/plannotator-review [--git \--gitbutler] [DIRECTORY \PR_URL]`Open code review UI for current changes, another repository/worktree, or a PR; optionally force the Git or GitButler provider
`/plannotator-annotate <file.md \file.html \https://... \folder/>`Annotate a file, URL, or folder
/plannotator-lastAnnotate the agent's last message

Obsidian Integration

Approved plans can be automatically saved to your Obsidian vault.

Setup:

  1. Open Settings (gear icon) in Plannotator
  2. Enable "Obsidian Integration"
  3. Select your vault from the dropdown (auto-detected) or enter the path manually
  4. Set folder name (default: plannotator)

What gets saved:

  • Plans saved with human-readable filenames: Title - Jan 2, 2026 2-30pm.md
  • YAML frontmatter with created, source, and tags
  • Tags extracted automatically from the plan title and code languages
  • Backlink to [[Plannotator Plans]] for graph connectivity

Example saved file:

---
created: 2026-01-02T14:30:00.000Z
source: plannotator
tags: [plan, authentication, typescript, sql]
---

[[Plannotator Plans]]

# Implementation Plan: User Authentication
...

<img width="1190" height="730" alt="image" src="https://github.com/user-attachments/assets/1f0876a0-8ace-4bcf-b0d6-4bbb07613b25" />

Source 15 files
hooks/mod/register.ts 758 lines
1/**
2 * The Plannotator mod: non-blocking plan review, annotate, code review and
3 * annotate-last for Claude Code, plus "Ask this session".
4 *
5 * ON BY DEFAULT (enabled.ts). With `PLANNOTATOR_CLAUDE_MOD=0` (or
6 * `{ "claudeCodeMod": false }` in config.json) every hook below passes straight
7 * through and nothing is registered or set, so the classic hook and skills
8 * run exactly as they do without mods.
9 *
10 * Loaded from `hooks/hooks.json` ("modules") only where Claude Code runs
11 * hooks modules (function hooks, 2.1.287+, CLI). Elsewhere the same plugin's
12 * classic command hooks and the `/plannotator-*` skills behave exactly as
13 * before; the mod also stands down in `-p`/SDK sessions and where there is no
14 * `/bin/sh` (Windows), leaving those classic paths in place.
15 *
16 * What it does:
17 * - ExitPlanMode (`tool.call`): answers `deny` with "waiting for review" text
18 *   at once and starts `plannotator claude-mod-plan` detached. A revision
19 *   while the review is open goes into the same tab. The decision arrives
20 *   later as a plugin turn (`$.prompt.submit`, origin `plannotator`). On
21 *   approval Claude calls ExitPlanMode again; the call whose plan matches the
22 *   approved text passes, and `classic.PermissionRequest` allows it with the
23 *   reviewer's permission mode. Because modules sit above the settings hooks
24 *   in that chain, the plugin's classic PermissionRequest command hook is
25 *   never reached for it: no second review. Where an organization's guard
26 *   plugin (Claude Code's `cc-plugin-sec-default` on Team/Enterprise
27 *   accounts) sends `classic.PermissionRequest` past this mod, the command
28 *   hook is reached; it finds the approval the mod recorded for the call in
29 *   flight (plan.ts `PLAN_APPROVALS_DIR`) and allows it without a review (#2007).
30 * - `/plannotator-review`, `/plannotator-annotate`, `/plannotator-last`
31 *   (`command.run`): the user's skills keep their names; the mod answers the
32 *   command itself, starting the CLI detached with the same arguments, and
33 *   returns the "Opened …" line. It registers a name only where no skill holds it.
34 * - The `plannotator` tool (`$.tool.register`, tool.ts): when Claude itself is
35 *   asked to open something in Plannotator it calls this tool instead of the
36 *   CLI; the call goes through the same detached launch and returns at once.
37 *   Not registered when the user turned the agent tool off
38 *   (`PLANNOTATOR_AGENT_TOOL=0` / `{ "agentTool": false }`, read once with the
39 *   mod switch). A main-loop Bash call that runs the CLI in a form the tool
40 *   can represent (`plannotator annotate|review|last ...`, take-over.ts) is
41 *   answered the same way instead of running, with or without the tool: the
42 *   take-over adds nothing to Claude's context, it only changes what a
43 *   command Claude already chose to run does.
44 * - "Ask this session": each launched server gets a pull-bridge token; the
45 *   mod polls it and runs the reviewer's questions as turns (bridge.ts).
46 * - The Plannotator Inbox (inbox.ts): where the inbox tool switch allows it
47 *   (on by default, `PLANNOTATOR_INBOX_TOOL=0` / `{ "inboxTool": false }`),
48 *   the `plannotator_inbox` tool, whose actions are the Inbox's own MCP tools
49 *   (read once from its `/mcp`, else the list it last answered with, else the
50 *   list bundled with the mod, so the tool is there before the Inbox ever
51 *   ran; the first call starts it), and the reply wake: the person's Send in
52 *   the Inbox reaches the session that asked as a turn once it is idle. With
53 *   the tool, and once the Inbox has run here (`inbox/inbox.json` at session
54 *   start), a one-line reminder naming the tool's full name rides the
55 *   conversation's first message as a `prompt.context` block, unless
56 *   `{ "inboxReminder": false }` turns it off. Where a guard plugin skips
57 *   that hook (#2159), the line goes as the first prompt's `prompt.submit`
58 *   context, only while this machine has not seen `prompt.context` run
59 *   (`$.store` `inboxReminderContextWorks`). After a compaction the plugin's
60 *   `SessionStart` `compact` command hook (hooks.json) prints it again from
61 *   `PLANNOTATOR_INBOX_REMINDER`, which session.start sets.
62 * - `PLANNOTATOR_SESSION_TAG=claude-code:<session id>` in the environment
63 *   every process the session starts inherits, so a Plannotator server can be
64 *   matched to the session that started it.
65 *
66 * Every `$` call is in this file (`claude plugin validate` follows `$`); the
67 * logic lives behind `Host` in controller.ts.
68 */
69
70import { PlannotatorMod } from './controller'
71import { resolveAgentToolEnabled, resolveClaudeModEnabled, resolveInboxReminderCustom, resolveInboxReminderEnabled, resolveInboxToolEnabled } from './enabled'
72import type { Host, LoadedPluginInfo } from './host'
73import {
74  discoverInboxTools,
75  engineHasSessionAppend,
76  inboxRegistryPathOf,
77  inboxReminderEnvValue,
78  inboxReminderFirstTurnLesson,
79  inboxReminderSubmitCopy,
80  pluginVersionOf,
81  readReminderContextWorks,
82  reminderSessionResumed,
83  STORE_INBOX_REMINDER_CONTEXT_WORKS,
84  withInboxReminder,
85} from './inbox'
86import { inboxAgentTool, inboxReminderFor, type InboxToolInfo } from './inbox-contract'
87import { INBOX_DEFAULT_TOOLS } from './inbox-default-tools'
88import { COMMANDS, dataDirOf, debugAppendArgv, isModCommand, waitArgv } from './launch'
89import { PLAN_TOOL } from './plan'
90import { answerShellCall, SHELL_TOOL, shellTakeOver } from './take-over'
91import { PLANNOTATOR_TOOL_NAME, PLANNOTATOR_TOOL_TAILSCALE_DESCRIPTION, PLANNOTATOR_TOOL_TAILSCALE_INPUT_SCHEMA } from './tool'
92
93// Minimal local types: the engine's declarations are written by `/plugin-types`
94// and not vendored here.
95type Engine = any
96type Next = any
97type On = (event: string, ...args: unknown[]) => void
98
99function hexOf(bytes: Uint8Array): string {
100  let out = ''
101  for (const byte of bytes) out += byte.toString(16).padStart(2, '0')
102  return out
103}
104
105/** Debug lines waiting to be appended; at most this many are kept while an append runs. */
106const DEBUG_PENDING_MAX = 500
107let debugPending: string[] = []
108let debugAppending = false
109/** Tells this process's lines apart from another's in the shared log. */
110let debugTag: string | null = null
111
112/** This plugin's name: what `$.prompt.submit` stamps as the origin of our prompts. */
113const PLUGIN_NAME = 'plannotator'
114
115/**
116 * When this module loaded: the plugin a restart would replace was loaded then.
117 * The Inbox compares it with the plugin registry's `lastUpdated`, which is the
118 * only sign of an update that kept the version and the folder.
119 */
120const MODULE_LOADED_AT = Date.now()
121
122/** The plugin this process loaded (plugin.json's version, its folder, the load time), read once. */
123let loadedPlugin: Promise<LoadedPluginInfo> | null = null
124// Never null: a mod of this release always reports `plugin`, with `root` or `version` null when it could not
125// read them, so a poll without the field only ever means an older mod (the Inbox flags that as outdated).
126function readLoadedPlugin($: Engine): Promise<LoadedPluginInfo> {
127  loadedPlugin ??= (async () => {
128    let root: string | null = null
129    try {
130      const raw: unknown = $.plugin.root
131      root = typeof raw === 'string' && raw ? raw.replace(/\/+$/, '') || null : null
132    } catch {
133      root = null
134    }
135    if (!root) return { version: null, root: null, loaded_at: MODULE_LOADED_AT }
136    // `$.plugin.root` is the folder holding `.claude-plugin/plugin.json`.
137    const text = (await $.fs.read(`${root}/.claude-plugin/plugin.json`).catch(() => null)) ?? (await $.fs.read(`${root}/plugin.json`).catch(() => null))
138    return { version: pluginVersionOf(typeof text === 'string' ? text : null), root, loaded_at: MODULE_LOADED_AT }
139  })()
140  return loadedPlugin
141}
142
143/** Claude Code's own version, read once (`$.session.version()`'s `base`). */
144let engineVersion: Promise<string | null> | null = null
145function readEngineVersion($: Engine): Promise<string | null> {
146  engineVersion ??= (async () => {
147    try {
148      const version = await $.session.version()
149      const base = version?.base ?? version?.version
150      return typeof base === 'string' && base ? base : null
151    } catch {
152      return null
153    }
154  })()
155  return engineVersion
156}
157
158/** Every closure over `$` the logic uses. `debugPath` set: lines go to that file. */
159function hostOf($: Engine, debugPath: string | null): Host {
160  return {
161    now: () => $.clock.now(),
162    sleep: (ms, signal) => $.clock.sleep(ms, signal ? { signal } : undefined),
163    waitForAny: async (paths, timeoutMs) => {
164      await $.process.run(waitArgv(paths, timeoutMs), { timeoutMs: timeoutMs + 5_000 }).catch(() => undefined)
165    },
166    every: (ms, fn) => $.clock.every(ms, fn),
167    run: (argv, init) => $.process.run(argv, init),
168    readFile: (path) => $.fs.read(path),
169    writeFile: (path, text) => $.fs.write(path, text),
170    exists: (path) => $.fs.exists(path),
171    fileSize: async (path) => {
172      const stat = await $.fs.stat(path)
173      return stat && stat.kind === 'file' ? Number(stat.size) : null
174    },
175    storeGet: (key) => $.store.get(key),
176    storeSet: (key, value) => $.store.set(key, value),
177    submit: async (text) => {
178      await $.prompt.submit({ text })
179    },
180    // Called only where `sessionAppendAvailable` said the engine has it; a refusal stops Send now here (inbox.ts).
181    appendUserRow: async (text) => {
182      const stored = await $.session.append({ message: { type: 'user', content: [{ type: 'text', text }] } })
183      if (stored && typeof stored.deny === 'string') throw new Error(stored.deny)
184    },
185    appendNotice: async (text) => {
186      const stored = await $.session.append({ message: { type: 'system', content: [{ type: 'text', text }] } })
187      if (stored && typeof stored.deny === 'string') throw new Error(stored.deny)
188    },
189    // Decided from the engine's version (validate refuses `typeof $.session.append`): an older engine never offers Send now.
190    sessionAppendAvailable: async () => {
191      try {
192        const version = await $.session.version()
193        return engineHasSessionAppend(version?.base ?? version?.version)
194      } catch {
195        return false
196      }
197    },
198    loadedPlugin: () => readLoadedPlugin($),
199    engineVersion: () => readEngineVersion($),
200    suggest: async (text) => {
201      await $.prompt.suggest({ text })
202    },
203    status: (text) => $.ui.status(text),
204    log: (text) => $.ui.log(text),
205    toast: (text) => $.ui.toast(text),
206    messages: async () => {
207      const messages = await $.session.messages()
208      return (Array.isArray(messages) ? messages : []).map((message: { role: 'user' | 'assistant'; text: string }) => ({
209        role: message.role,
210        text: typeof message.text === 'string' ? message.text : '',
211      }))
212    },
213    fetch: (url, init) => $.http.fetch(url, init),
214    abortTurn: (turnId) => $.turn.abort({ turnId }),
215    randomHex: (bytes) => hexOf(crypto.getRandomValues(new Uint8Array(bytes))),
216    debug: (text) => {
217      if (!debugPath) return
218      debugTag ??= hexOf(crypto.getRandomValues(new Uint8Array(3)))
219      debugPending.push(`${new Date().toISOString()} [${debugTag}] ${text}`)
220      if (debugPending.length > DEBUG_PENDING_MAX) debugPending.splice(0, debugPending.length - DEBUG_PENDING_MAX)
221      if (debugAppending) return
222      // Appended (O_APPEND, launch.ts DEBUG_APPEND_SCRIPT), one batch at a
223      // time: several Claude Code processes share this log, and rewriting the
224      // whole file from each one's buffer clobbered the other's lines.
225      debugAppending = true
226      void (async () => {
227        try {
228          while (debugPending.length > 0) {
229            const batch = debugPending
230            debugPending = []
231            await $.process.run(debugAppendArgv(debugPath), { stdin: `${batch.join('\n')}\n`, timeoutMs: 5_000 }).catch(() => undefined)
232          }
233        } finally {
234          debugAppending = false
235        }
236      })()
237    },
238    sha256: async (text) => hexOf(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))),
239  }
240}
241
242/** What session.start found: the mod may run in this process. Null: inert. */
243interface Allowed {
244  dataDir: string
245  debugPath: string | null
246  /** Register Claude's `plannotator` tool (the agent tool switch, on by default). */
247  agentTool: boolean
248  /** Connect to the Plannotator Inbox (the inbox tool switch, on by default). */
249  inboxTool: boolean
250  /** With the Inbox tool: the one-line reminder at the start of each conversation (`inboxReminder`, on by default). */
251  inboxReminder: boolean
252  /** The person's own reminder text (config.json `prompts.inbox`), or null: the built-in line. */
253  inboxReminderCustom: string | null
254}
255
256// One plugin instance per Claude Code process.
257let allowed: Allowed | null = null
258/**
259 * The Inbox tools registered as `plannotator_inbox` at the first session.start
260 * (fixed for the process: the tool list is part of Claude's prompt); null: no
261 * Inbox connection.
262 */
263let inboxTools: readonly InboxToolInfo[] | null = null
264/** `mcp__<plugin server>__plannotator_inbox` as the engine registered it; null until then. */
265let inboxToolName: string | null = null
266/** `inbox/inbox.json` existed at the first session.start: the person has run the Inbox here (the reminder's gate). */
267let inboxRanHere = false
268let mod: PlannotatorMod | null = null
269let switching: Promise<PlannotatorMod | null> | null = null
270
271/**
272 * The reminder is on in this process: the switch, an Inbox that has run here,
273 * and plannotator_inbox registered (its full name is in the text). Fixed after
274 * the first session.start.
275 */
276function reminderOn(): boolean {
277  return !!allowed?.inboxReminder && inboxRanHere && !!inboxToolName
278}
279
280/**
281 * Settles with `reminderOn()` once the first session.start has decided it
282 * (the switch, inbox.json, plannotator_inbox registered), or with false on its
283 * early returns (`-p`, the mod off). The engine runs prompt.context BEFORE
284 * session.start finishes (seen live on 2.1.310: the Inbox tool was registered
285 * about 230 ms after prompt.context returned), so prompt.context and the
286 * prompt.submit fallback wait on this, bounded, instead of reading the
287 * not-yet-set module state.
288 */
289let reminderGateValue: boolean | null = null
290let resolveReminderGate: (on: boolean) => void = () => undefined
291const reminderGate = new Promise<boolean>((resolve) => {
292  resolveReminderGate = resolve
293})
294function settleReminderGate(on: boolean): void {
295  if (reminderGateValue !== null) return
296  reminderGateValue = on
297  resolveReminderGate(on)
298}
299/** The longest prompt.context / prompt.submit wait for session.start's decision. */
300const REMINDER_GATE_WAIT_MS = 2_500
301/**
302 * The decision, waiting at most REMINDER_GATE_WAIT_MS for session.start;
303 * `null` when it has not decided by then (the caller then knows nothing).
304 */
305async function reminderGateDecided($: Engine): Promise<boolean | null> {
306  if (reminderGateValue !== null) return reminderGateValue
307  const controller = new AbortController()
308  const waited = Promise.resolve()
309    .then(() => $.clock.sleep(REMINDER_GATE_WAIT_MS, { signal: controller.signal }))
310    .then(
311      () => null,
312      () => null,
313    )
314  try {
315    return await Promise.race([reminderGate, waited])
316  } finally {
317    controller.abort()
318  }
319}
320
321/** `$.clock.now()` at this process's first session.start: tells a resumed session from one started here. */
322let processStartedAt: number | null = null
323
324/**
325 * Per conversation (session id), in this process: `contextRan`, the mod's
326 * `prompt.context` hook ran for it; `delivered`, the reminder reached it by
327 * either path; `firstTurnDone`, its first main turn has been looked at.
328 */
329interface ReminderConversation {
330  contextRan: boolean
331  delivered: boolean
332  firstTurnDone: boolean
333}
334const reminderConversations = new Map<string, ReminderConversation>()
335function reminderConversation(sessionId: string): ReminderConversation {
336  let state = reminderConversations.get(sessionId)
337  if (!state) {
338    state = { contextRan: false, delivered: false, firstTurnDone: false }
339    reminderConversations.set(sessionId, state)
340  }
341  return state
342}
343
344/** `inboxReminderContextWorks` as this process knows it: read from `$.store` once, then kept in step with its writes. */
345let reminderContextWorks: Promise<boolean | undefined> | null = null
346function readContextWorks($: Engine): Promise<boolean | undefined> {
347  reminderContextWorks ??= Promise.resolve($.store.get(STORE_INBOX_REMINDER_CONTEXT_WORKS)).then(readReminderContextWorks, () => undefined)
348  return reminderContextWorks
349}
350async function writeContextWorks($: Engine, value: boolean): Promise<void> {
351  if ((await readContextWorks($)) === value) return
352  reminderContextWorks = Promise.resolve(value)
353  await $.store.set(STORE_INBOX_REMINDER_CONTEXT_WORKS, value)
354}
355
356/**
357 * The instance for the session the process is in NOW. `session.start` does
358 * not fire for `/clear` or an in-process resume (the process goes on under
359 * another session id), so the id is checked here and a new instance is made
360 * (restoring that session's open reviews) when it changed. The old one was
361 * disposed at `session.end`, so its decisions never land in another session.
362 */
363async function currentMod($: Engine): Promise<PlannotatorMod | null> {
364  const settings = allowed
365  if (!settings) return null
366  const sessionId = await $.session.id()
367  if (mod && !mod.isDisposed && mod.session.sessionId === sessionId) return mod
368  if (switching) return switching
369  switching = (async () => {
370    mod?.dispose()
371    await $.env.set('PLANNOTATOR_SESSION_TAG', `claude-code:${sessionId}`)
372    const instance = new PlannotatorMod(hostOf($, settings.debugPath), {
373      sessionId,
374      dataDir: settings.dataDir,
375      interactive: true,
376      ...(inboxTools
377        ? {
378            inboxTools,
379            ...(inboxToolName ? { inboxToolName } : {}),
380            cwd: async () => String(await $.session.cwd()),
381            // The session's root (where it started; a shell cd does not move it): its `claude --resume` folder.
382            root: async () => String(await $.session.root()),
383          }
384        : {}),
385    })
386    mod = instance
387    await instance.restore().catch(() => undefined)
388    return instance
389  })()
390  try {
391    return await switching
392  } finally {
393    switching = null
394  }
395}
396
397/** Whether the mod runs here (on unless the user turned it off) and where its data dir is; null: stay inert. */
398async function resolveAllowed($: Engine, e: { isInteractive?: unknown }): Promise<Allowed | null> {
399  // A person at the prompt is what makes a later plugin turn mean anything;
400  // `-p` and SDK runs keep the classic, blocking flows.
401  if (!e.isInteractive) return null
402  if (!(await $.fs.exists('/bin/sh'))) return null
403  const home = await $.env.get('HOME')
404  const dataDir = dataDirOf({
405    home,
406    dataDir: await $.env.get('PLANNOTATOR_DATA_DIR'),
407    xdgDataHome: await $.env.get('XDG_DATA_HOME'),
408    legacyExists: home ? await $.fs.exists(`${String(home).replace(/\/+$/, '')}/.plannotator`) : false,
409  })
410  if (!dataDir) return null
411  // On by default; nothing happens when the user turned the mod off.
412  const read = await $.fs.read(`${dataDir}/config.json`).catch(() => null)
413  const configText = typeof read === 'string' ? read : null
414  if (!resolveClaudeModEnabled(await $.env.get('PLANNOTATOR_CLAUDE_MOD'), configText)) {
415    return null
416  }
417  const debug = await $.env.get('PLANNOTATOR_MOD_DEBUG')
418  return {
419    dataDir,
420    debugPath: debug && debug !== '0' ? `${dataDir}/claude-code-mod/debug.log` : null,
421    agentTool: resolveAgentToolEnabled(await $.env.get('PLANNOTATOR_AGENT_TOOL'), configText),
422    inboxTool: resolveInboxToolEnabled(await $.env.get('PLANNOTATOR_INBOX_TOOL'), configText),
423    inboxReminder: resolveInboxReminderEnabled(await $.env.get('PLANNOTATOR_INBOX_TOOL'), configText),
424    inboxReminderCustom: resolveInboxReminderCustom(configText),
425  }
426}
427
428/** Register the slash commands no one holds (the user's own skills keep theirs; command.run answers them). */
429async function registerCommands($: Engine): Promise<void> {
430  const listed = await $.command.list().catch(() => [])
431  const taken = new Set((Array.isArray(listed) ? listed : []).map((command: { name: string }) => command.name))
432  for (const [name, spec] of Object.entries(COMMANDS)) {
433    if (taken.has(name)) continue
434    await $.command
435      .register({ name, description: spec.description, ...(spec.argumentHint ? { argumentHint: spec.argumentHint } : {}), immediate: true })
436      .catch(() => undefined)
437  }
438}
439
440/**
441 * The `plannotator` tool's full name as the engine registered it
442 * (`mcp__<plugin server>__plannotator`); null until registered, and never set
443 * while the mod is off.
444 */
445let toolName: string | null = null
446
447/** Register Claude's `plannotator` tool (tool.ts): agent-initiated opens get the slash commands' launch. */
448async function registerTool($: Engine): Promise<void> {
449  try {
450    const registered = await $.tool.register({
451      // The tailscale variant: the mod's CLI launch can publish over the tailnet (#2166).
452      name: PLANNOTATOR_TOOL_NAME,
453      description: PLANNOTATOR_TOOL_TAILSCALE_DESCRIPTION,
454      inputSchema: PLANNOTATOR_TOOL_TAILSCALE_INPUT_SCHEMA,
455    })
456    toolName = registered && typeof registered.tool === 'string' ? registered.tool : null
457  } catch (error) {
458    // A session with no built-in tools, --bare, or a host without a tool
459    // registrar: Claude keeps the CLI through the plannotator skill.
460    toolName = null
461    $.ui.log(`Plannotator: the plannotator tool is not available in this session (${error instanceof Error ? error.message : String(error)}).`)
462  }
463}
464
465/**
466 * Register `plannotator_inbox` (inbox.ts): its actions are the tools the Inbox
467 * offers, so an older Inbox gives fewer actions; before any Inbox ran here,
468 * the list bundled with the mod (the first call starts the Inbox).
469 */
470async function registerInboxTool($: Engine, settings: Allowed): Promise<void> {
471  const host = hostOf($, settings.debugPath)
472  // The reminder speaks only for an Inbox that has run here; the tool is there either way.
473  inboxRanHere = await host.exists(inboxRegistryPathOf(settings.dataDir)).catch(() => false)
474  const tools = await discoverInboxTools(host, settings.dataDir).catch(() => INBOX_DEFAULT_TOOLS.map((tool) => ({ ...tool })))
475  const spec = tools.length > 0 ? inboxAgentTool(tools) : null
476  if (!spec) return
477  try {
478    const registered = await $.tool.register(spec)
479    inboxToolName = registered && typeof registered.tool === 'string' ? registered.tool : null
480    if (inboxToolName) inboxTools = tools
481  } catch (error) {
482    inboxToolName = null
483    $.ui.log(`Plannotator: the plannotator_inbox tool is not available in this session (${error instanceof Error ? error.message : String(error)}).`)
484  }
485}
486
487/** A tool call's arguments: the event minus the keys the engine reserves. */
488function toolArgsOf(e: Record<string, unknown>): Record<string, unknown> {
489  const { tool: _tool, tool_use_id: _id, agentId: _agent, consent: _consent, ...args } = e
490  return args
491}
492
493export function register(on: On) {
494  on('session.start', async ($: Engine, e: any, next: Next) => {
495    const result = await next(e)
496    if (allowed) return result
497    try {
498      allowed = await resolveAllowed($, e)
499      if (!allowed) return result
500      processStartedAt = await Promise.resolve($.clock.now()).catch(() => null)
501      // Before the instance exists: it owns the Inbox link when the tool is registered.
502      if (allowed.inboxTool) await registerInboxTool($, allowed)
503      // The reminder for the plugin's SessionStart `compact` command hook
504      // (hooks.json), which prints it after a compaction: the conversation then
505      // holds it again whether or not prompt.context reaches this mod. Unset
506      // when the reminder is off (a value inherited from a parent Claude Code
507      // must not speak for this session).
508      await Promise.resolve($.env.set('PLANNOTATOR_INBOX_REMINDER', inboxReminderEnvValue(reminderOn(), inboxToolName, allowed.inboxReminderCustom))).catch(() => undefined)
509    } finally {
510      // Decided (or inert): prompt.context, which the engine may already be
511      // running, adds the block now, without waiting for the commands and tools below.
512      settleReminderGate(reminderOn())
513    }
514    const instance = await currentMod($)
515    if (!instance) return result
516    await registerCommands($)
517    // Decided once per process, here: the tool list is part of Claude's
518    // prompt, so it never changes under a running session.
519    if (allowed.agentTool) await registerTool($)
520    return result
521  })
522
523  // The Inbox reminder: one fixed line in the context of the conversation's
524  // first message, only in a process that registered plannotator_inbox, where
525  // the Inbox had run (inbox/inbox.json at the first session.start) and with
526  // the switch on, all decided once then. It names the tool by its registered
527  // full name, so tool search finds the deferred tool. The engine renders it
528  // once per conversation, after the system prompt and the tools, so it never
529  // moves a cached prefix; it is never invalidated.
530  //
531  // Where a guard plugin seated above the mod skips this hook (#2159), the
532  // same line goes as `prompt.submit` context instead (below). This hook
533  // running is the evidence that stops that copy: it records the conversation
534  // as reached and the machine as one where prompt.context works.
535  //
536  // The engine runs this hook while session.start may still be registering
537  // the tool, so it waits for session.start's decision (bounded). When that
538  // does not come in time the hook adds nothing, but it still records that it
539  // ran, so the machine is never taken for one where prompt.context is skipped.
540  on('prompt.context', async ($: Engine, e: any, next: Next) => {
541    const decided = await reminderGateDecided($)
542    if (decided === false) return next(e)
543    const toolName = decided ? inboxToolName : null
544    const result = toolName ? await next({ ...e, blocks: withInboxReminder(Array.isArray(e.blocks) ? e.blocks : [], toolName, allowed?.inboxReminderCustom ?? null) }) : await next(e)
545    try {
546      const state = reminderConversation(String(await $.session.id()))
547      state.contextRan = true
548      if (toolName) {
549        state.delivered = true
550        await writeContextWorks($, true)
551      }
552    } catch {
553      // Bookkeeping only: the block above is what matters.
554    }
555    return result
556  })
557
558  on('session.end', async ($: Engine, e: any, next: Next) => {
559    // Stop delivering for the session that ended; its open reviews stay in
560    // the store and reattach if it is resumed.
561    mod?.dispose()
562    return next(e)
563  })
564
565  // Matched by name: an unmatched hook makes the engine credit Plannotator on every plugin's command answer.
566  on('command.run', { command: Object.keys(COMMANDS) }, async ($: Engine, e: any, next: Next) => {
567    const name: string = typeof e.command === 'string' ? e.command : ''
568    if (!allowed || !isModCommand(name)) return next(e)
569    const instance = await currentMod($)
570    if (!instance) return next(e)
571    const spec = COMMANDS[name]
572    const text = await instance.runCommand(spec.kind, typeof e.args === 'string' ? e.args : '')
573    return { text }
574  })
575
576  on('tool.call', async ($: Engine, e: any, next: Next) => {
577    // Claude's `plannotator` tool: answered here, with the same detached
578    // launch the slash commands use. No other hook or core runs for it.
579    if (allowed && toolName && e.tool === toolName) {
580      const instance = await currentMod($)
581      if (!instance) return { deny: 'Plannotator is not available in this session; run the plannotator CLI instead.' }
582      // `last` reads the main session's transcript, so from a subagent it
583      // would annotate a message the subagent never wrote.
584      if (e.agentId && e.action === 'last') {
585        return { deny: 'Invalid plannotator call: action "last" annotates the main session\'s last message and is not available to a subagent.' }
586      }
587      const answer = await instance.runTool(toolArgsOf(e))
588      return 'deny' in answer ? { deny: answer.deny } : { result: answer.text }
589    }
590    // `plannotator_inbox`: the Inbox tool the call names, through the Inbox's
591    // /mcp, with this session's working folder and id filled in (inbox.ts).
592    if (allowed && inboxToolName && e.tool === inboxToolName) {
593      const instance = await currentMod($)
594      if (!instance?.inbox) return { deny: 'The Plannotator Inbox is not connected in this session; use the plannotator inbox mcp server instead.' }
595      const answer = await instance.inbox.callTool(toolArgsOf(e), String(await $.session.cwd()))
596      return 'deny' in answer ? { deny: answer.deny } : { result: answer.text }
597    }
598    // Claude running `plannotator annotate|review|last` in Bash on the main
599    // loop: the same launch and result as the tool (take-over.ts); anything
600    // the tool cannot represent, and every subagent's command, runs as written.
601    if (allowed && e.tool === SHELL_TOOL) {
602      const input = shellTakeOver(e.command, !!e.agentId)
603      if (!input) return next(e)
604      const instance = await currentMod($)
605      if (!instance) return next(e)
606      return answerShellCall(instance, input)
607    }
608    // Only the main loop's ExitPlanMode: a subagent's keeps the classic flow.
609    if (!allowed || e.tool !== PLAN_TOOL || e.agentId) return next(e)
610    const instance = await currentMod($)
611    if (!instance) return next(e)
612    const answer = await instance.onPlanCall({ tool_use_id: e.tool_use_id, plan: e.plan, planFilePath: e.planFilePath })
613    if ('deny' in answer) return { deny: answer.deny }
614    try {
615      return await next(e)
616    } finally {
617      await instance.onPlanCallSettled(e.tool_use_id)
618    }
619  })
620
621  // Matched on ExitPlanMode alone (#2159): a plugin seated above that sends
622  // classic.PermissionRequest past this mod (cc-plugin-sec-default) makes the
623  // engine print "its classic.PermissionRequest hook was skipped" for every
624  // tool the hook is selected for. Unmatched, that was every permission prompt
625  // of every tool. Matched, the engine never selects it for another tool, and
626  // a skip during a plan approval is answered by the record plan.ts writes.
627  on('classic.PermissionRequest', { tool_name: PLAN_TOOL }, async ($: Engine, e: any, next: Next) => {
628    const instance = mod
629    // A subagent's ExitPlanMode keeps the classic hook (its tool.call was not ours).
630    if (!instance || instance.isDisposed || e.tool_name !== PLAN_TOOL || e.agent_id) return next(e)
631    const decision = instance.onPlanPermission(typeof e.tool_use_id === 'string' ? e.tool_use_id : undefined, e.tool_input)
632    // Answered here, without next(e): the plugin's own classic command hook
633    // below never runs for this call, so it cannot open a second review.
634    return decision ? { decision } : next(e)
635  })
636
637  on('prompt.submit', async ($: Engine, e: any, next: Next) => {
638    const instance = allowed ? mod : null
639    const live = !!instance && !instance.isDisposed
640    // A prompt typed (or delivered) while a turn ran carries that turn's id:
641    // when the turn is a question's and a person sent it, the rest of the turn
642    // answers this prompt instead (turns.ts, take-over). Streaming stops HERE,
643    // before the hooks beneath run, so a slow one cannot let the next step
644    // through; it resumes if one of them drops the prompt.
645    const origin = e.origin
646    const ref = {
647      fromUs: !!origin && origin.kind === 'plugin' && origin.name === PLUGIN_NAME,
648      ...(typeof e.turnId === 'string' ? { turnId: e.turnId } : {}),
649      ...(origin && typeof origin.kind === 'string' ? { originKind: origin.kind } : {}),
650    }
651    if (live) instance.onPromptSubmitting(ref)
652    // The learned fallback for the Inbox reminder (#2159): on a conversation
653    // the reminder has not reached, while this machine has no evidence that
654    // prompt.context runs, the prompt carries the same line as context.
655    let entering = e
656    let reminderFor: ReminderConversation | null = null
657    // A prompt typed while session.start is still deciding waits for it (bounded), as prompt.context does.
658    if (!ref.fromUs && (await reminderGateDecided($)) === true && inboxToolName) {
659      try {
660        const state = reminderConversation(String(await $.session.id()))
661        const copy = inboxReminderSubmitCopy({
662          delivered: state.delivered,
663          contextWorks: await readContextWorks($),
664          isMeta: e.isMeta === true,
665          command: !!e.command,
666        })
667        if (copy) {
668          entering = { ...e, context: [...(Array.isArray(e.context) ? e.context : []), inboxReminderFor(allowed?.inboxReminderCustom ?? null, inboxToolName)] }
669          reminderFor = state
670        }
671      } catch {
672        entering = e
673      }
674    }
675    let result
676    try {
677      result = await next(entering)
678    } catch (error) {
679      if (live) instance.onPromptDropped(ref)
680      throw error
681    }
682    // Entered: the conversation has the reminder now (a dropped prompt does not).
683    if (reminderFor && result && typeof result.text === 'string') reminderFor.delivered = true
684    if (!live || instance.isDisposed) return result
685    if (result && typeof result.text === 'string') {
686      // Every prompt seen here is someone else's (the engine skips our hooks
687      // for prompts our own code submitted): its turn is never a question's.
688      instance.onPromptEntered({ ...ref, text: result.text })
689    } else {
690      instance.onPromptDropped(ref)
691    }
692    return result
693  })
694
695  on('turn.start', async ($: Engine, e: any, next: Next) => {
696    if (allowed && typeof e.turnId === 'string') {
697      const instance = await currentMod($).catch(() => null)
698      // A subagent's start carries its id: the controller counts only the main loop's turns.
699      if (instance) await instance.onTurnStart(e.turnId, typeof e.text === 'string' ? e.text : '', typeof e.agentId === 'string' ? e.agentId : undefined)
700    }
701    return next(e)
702  })
703
704  on('turn.step', async function* ($: Engine, e: any, next: Next) {
705    const instance = allowed ? mod : null
706    // A main-loop model request is going out: a reply Send now put into the turn is in it (inbox.ts).
707    if (instance && !instance.isDisposed && !e.agentId && typeof e.turnId === 'string') instance.onMainStep(e.turnId)
708    if (!instance || !instance.turns.ownsTurn(e.turnId)) return yield* next(e)
709    // A question's turn that someone else's prompt entered settles here: this
710    // request carries their prompt, so nothing it says is the question's answer.
711    instance.onTurnStep(e.turnId)
712    if (!instance.turns.ownsTurn(e.turnId)) return yield* next(e)
713    const stream = next(e)
714    let step = await stream.next()
715    while (!step.done) {
716      const chunk = step.value
717      if (chunk && chunk.kind === 'text' && typeof chunk.text === 'string') instance.turns.onText(e.turnId, chunk.text)
718      else if (chunk && chunk.kind === 'tool' && typeof chunk.name === 'string') instance.turns.onTool(e.turnId, chunk.name)
719      else if (chunk && chunk.kind === 'stop') instance.onTurnStepStop(e.turnId, typeof chunk.stopReason === 'string' ? chunk.stopReason : null)
720      yield chunk
721      step = await stream.next()
722    }
723    return step.value
724  })
725
726  on('turn.complete', async ($: Engine, e: any, next: Next) => {
727    if (allowed && mod && !mod.isDisposed && !e.agentId && typeof e.turnId === 'string') {
728      mod.onTurnComplete(e.turnId, typeof e.answer === 'string' ? e.answer : '', e.isAborted === true)
729    }
730    // A conversation's first main turn: prompt.context resolves while the
731    // first request is built, so by now it ran unless something above the mod
732    // skipped it. Then this machine learns `false`, and the conversation's
733    // next prompt carries the reminder (prompt.submit above).
734    if (reminderOn() && !e.agentId) {
735      try {
736        const state = reminderConversation(String(await $.session.id()))
737        if (!state.firstTurnDone) {
738          const usage = state.contextRan ? null : await Promise.resolve($.session.usage()).catch(() => null)
739          const lesson = inboxReminderFirstTurnLesson({
740            contextRan: state.contextRan,
741            aborted: e.isAborted === true,
742            resumed: reminderSessionResumed(usage?.startedAt, processStartedAt),
743            contextWorks: await readContextWorks($),
744          })
745          state.firstTurnDone = lesson.done
746          if (lesson.write === false) {
747            await writeContextWorks($, false)
748            if (allowed) hostOf($, allowed.debugPath).debug('inbox reminder: prompt.context did not run in the first turn; the reminder goes as prompt.submit context on this machine')
749          }
750        }
751      } catch {
752        // Bookkeeping only.
753      }
754    }
755    return next(e)
756  })
757}
758
hooks/mod/controller.ts 1743 lines
1/**
2 * The Plannotator mod's state for one Claude Code session: the reviews it has
3 * open, the plan approval waiting for Claude's next ExitPlanMode, delivery of
4 * decisions as plugin turns, and the "Ask this session" bridges.
5 *
6 * Every engine call goes through `Host` (built from `$` in register.ts), so
7 * bun tests drive this class with a host made of memory.
8 */
9
10import { BRIDGE_HOST, BRIDGE_MODES, bridgeBaseUrl, createBridge, type BridgeEnd, type BridgeHandle } from './bridge'
11import { deliveryFor, legacyResult, parseHostResult, type HostResultRecord, type SessionKind } from './delivery'
12import type { Host, HttpResult } from './host'
13import { InboxLink } from './inbox'
14import type { InboxToolInfo } from './inbox-contract'
15import {
16  aliveArgv,
17  CLAIM_EXIT,
18  claimArgv,
19  cleanupArgv,
20  stopArgv,
21  STOP_EXIT,
22  cliArgvFor,
23  failedText,
24  fileIn,
25  isSeveralFilePaths,
26  launchArgv,
27  launchDirOf,
28  modTargetFor,
29  openedText,
30  parseReadyFile,
31  pickerFile,
32  planApprovalPathOf,
33  privateDirArgv,
34  pruneArgv,
35  RECENT_MESSAGES_SUBJECT,
36  removeFileArgv,
37  recentAssistantTexts,
38  SETTLED_BY,
39  SETTLED_DIR,
40  subjectFor,
41  subjectFromServerTarget,
42  wordsOf,
43} from './launch'
44import {
45  approvedPermissionDecision,
46  CLASSIC_PLAN_RETRY_TEXT,
47  CLASSIC_PLAN_REVIEW_TEXT,
48  cliLacksModPlan,
49  decidingDenyText,
50  isTrustablePlanPath,
51  MAX_PLAN_FILE_BYTES,
52  normalizePlanForHash,
53  planApprovalRecord,
54  planCallAction,
55  planWaitingStatus,
56  revisedDenyText,
57  revisionPendingDenyText,
58  unchangedDenyText,
59  waitingDenyText,
60  type OpenPlanReview,
61  type PendingApproval,
62} from './plan'
63import {
64  isOlderCliBundleRefusal,
65  isOlderCliTailscaleRefusal,
66  parsePlannotatorToolInput,
67  plannotatorDecisionSubject,
68  plannotatorDistinctSubjects,
69  plannotatorSameTarget,
70  plannotatorBundleSubject,
71  plannotatorSessionId,
72  plannotatorToolArgs,
73  plannotatorToolCloseText,
74  plannotatorToolListText,
75  plannotatorToolOpenedText,
76  plannotatorToolTargets,
77  plannotatorUnknownSessionText,
78  PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT,
79  PLANNOTATOR_TOOL_TAILSCALE_UNAVAILABLE_TEXT,
80  scriptOnlyAnnotateFlag,
81  scriptOnlyAnnotateFlagText,
82  type PlannotatorCloseOutcome,
83  type PlannotatorSessionSummary,
84  type PlannotatorTarget,
85} from './tool'
86import { TurnTracker, type EnteredPrompt } from './turns'
87
88/** Persisted in `$.store` so open reviews reattach after a restart or `--resume`. */
89export interface LaunchRecord {
90  id: string
91  sessionId: string
92  kind: SessionKind
93  dir: string
94  /** How the launch is named now: `baseSubject`, told apart from same-named open launches. */
95  subject: string
96  /** The subject before same-named launches were told apart (`plannotatorDistinctSubjects`). */
97  baseSubject?: string
98  /**
99   * What the launch shows, in full. From the ready file when the CLI names it
100   * (`targetFromServer`), else the mod's own resolution of the words: the
101   * fallback a decision from an older CLI (no `target` in its record) is named by.
102   */
103  target?: string | string[]
104  /** `target` came from the server's ready file, not the mod's guess. */
105  targetFromServer?: boolean
106  startedAt: number
107  url?: string
108  port?: number
109  /** Plan: the version shown in the copy. */
110  version?: number
111  /** Plan: the last revision sequence written to revision.json. */
112  revisionSeq?: number
113  /** The pull-bridge token this launch's server was started with. */
114  bridgeToken?: string
115  /**
116   * Opened by Claude's `plannotator` tool with `gate: true`: Claude was told
117   * to wait for the sign-off, so a bare approval is delivered as a turn (the
118   * slash command's bare approval only logs).
119   */
120  deliverApproval?: boolean
121  /**
122   * Claude closed this review (the `plannotator` tool's `close`): nothing is
123   * delivered for it, and it is gone from `list` and the status line while
124   * the server shuts down.
125   */
126  closedByAgent?: boolean
127  /** The ready file's `tailnet` (a `--tailscale` session of a CLI that keeps Ask this session there, #2166). */
128  tailnet?: { ask: boolean }
129  /** Opened by the tool with `tailscale: true`: a ready line without `tailnet` means a CLI too old for it. */
130  tailscaleAsked?: boolean
131}
132
133/** What the mod says when a tool `tailscale` launch came up late from a CLI too old for it. */
134export const TAILSCALE_LATE_OLDER_CLI_TEXT = (subject: string): string =>
135  `${subject} opened, but the installed Plannotator is too old to keep "Ask this session" over the tailnet. Update Plannotator (\`plannotator update\`).`
136
137/** The `pn-` session id of a launch: the six hex digits that end its launch id. */
138export function sessionIdOf(launch: { id: string }): string {
139  const hex = /([0-9a-f]{6})$/i.exec(launch.id)?.[1] ?? '000000'
140  return plannotatorSessionId(hex)
141}
142
143/** The host-only endpoints of the CLI's server (packages/shared/host-control.ts). */
144export const HOST_STATUS_PATH = '/api/host/status'
145export const HOST_CLOSE_PATH = '/api/host/close'
146/** The code a current CLI's 404 carries while host control is off (packages/shared/host-control.ts). */
147export const HOST_CONTROL_DISABLED_CODE = 'host_control_disabled'
148
149function jsonObjectOf(text: string): Record<string, unknown> | null {
150  try {
151    const value = JSON.parse(text) as unknown
152    return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null
153  } catch {
154    return null
155  }
156}
157
158/** What `POST /api/host/close` told the mod. */
159export type HostCloseAnswer =
160  | { kind: 'closed'; unsent: number }
161  | { kind: 'decided' }
162  /** A Plannotator without the endpoint answered: a JSON 404 (0.24+) or its app page (0.19.24–0.23.x). */
163  | { kind: 'older' }
164  /** A Plannotator WITH the endpoint, turned off (remote mode): `404 { code: "host_control_disabled" }`. */
165  | { kind: 'disabled' }
166  | { kind: 'refused'; status: number }
167  /** Nothing answered on the port. */
168  | { kind: 'unreachable' }
169
170/**
171 * Reads the close answer. Only a JSON body with a numeric `unsentAnnotations`
172 * is a close: a CLI before the `/api/*` 404 guard (#748) serves its app page
173 * with 200 for any path, which must not read as closed (the reviewer's later
174 * decision would be swallowed as the agent's close).
175 */
176export function classifyHostCloseAnswer(response: HttpResult | null): HostCloseAnswer {
177  if (!response) return { kind: 'unreachable' }
178  const body = jsonObjectOf(response.text)
179  if (body) {
180    if (response.ok && typeof body.unsentAnnotations === 'number') return { kind: 'closed', unsent: body.unsentAnnotations }
181    if (response.status === 409 && body.code === 'already_decided') return { kind: 'decided' }
182    if (response.status === 404 && body.code === HOST_CONTROL_DISABLED_CODE) return { kind: 'disabled' }
183    if (response.status === 404 && typeof body.error === 'string') return { kind: 'older' }
184    return { kind: 'refused', status: response.status }
185  }
186  if (response.status === 200 && /<html|<!doctype html/i.test(response.text)) return { kind: 'older' }
187  return { kind: 'refused', status: response.status }
188}
189
190export const STORE_LAUNCHES = 'launches'
191export const STORE_APPROVALS = 'approvals'
192
193const TICK_MS = 1_000
194/** Liveness check of a launch whose server has not decided yet. */
195const PID_CHECK_EVERY_TICKS = 15
196const PID_MISSES_BEFORE_STOPPED = 3
197const READY_WAIT_MS = { review: 45_000, other: 15_000 }
198const REVISION_ACK_WAIT_MS = 4_000
199/**
200 * A bridge loop that ended because the server stopped answering is started
201 * again after `first`, doubling up to `max` while it keeps failing. A loop
202 * that got through at least once starts the next wait at `first` again.
203 */
204export const BRIDGE_RETRY_MS = { first: 5_000, max: 60_000 } as const
205/**
206 * The watcher lease (`watcher.json` in the launch directory): when two Claude
207 * Code processes hold the same session (`claude --continue` while the first
208 * still runs), one of them watches a launch, runs its bridge and delivers its
209 * decision. The process the person last acted in wins it (`touchedAt`:
210 * restore, a typed prompt, a command, the tool, ExitPlanMode); the holder
211 * renews it every `LEASE_EVERY_TICKS`, and anyone takes it over once it is
212 * `LEASE_STALE_MS` old (the holder exited, slept, or hung). Delivery is also
213 * claimed once per launch (`claimArgv`), so a lease race can never deliver
214 * twice.
215 */
216const LEASE_EVERY_TICKS = 5
217export const LEASE_STALE_MS = 20_000
218/**
219 * The minimum age of a stored record `pruneStoredLaunches` looks at: a
220 * younger one's wrapper may not have written its pid yet.
221 */
222export const LAUNCH_SETTLED_AGE_MS = 60_000
223/** Another session's launch this old whose server is gone is pruned even with a decision waiting. */
224export const LAUNCH_EXPIRED_MS = 14 * 24 * 60 * 60_000
225/**
226 * A claimed decision whose claimant has not renewed its watcher lease for
227 * this long (or released it at `session.end`) and never marked it delivered
228 * is reported as undelivered: the claimant quit (or crashed) while
229 * `$.prompt.submit` waited for Claude to go idle.
230 */
231export const UNDELIVERED_AFTER_MS = 60_000
232export const SETTLED_DELIVERED = `${SETTLED_DIR}/delivered`
233export const SETTLED_REPORTED = `${SETTLED_DIR}/reported`
234
235/** A stored record minus the in-memory watch state. */
236function recordOf(launch: LiveLaunch): LaunchRecord {
237  const {
238    pidMisses: _misses,
239    ticks: _ticks,
240    settling: _settling,
241    starting: _starting,
242    bridge: _bridge,
243    bridgeRetryAt: _retryAt,
244    bridgeBackoffMs: _backoff,
245    bridgeOff: _off,
246    leader: _leader,
247    leaseTick: _leaseTick,
248    touchedAt: _touchedAt,
249    checking: _checking,
250    ...record
251  } = launch
252  return record
253}
254
255interface LiveLaunch extends LaunchRecord {
256  pidMisses: number
257  ticks: number
258  settling: boolean
259  /**
260   * A hook is still waiting in `awaitReady` for this launch to come up or
261   * fail: that hook reports the outcome, so the timer leaves the launch alone.
262   */
263  starting: boolean
264  /** A tick is checking this launch now: the next tick skips it (ticks are not awaited). */
265  checking: boolean
266  bridge: BridgeHandle | null
267  /** No new bridge before this time (after a loop gave up on a silent server). */
268  bridgeRetryAt: number
269  /** The last retry wait, doubled while loops keep failing. */
270  bridgeBackoffMs: number
271  /** The server refused the bridge (an older CLI, a wrong token, AI off) or is closing: never again. */
272  bridgeOff: boolean
273  /** This instance holds the watcher lease: it runs the bridge and delivers. */
274  leader: boolean
275  /** The tick the lease was last looked at; null: never. */
276  leaseTick: number | null
277  /**
278   * When the person last acted on this launch from this process (restored it,
279   * typed here, ran a command or tool, ExitPlanMode); 0: never. The more
280   * recent touch wins the watcher lease.
281   */
282  touchedAt: number
283}
284
285interface WatcherLease {
286  owner: string | null
287  /** Heartbeat. */
288  at: number
289  /** The holder's `touchedAt` for this launch. */
290  touchedAt: number
291}
292
293function parseWatcherLease(text: string): WatcherLease | null {
294  const body = jsonObjectOf(text)
295  if (!body || typeof body.at !== 'number') return null
296  return {
297    owner: typeof body.owner === 'string' && body.owner ? body.owner : null,
298    at: body.at,
299    touchedAt: typeof body.touchedAt === 'number' ? body.touchedAt : 0,
300  }
301}
302
303export interface SessionInfo {
304  sessionId: string
305  dataDir: string
306  interactive: boolean
307  /**
308   * The Plannotator Inbox tools this process registered as `plannotator_inbox`
309   * at its first session start (inbox.ts); absent: no Inbox connection.
310   */
311  inboxTools?: readonly InboxToolInfo[]
312  /** The name the engine registered `plannotator_inbox` under (`mcp__<server>__plannotator_inbox`): the wake's closing line names it. */
313  inboxToolName?: string
314  /** The session's working folder, read when asked (the Inbox link's polls say where the session works). */
315  cwd?: () => Promise<string>
316  /** The session's root folder (`$.session.root()`), read once at the link's start: where `claude --resume` runs. */
317  root?: () => Promise<string>
318}
319
320export class PlannotatorMod {
321  readonly turns = new TurnTracker()
322  private launches = new Map<string, LiveLaunch>()
323  private approval: PendingApproval | null = null
324  /** ExitPlanMode calls passed through as the approved plan, by tool_use_id. */
325  private passing = new Map<string, PendingApproval>()
326  private planVersion = 0
327  /**
328   * The CLI has no `claude-mod-plan` (it is older than the plugin): every
329   * ExitPlanMode of this session takes Claude Code's own flow, and the
330   * plugin's classic hook reviews it, blocking, as before the mod.
331   */
332  private classicPlanReview = false
333  private timer: { cancel: () => void } | null = null
334  private delivering: Promise<void> = Promise.resolve()
335  private sequence = 0
336  private disposed = false
337  /** Launch ids this instance settled or dropped: kept out of the store even if another process re-adds them. */
338  private forgotten = new Set<string>()
339  /** Names this instance in a launch's watcher lease and settlement claim. */
340  private readonly instanceId: string
341  /** The store housekeeping started at restore (awaited by tests only). */
342  pruning: Promise<void> = Promise.resolve()
343  /**
344   * Launches this instance claimed whose decision waits for Claude to go idle
345   * (`$.prompt.submit`): their records stay in the store and their lease is
346   * renewed until `settled/delivered` is written, so another process can tell
347   * a claimant still waiting from one that quit.
348   */
349  private awaitingIdle = new Map<string, LaunchRecord>()
350  /** Launches another process claimed: watched until delivered, or reported once its claimant is gone. */
351  private claimedElsewhere = new Map<string, LaunchRecord>()
352  private tickCount = 0
353  /** This session's connection to the Plannotator Inbox (the tool and the reply wake); null without one. */
354  readonly inbox: InboxLink | null
355
356  constructor(
357    private readonly host: Host,
358    readonly session: SessionInfo,
359  ) {
360    this.instanceId = host.randomHex(8)
361    this.inbox = session.inboxTools
362      ? new InboxLink({
363          host,
364          dataDir: session.dataDir,
365          sessionId: session.sessionId,
366          tools: session.inboxTools,
367          ...(session.inboxToolName ? { toolName: session.inboxToolName } : {}),
368          isBusy: () => this.turns.busy,
369          // Send now goes into a running main turn, never into this session's own Ask question, and
370          // never into a turn another plugin's prompt started (that plugin may read its answer as its own).
371          steerableTurn: () => {
372            const turn = this.turns.runningTurn
373            return turn !== null && !this.turns.ownsTurn(turn) && !this.turns.isOtherPluginTurn(turn) ? turn : null
374          },
375          ...(session.cwd ? { cwd: session.cwd } : {}),
376          ...(session.root ? { root: session.root } : {}),
377          instanceId: this.instanceId,
378        })
379      : null
380    this.inbox?.start()
381  }
382
383  // --- Lifecycle -----------------------------------------------------------
384
385  /**
386   * Reattach the reviews this session left open (restart, `--resume`,
387   * `--continue`). Restoring is the strongest sign the person now works in
388   * THIS process, so its launches are touched: when another process still
389   * runs on the same session, this one takes over watching them
390   * (`holdLease`), and their decisions land in the conversation in use.
391   */
392  async restore(): Promise<void> {
393    const stored = await this.host.storeGet(STORE_LAUNCHES)
394    const records = (Array.isArray(stored) ? (stored as LaunchRecord[]) : []).filter(
395      (record) => record && record.sessionId === this.session.sessionId && typeof record.dir === 'string',
396    )
397    const now = await this.host.now()
398    const mine: LaunchRecord[] = []
399    for (const record of records) {
400      // Already settled: delivered, still on its way, or stranded (reported).
401      if (await this.host.exists(`${record.dir}/${SETTLED_DIR}`)) {
402        await this.watchClaimedElsewhere(record)
403        continue
404      }
405      // Cleaned up: nothing to reattach.
406      if (!(await this.host.exists(fileIn(record.dir, 'stdin')))) continue
407      mine.push(record)
408    }
409    // Watched from here from now on (the lease is written at once, so a
410    // decision arriving before the first tick lands here too).
411    for (const record of mine) await this.holdLease(this.adopt(record, now), true).catch(() => false)
412    this.refreshSubjects()
413    await this.loadApproval()
414    for (const launch of this.launches.values()) {
415      if (launch.kind === 'plan') this.planVersion = Math.max(this.planVersion, launch.version ?? 0)
416    }
417    if (mine.length > 0) {
418      const names = mine.map((record) => record.subject).join(', ')
419      this.host.log(`Reattached ${mine.length} open ${mine.length === 1 ? 'session' : 'sessions'} (${names}).`)
420      this.refreshStatus()
421    }
422    this.ensureTimer()
423    // Housekeeping off the session-start path.
424    this.pruning = this.pruneStoredLaunches().catch(() => undefined)
425  }
426
427  /**
428   * The approval waiting for this session's next ExitPlanMode, from the store:
429   * another Claude Code process on the session may have received it, or
430   * already used it.
431   */
432  private async loadApproval(): Promise<void> {
433    const approvals = await this.host.storeGet(STORE_APPROVALS)
434    const approval = approvals && typeof approvals === 'object' ? (approvals as Record<string, PendingApproval>)[this.session.sessionId] : undefined
435    this.approval = approval && typeof approval.hash === 'string' ? approval : null
436  }
437
438  /**
439   * Adopt this session's launches another Claude Code process on the same
440   * session started after this one restored, so a plan review, `list` and
441   * `close` see them here too.
442   */
443  private async adoptNewStoredLaunches(): Promise<void> {
444    const stored = await this.host.storeGet(STORE_LAUNCHES)
445    const records = Array.isArray(stored) ? (stored as LaunchRecord[]) : []
446    const now = await this.host.now()
447    let adopted = 0
448    for (const record of records) {
449      if (!record || record.sessionId !== this.session.sessionId || typeof record.dir !== 'string') continue
450      if (this.launches.has(record.id) || this.forgotten.has(record.id) || this.claimedElsewhere.has(record.id)) continue
451      if (await this.host.exists(`${record.dir}/${SETTLED_DIR}`)) {
452        await this.watchClaimedElsewhere(record)
453        continue
454      }
455      if (!(await this.host.exists(fileIn(record.dir, 'stdin')))) continue
456      const live = this.adopt(record, now)
457      if (live.kind === 'plan') this.planVersion = Math.max(this.planVersion, live.version ?? 0)
458      adopted += 1
459    }
460    if (adopted > 0) this.refreshStatus()
461    this.ensureTimer()
462  }
463
464  /**
465   * Where a claimed launch's decision stands: delivered (or nothing to
466   * deliver), on its way (its claimant renews its lease, or it is this
467   * instance's own), or stranded (its claimant quit while waiting for Claude to
468   * go idle), with the file holding the decision.
469   */
470  private async claimedState(record: LaunchRecord): Promise<'done' | 'waiting' | { stranded: string }> {
471    const dir = record.dir
472    if (!(await this.host.exists(`${dir}/${SETTLED_DIR}`))) return 'done'
473    if (await this.host.exists(`${dir}/${SETTLED_DELIVERED}`)) return 'done'
474    if (await this.host.exists(`${dir}/${SETTLED_REPORTED}`)) return 'done'
475    if (!(await this.host.exists(fileIn(dir, 'stdin')))) return 'done'
476    let decision: string | null = null
477    if (await this.host.exists(fileIn(dir, 'result'))) decision = fileIn(dir, 'result')
478    else if ((await this.host.readFile(fileIn(dir, 'exit')).catch(() => '')).trim() === '0') decision = fileIn(dir, 'stdout')
479    // A claim on a server that stopped without a decision: nothing was lost.
480    if (!decision) return 'done'
481    const by = (await this.host.readFile(`${dir}/${SETTLED_BY}`).catch(() => '')).trim()
482    if (by === this.instanceId) return this.awaitingIdle.has(record.id) ? 'waiting' : 'done'
483    const lease = parseWatcherLease(await this.host.readFile(fileIn(dir, 'watcher')).catch(() => ''))
484    const now = await this.host.now()
485    if (lease?.owner && lease.owner === by && now - lease.at < UNDELIVERED_AFTER_MS) return 'waiting'
486    return { stranded: decision }
487  }
488
489  /**
490   * A launch another process claimed: report it now if its decision was
491   * stranded, else watch it until it is delivered or stranded. Never
492   * delivered from here: the claimant may still be waiting to deliver it, so
493   * only a report is strictly at most once.
494   */
495  private async watchClaimedElsewhere(record: LaunchRecord): Promise<void> {
496    const state = await this.claimedState(record)
497    if (state === 'done') {
498      this.claimedElsewhere.delete(record.id)
499      return
500    }
501    if (state === 'waiting') {
502      this.claimedElsewhere.set(record.id, record)
503      this.ensureTimer()
504      return
505    }
506    this.claimedElsewhere.delete(record.id)
507    await this.host.writeFile(`${record.dir}/${SETTLED_REPORTED}`, String(await this.host.now())).catch(() => undefined)
508    this.host.log(`A decision for ${record.subject} arrived but wasn't delivered — it's saved in ${state.stranded}.`)
509    this.host.toast(`${record.subject}: a decision wasn't delivered; it is saved on disk`)
510  }
511
512  /**
513   * The person acts in this process (a prompt typed here, a slash command,
514   * Claude's tool, ExitPlanMode): its launches should be watched from here,
515   * so the lease is taken at once.
516   */
517  private async touchLaunches(): Promise<void> {
518    if (this.launches.size === 0) return
519    const now = await this.host.now()
520    for (const launch of [...this.launches.values()]) {
521      launch.touchedAt = now
522      if (!launch.settling) await this.holdLease(launch, true).catch(() => false)
523    }
524  }
525
526  /**
527   * The session this instance serves ended (`/clear`, an in-process resume,
528   * exit). Stop watching and polling so nothing is delivered into whatever
529   * session the process goes on with; open reviews stay in the store under
530   * this session id and reattach when it is resumed.
531   */
532  dispose(): void {
533    this.disposed = true
534    this.timer?.cancel()
535    this.timer = null
536    this.inbox?.dispose()
537    this.host.status(undefined)
538    // Hand the launches this instance watched to any other process on the session at once.
539    for (const launch of this.launches.values()) {
540      if (!launch.leader) continue
541      launch.leader = false
542      void this.host.writeFile(fileIn(launch.dir, 'watcher'), JSON.stringify({ owner: null, at: 0, touchedAt: 0 })).catch(() => undefined)
543    }
544    // A decision still waiting for Claude to go idle: say at once that nobody waits for it any more.
545    for (const record of this.awaitingIdle.values()) {
546      void this.host.writeFile(fileIn(record.dir, 'watcher'), JSON.stringify({ owner: null, at: 0, touchedAt: 0 })).catch(() => undefined)
547    }
548  }
549
550  get isDisposed(): boolean {
551    return this.disposed
552  }
553
554  private adopt(record: LaunchRecord, touchedAt = 0): LiveLaunch {
555    const live: LiveLaunch = {
556      ...record,
557      pidMisses: 0,
558      ticks: 0,
559      settling: false,
560      starting: false,
561      checking: false,
562      bridge: null,
563      bridgeRetryAt: 0,
564      bridgeBackoffMs: 0,
565      bridgeOff: false,
566      leader: false,
567      leaseTick: null,
568      touchedAt,
569    }
570    this.launches.set(record.id, live)
571    return live
572  }
573
574  /**
575   * Drops stored records nothing is left of (all sessions older than a
576   * minute, whose wrapper has surely written its pid):
577   * - settled or cleaned-up launches (a `settled/` claim, no `stdin`);
578   * - other sessions' servers that died without a decision;
579   * - other sessions' launches older than `LAUNCH_EXPIRED_MS` whose server is
580   *   gone, decision or not (a session nobody resumed).
581   * A live server always keeps its record; this session's dead servers are
582   * left to the timer, which reports them. The store is read again before the
583   * write, so a record another process added meanwhile is kept.
584   */
585  private async pruneStoredLaunches(): Promise<void> {
586    const stored = await this.host.storeGet(STORE_LAUNCHES)
587    const records = (Array.isArray(stored) ? (stored as LaunchRecord[]) : []).filter(
588      (record) => record && typeof record.dir === 'string' && typeof record.sessionId === 'string',
589    )
590    const now = await this.host.now()
591    const age = (record: LaunchRecord) => now - (Number(record.startedAt) || 0)
592    const old = records.filter((record) => age(record) > LAUNCH_SETTLED_AGE_MS)
593    if (old.length === 0) return
594    const mine = (record: LaunchRecord) => record.sessionId === this.session.sessionId
595    const groups = {
596      cleaned: old.filter(mine).map((record) => record.dir),
597      dead: old.filter((record) => !mine(record) && age(record) <= LAUNCH_EXPIRED_MS).map((record) => record.dir),
598      expired: old.filter((record) => !mine(record) && age(record) > LAUNCH_EXPIRED_MS).map((record) => record.dir),
599    }
600    const probe = await this.host.run(pruneArgv(groups), { timeoutMs: 5_000 }).catch(() => null)
601    if (!probe || probe.exitCode !== 0) return
602    const gone = new Set(probe.stdout.split('\n').map((line) => line.trim()).filter(Boolean))
603    if (gone.size === 0) return
604    const current = await this.host.storeGet(STORE_LAUNCHES)
605    const all = Array.isArray(current) ? (current as LaunchRecord[]) : []
606    const kept = all.filter((record) => !record || typeof record.dir !== 'string' || !gone.has(record.dir) || this.launches.has(record.id))
607    this.host.debug(`pruned ${all.length - kept.length} stored launch record(s)`)
608    await this.host.storeSet(STORE_LAUNCHES, kept)
609  }
610
611  /**
612   * Writes this instance's launches for this session. Records of this session
613   * this instance does not know (another Claude Code process on the same
614   * session launched them) are kept, unless this instance settled them.
615   */
616  private async persist(): Promise<void> {
617    const stored = await this.host.storeGet(STORE_LAUNCHES)
618    const all = (Array.isArray(stored) ? (stored as LaunchRecord[]) : []).filter((record) => !!record)
619    const others = all.filter(
620      (record) =>
621        record.sessionId !== this.session.sessionId ||
622        (!this.launches.has(record.id) && !this.awaitingIdle.has(record.id) && !this.forgotten.has(record.id)),
623    )
624    // A decision waiting for Claude to go idle keeps its record: if this
625    // process quits first, the next restore finds and reports it.
626    const mine: LaunchRecord[] = [...[...this.launches.values()].map(recordOf), ...this.awaitingIdle.values()]
627    await this.host.storeSet(STORE_LAUNCHES, [...others, ...mine])
628  }
629
630  private async persistApproval(): Promise<void> {
631    const stored = await this.host.storeGet(STORE_APPROVALS)
632    const all = stored && typeof stored === 'object' ? { ...(stored as Record<string, PendingApproval>) } : {}
633    if (this.approval) all[this.session.sessionId] = this.approval
634    else delete all[this.session.sessionId]
635    await this.host.storeSet(STORE_APPROVALS, all)
636  }
637
638  private hasWork(): boolean {
639    return this.launches.size > 0 || this.awaitingIdle.size > 0 || this.claimedElsewhere.size > 0
640  }
641
642  private ensureTimer(): void {
643    if (this.disposed || this.timer || !this.hasWork()) return
644    this.timer = this.host.every(TICK_MS, () => {
645      void this.tick()
646    })
647  }
648
649  private stopTimerIfIdle(): void {
650    if (!this.hasWork() && this.timer) {
651      this.timer.cancel()
652      this.timer = null
653    }
654  }
655
656  /** A launch id whose last six hex digits (its `pn-` session id) no open launch of this session uses. */
657  private async newLaunchId(): Promise<string> {
658    this.sequence += 1
659    const used = new Set([...this.launches.values()].map((launch) => sessionIdOf(launch)))
660    let value = Number.parseInt(this.host.randomHex(3), 16) || 0
661    let hex = value.toString(16).padStart(6, '0')
662    while (used.has(plannotatorSessionId(hex))) {
663      value = (value + 1) % 0x1000000
664      hex = value.toString(16).padStart(6, '0')
665    }
666    return `${await this.host.now()}-${this.sequence}-${hex}`
667  }
668
669  // --- Launch --------------------------------------------------------------
670
671  private async launch(
672    kind: SessionKind,
673    cliArgv: string[],
674    subject: string,
675    stdin: string | ((dir: string) => string),
676    extra: Partial<LaunchRecord> = {},
677    side: { messages?: string } = {},
678  ): Promise<LiveLaunch | { error: string }> {
679    const id = await this.newLaunchId()
680    const dir = launchDirOf(this.session.dataDir, this.session.sessionId, id)
681    const bridgeToken = this.host.randomHex(32)
682    let cwd: string | undefined
683    try {
684      // Owner-only before anything lands in it (stdin holds the plan or message).
685      const made = await this.host.run(privateDirArgv(dir), { timeoutMs: 5_000 })
686      if (made.exitCode !== 0) return { error: made.stderr.trim() || `could not create ${dir}` }
687      // The session's working directory (the CLI runs there too): what the
688      // mod's fallback target resolves relative words against.
689      cwd = made.stdout.trim().split('\n').pop()?.trim() || undefined
690      await this.host.writeFile(fileIn(dir, 'stdin'), typeof stdin === 'function' ? stdin(dir) : stdin)
691      // `last`'s picker list. A CLI that predates the variable ignores it and
692      // opens the newest message from stdin, as before.
693      if (side.messages !== undefined) await this.host.writeFile(fileIn(dir, 'messages'), side.messages)
694      const result = await this.host.run(launchArgv(dir, cliArgv), {
695        env: {
696          PLANNOTATOR_READY_FILE: fileIn(dir, 'ready'),
697          PLANNOTATOR_HOST_RESULT_FILE: fileIn(dir, 'result'),
698          ...(side.messages !== undefined ? { PLANNOTATOR_HOST_MESSAGES_FILE: fileIn(dir, 'messages') } : {}),
699          PLANNOTATOR_SESSION_BRIDGE_TOKEN: bridgeToken,
700          PLANNOTATOR_SESSION_BRIDGE_HOST: BRIDGE_HOST,
701          PLANNOTATOR_SESSION_BRIDGE_MODES: BRIDGE_MODES,
702          // The review's pn- id, for the `sessions/` registry (`plannotator sessions`).
703          PLANNOTATOR_HOST_REVIEW_ID: sessionIdOf({ id }),
704        },
705        timeoutMs: 15_000,
706      })
707      if (result.exitCode !== 0) return { error: result.stderr.trim() || `launcher exited ${result.exitCode}` }
708    } catch (error) {
709      return { error: error instanceof Error ? error.message : String(error) }
710    }
711    const target = extra.target ?? modTargetFor(kind, cliArgv.slice(2), cwd)
712    const record: LaunchRecord = {
713      id,
714      sessionId: this.session.sessionId,
715      kind,
716      dir,
717      subject,
718      baseSubject: subject,
719      startedAt: await this.host.now(),
720      bridgeToken,
721      ...extra,
722      ...(target !== undefined ? { target } : {}),
723    }
724    // Launched from here: the person is in this process.
725    const live = this.adopt(record, record.startedAt)
726    this.refreshSubjects()
727    this.host.debug(`launched ${kind} ${id}: ${cliArgv.join(' ')}`)
728    await this.persist()
729    this.ensureTimer()
730    return live
731  }
732
733  /**
734   * Wait until the server is listening or the CLI exited, up to `ms`. Called
735   * from hooks, so the waiting happens in `waitForAny` (a process call), never
736   * in a `$.clock` wait that would spend the hook's budget.
737   */
738  private async awaitReady(launch: LiveLaunch, ms: number): Promise<'ready' | 'exited' | 'timeout'> {
739    launch.starting = true
740    try {
741      return await this.waitReadyOrExit(launch, ms)
742    } finally {
743      launch.starting = false
744    }
745  }
746
747  private async waitReadyOrExit(launch: LiveLaunch, ms: number): Promise<'ready' | 'exited' | 'timeout'> {
748    const ready = fileIn(launch.dir, 'ready')
749    const exit = fileIn(launch.dir, 'exit')
750    const deadline = (await this.host.now()) + ms
751    for (;;) {
752      if (await this.readReady(launch)) return 'ready'
753      if (await this.host.exists(exit)) {
754        // A last look: the CLI may have become ready and exited at once.
755        return (await this.readReady(launch)) ? 'ready' : 'exited'
756      }
757      const left = deadline - (await this.host.now())
758      if (left <= 0) return 'timeout'
759      // The ready file appears before its JSON line is complete; re-check shortly.
760      await this.host.waitForAny([ready, exit], (await this.host.exists(ready)) ? 200 : left)
761    }
762  }
763
764  private async readReady(launch: LiveLaunch): Promise<boolean> {
765    if (launch.url) return true
766    const path = fileIn(launch.dir, 'ready')
767    if (!(await this.host.exists(path))) return false
768    const ready = parseReadyFile(await this.host.readFile(path).catch(() => ''))
769    if (!ready) return false
770    launch.url = ready.url
771    launch.port = ready.port
772    if (ready.tailnet) launch.tailnet = ready.tailnet
773    else if (launch.tailscaleAsked && !launch.starting) {
774      // The tool answered "starting" and the CLI came up later: the tool can
775      // no longer refuse, so say it here (the review stays open).
776      this.host.log(TAILSCALE_LATE_OLDER_CLI_TEXT(launch.subject))
777      this.host.toast(TAILSCALE_LATE_OLDER_CLI_TEXT(launch.subject))
778    }
779    if (ready.target !== undefined) {
780      // The server's own answer: it may have found a bare name elsewhere in the project.
781      if (launch.target !== undefined && !plannotatorSameTarget(launch.target, ready.target)) {
782        this.host.debug(`ready ${launch.id}: the server opened ${JSON.stringify(ready.target)}, not ${JSON.stringify(launch.target)}`)
783      }
784      launch.target = ready.target
785      launch.targetFromServer = true
786      // Named by what the CLI opened, not the typed words: it drops a stray
787      // `.` or prose beside a file (`annotate . a.md` opens a.md alone).
788      const named = subjectFromServerTarget(launch.kind, launch.baseSubject ?? launch.subject, ready.target)
789      if (named !== null) launch.baseSubject = named
790      this.refreshSubjects()
791    }
792    await this.persist()
793    this.refreshStatus()
794    return true
795  }
796
797  private async startupFailure(launch: LiveLaunch): Promise<string> {
798    const read = (name: 'stderr' | 'stdout' | 'exit') => this.host.readFile(fileIn(launch.dir, name)).catch(() => '')
799    const code = Number.parseInt((await read('exit')).trim(), 10)
800    const text = failedText(launch.subject, await read('stderr'), await read('stdout'), Number.isFinite(code) ? code : null)
801    await this.forget(launch)
802    return text
803  }
804
805  /**
806   * Not a failure to report each time: an older CLI. Say so once, and leave
807   * this instance's plans to the classic review (a resumed session probes
808   * once more, so a CLI updated in between is picked up).
809   */
810  private async fallBackToClassicPlans(launch: LiveLaunch): Promise<void> {
811    this.classicPlanReview = true
812    await this.forget(launch)
813    await this.host.run(cleanupArgv(launch.dir), { timeoutMs: 5_000 }).catch(() => undefined)
814    this.host.log(CLASSIC_PLAN_REVIEW_TEXT)
815  }
816
817  /** The plan launch exited because the CLI has no `claude-mod-plan`. */
818  private async lacksModPlan(launch: LiveLaunch): Promise<boolean> {
819    const stderr = await this.host.readFile(fileIn(launch.dir, 'stderr')).catch(() => '')
820    return cliLacksModPlan(stderr)
821  }
822
823  // --- Commands ------------------------------------------------------------
824
825  /** `/plannotator-review`, `/plannotator-annotate`, `/plannotator-last`: open and return at once. */
826  async runCommand(kind: Exclude<SessionKind, 'plan'>, rawArgs: string): Promise<string> {
827    await this.touchLaunches()
828    const opened = await this.open(kind, rawArgs, subjectFor(kind, rawArgs))
829    switch (opened.state) {
830      case 'error':
831        // Several file paths given to a CLI that predates reviews of several
832        // files: say to update instead of showing its "pick one" error.
833        if (kind === 'annotate' && isOlderCliBundleRefusal(opened.text) && isSeveralFilePaths(wordsOf(rawArgs))) {
834          return PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT
835        }
836        return opened.text
837      case 'starting':
838        // Neutral on purpose: PLANNOTATOR_BROWSER=none opens no browser.
839        return `Starting Plannotator for ${opened.subject}… \`plannotator sessions\` lists its link once it is up, and your feedback comes back here as a message.`
840      case 'ready':
841        return openedText(kind, opened.subject, opened.url, opened.extra)
842    }
843  }
844
845  /**
846   * Claude's `plannotator` tool: the same launch as the slash command, with
847   * the call's validated arguments (never re-split). `{ deny }` is an error
848   * result for Claude (a bad call, or the CLI's startup error); `{ text }`
849   * tells Claude the page is open and to end its turn and wait.
850   */
851  async runTool(input: unknown): Promise<{ text: string } | { deny: string }> {
852    await this.adoptNewStoredLaunches()
853    await this.touchLaunches()
854    // The mod's launch can publish over the tailnet, so `tailscale` is accepted (#2166).
855    const parsed = parsePlannotatorToolInput(input, { tailscale: true })
856    if (!parsed.ok) return { deny: parsed.error }
857    const call = parsed.input
858    switch (call.action) {
859      case 'list':
860        return { text: await this.listText() }
861      case 'close':
862        return this.closeSessions(call.session as string)
863      case 'annotate':
864      case 'review':
865      case 'last':
866        break
867    }
868    const action = call.action
869    const gate = call.gate === true
870    const targets = plannotatorToolTargets(call)
871    // A list of files is one review of all of them (a bundle), named as such.
872    const bundle = Array.isArray(call.target)
873    const subject = bundle ? plannotatorBundleSubject(targets) : subjectFor(action, targets)
874    const tailscale = call.tailscale === true
875    const opened = await this.open(action, plannotatorToolArgs(call), subject, {
876      ...(gate ? { deliverApproval: true } : {}),
877      ...(tailscale ? { tailscaleAsked: true } : {}),
878    })
879    switch (opened.state) {
880      case 'error':
881        // An older CLI answers several paths with its ambiguity error.
882        if (bundle && isOlderCliBundleRefusal(opened.text)) return { deny: PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT }
883        // A CLI from before `--tailscale` refuses the word (an unknown flag or
884        // file). A current CLI's publish failure (`--tailscale: Tailscale is
885        // not running`, signed out, port routed) is shown as it is.
886        if (tailscale && isOlderCliTailscaleRefusal(opened.text)) return { deny: PLANNOTATOR_TOOL_TAILSCALE_UNAVAILABLE_TEXT }
887        return { deny: opened.text }
888      case 'starting':
889        return { text: plannotatorToolOpenedText(opened.subject, undefined, gate, opened.sessionId, opened.target) }
890      case 'ready':
891        if (tailscale && !opened.tailnet) {
892          // The CLI opened it without the tailnet's Ask this session (it
893          // predates #2166) or not on the tailnet at all (it ignored the
894          // flag): say so and do not leave it open, never a silent downgrade.
895          await this.abandonLaunch(opened.sessionId)
896          return { deny: PLANNOTATOR_TOOL_TAILSCALE_UNAVAILABLE_TEXT }
897        }
898        return {
899          text: plannotatorToolOpenedText(
900            opened.subject,
901            opened.url,
902            gate,
903            opened.sessionId,
904            opened.target,
905            tailscale ? opened.tailnet : undefined,
906          ),
907        }
908    }
909  }
910
911  /**
912   * Stop a review the tool just opened and must not leave running (a CLI too
913   * old for `tailscale`): TERM its process when the pid still names a
914   * plannotator process (`STOP_SCRIPT`), then forget it. Nothing is delivered.
915   */
916  private async abandonLaunch(sessionId: string): Promise<void> {
917    const launch = [...this.launches.values()].find((candidate) => sessionIdOf(candidate) === sessionId)
918    if (!launch) return
919    launch.settling = true
920    const pid = (await this.host.readFile(fileIn(launch.dir, 'pid')).catch(() => '')).trim()
921    if (/^\d+$/.test(pid)) {
922      await this.host.run(stopArgv(pid, [fileIn(launch.dir, 'result'), fileIn(launch.dir, 'exit')]), { timeoutMs: 5_000 }).catch(() => null)
923    }
924    await this.forget(launch)
925    await this.host.run(cleanupArgv(launch.dir), { timeoutMs: 5_000 }).catch(() => undefined)
926    this.host.debug(`abandoned ${launch.id}: the CLI cannot serve the tailnet session the tool asked for`)
927  }
928
929  // --- The agent's own sessions (list, close) ------------------------------
930
931  /** The reviews this Claude session opened that are still open (not settling, not closed by Claude). */
932  private openLaunches(): LiveLaunch[] {
933    return [...this.launches.values()].filter((launch) => !launch.settling && !launch.closedByAgent)
934  }
935
936  private hostHeaders(launch: LiveLaunch): Record<string, string> {
937    return { authorization: `Bearer ${launch.bridgeToken ?? ''}` }
938  }
939
940  /** `GET /api/host/status`, or null when the server cannot say (not up yet, an older CLI). */
941  private async hostStatus(launch: LiveLaunch): Promise<{ unsent: number; decided: boolean } | null> {
942    if (!launch.port || !launch.bridgeToken) return null
943    try {
944      const response = await this.host.fetch(`${bridgeBaseUrl(launch.port)}${HOST_STATUS_PATH}`, {
945        method: 'GET',
946        headers: this.hostHeaders(launch),
947      })
948      if (!response.ok) return null
949      // An older CLI answers its app page (200 text/html) or a JSON 404: no count.
950      const body = jsonObjectOf(response.text)
951      if (!body || typeof body.unsentAnnotations !== 'number') return null
952      return { unsent: body.unsentAnnotations, decided: body.decided === true }
953    } catch {
954      return null
955    }
956  }
957
958  /** The tool's `list`: every open review of THIS Claude session (the launch store is per session). */
959  async listText(): Promise<string> {
960    const now = await this.host.now()
961    const sessions: PlannotatorSessionSummary[] = []
962    for (const launch of this.openLaunches()) {
963      if (!launch.url) await this.readReady(launch).catch(() => false)
964      const status = launch.url ? await this.hostStatus(launch) : null
965      sessions.push({
966        id: sessionIdOf(launch),
967        kind: launch.kind,
968        subject: launch.subject,
969        ...(launch.url ? { url: launch.url } : {}),
970        ageMs: now - launch.startedAt,
971        state: !launch.url ? 'starting' : status?.decided ? 'decided' : 'open',
972        unsent: status ? status.unsent : null,
973      })
974    }
975    return plannotatorToolListText(sessions)
976  }
977
978  /** The tool's `close`: one id or "all", only among this Claude session's reviews. */
979  private async closeSessions(session: string): Promise<{ text: string } | { deny: string }> {
980    if (session === 'all') {
981      const outcomes: PlannotatorCloseOutcome[] = []
982      for (const launch of this.openLaunches()) outcomes.push(await this.closeLaunch(launch))
983      return { text: plannotatorToolCloseText(outcomes) }
984    }
985    const launch = this.openLaunches().find((candidate) => sessionIdOf(candidate) === session)
986    if (!launch) return { deny: plannotatorUnknownSessionText(session) }
987    const outcome = await this.closeLaunch(launch)
988    const text = plannotatorToolCloseText([outcome])
989    return outcome.closed ? { text } : { deny: text }
990  }
991
992  /**
993   * Close one review: the server's host close (the reviewer's Close, draft
994   * kept, the tab told), or for a CLI without it a TERM to the process (which
995   * never deletes a draft). Plan reviews end only with a decision.
996   */
997  private async closeLaunch(launch: LiveLaunch): Promise<PlannotatorCloseOutcome> {
998    const id = sessionIdOf(launch)
999    const subject = launch.subject
1000    if (launch.kind === 'plan') return { id, subject, closed: false, reason: 'plan' }
1001    if (!launch.port) {
1002      return { id, subject, closed: false, reason: 'failed', detail: 'its server has not started yet; try again in a moment' }
1003    }
1004    const response = await this.host
1005      .fetch(`${bridgeBaseUrl(launch.port)}${HOST_CLOSE_PATH}`, {
1006        method: 'POST',
1007        headers: { ...this.hostHeaders(launch), 'content-type': 'application/json' },
1008        body: '{}',
1009      })
1010      .catch(() => null)
1011    const answer = classifyHostCloseAnswer(response)
1012    switch (answer.kind) {
1013      case 'closed':
1014        await this.markClosedByAgent(launch)
1015        return { id, subject, closed: true, unsent: answer.unsent }
1016      case 'decided':
1017        // The reviewer decided first: that decision is on its way.
1018        return { id, subject, closed: false, reason: 'decided' }
1019      case 'unreachable':
1020        // Nothing answers on its port: the server is gone (the timer reports
1021        // that) or the pid is stale. Never signal a pid on a guess.
1022        return { id, subject, closed: false, reason: 'failed', detail: 'its server is not answering' }
1023      case 'refused':
1024        return { id, subject, closed: false, reason: 'failed', detail: `its server refused the close (HTTP ${answer.status})` }
1025      case 'disabled':
1026        // A current CLI that turned host control off (remote mode): its
1027        // process is not ours to signal.
1028        return {
1029          id,
1030          subject,
1031          closed: false,
1032          reason: 'failed',
1033          detail: 'it runs in remote mode, where Plannotator turns host close off; close it from the tab',
1034        }
1035      case 'older':
1036        return this.stopOlderCli(launch, id, subject)
1037    }
1038  }
1039
1040  /**
1041   * An older Plannotator (no host close) answered on the launch's port: TERM
1042   * its process, unless the reviewer's decision is already on disk or the pid
1043   * no longer names a plannotator process (`STOP_SCRIPT`). A decision such a
1044   * CLI is still publishing (it waits 1.5 s after the reviewer decides) cannot
1045   * be seen and is lost; see "Version skew" in
1046   * docs/agent-guides/claude-code-mod.md.
1047   */
1048  private async stopOlderCli(launch: LiveLaunch, id: string, subject: string): Promise<PlannotatorCloseOutcome> {
1049    const pid = (await this.host.readFile(fileIn(launch.dir, 'pid')).catch(() => '')).trim()
1050    if (!/^\d+$/.test(pid)) return { id, subject, closed: false, reason: 'failed', detail: 'its server has not started yet; try again in a moment' }
1051    const stopped = await this.host
1052      .run(stopArgv(pid, [fileIn(launch.dir, 'result'), fileIn(launch.dir, 'exit')]), { timeoutMs: 5_000 })
1053      .catch(() => null)
1054    switch (stopped?.exitCode) {
1055      case STOP_EXIT.stopped:
1056        await this.markClosedByAgent(launch)
1057        return { id, subject, closed: true, unsent: null }
1058      case STOP_EXIT.decided:
1059        return { id, subject, closed: false, reason: 'decided' }
1060      case STOP_EXIT.notPlannotator:
1061        return { id, subject, closed: false, reason: 'failed', detail: 'its server process is gone' }
1062      case STOP_EXIT.cannotVerify:
1063        return {
1064          id,
1065          subject,
1066          closed: false,
1067          reason: 'failed',
1068          detail: "this system's ps could not verify the review's process, so it was left running; close it from the tab",
1069        }
1070      default:
1071        return { id, subject, closed: false, reason: 'failed', detail: 'its server could not be stopped' }
1072    }
1073  }
1074
1075  private async markClosedByAgent(launch: LiveLaunch): Promise<void> {
1076    launch.closedByAgent = true
1077    await this.persist()
1078    this.refreshStatus()
1079    this.ensureTimer()
1080  }
1081
1082  /** A review Claude closed has exited (or published its dismissal): forget it, log one line, deliver nothing. */
1083  private async finishAgentClose(launch: LiveLaunch, record: HostResultRecord | null): Promise<void> {
1084    launch.settling = true
1085    await this.forget(launch)
1086    const unsent = record?.unsentAnnotations
1087    const saved = typeof unsent === 'number' && unsent > 0 ? ` ${unsent} unsent ${unsent === 1 ? 'comment' : 'comments'} kept in the draft.` : ''
1088    this.host.log(`Claude closed ${launch.subject} (${sessionIdOf(launch)}).${saved} Nothing was sent to Claude.`)
1089    await this.markDelivered(launch.dir)
1090    await this.host.run(cleanupArgv(launch.dir), { timeoutMs: 5_000 }).catch(() => undefined)
1091  }
1092
1093  /** The launch both entry points share: detached CLI, result later as a plugin turn, bridge, cleanup. */
1094  private async open(
1095    kind: Exclude<SessionKind, 'plan'>,
1096    args: string | readonly string[],
1097    subject: string,
1098    record: Partial<LaunchRecord> = {},
1099  ): Promise<
1100    | { state: 'error'; text: string }
1101    | { state: 'starting'; subject: string; sessionId: string; target?: PlannotatorTarget }
1102    | { state: 'ready'; subject: string; url: string; sessionId: string; extra?: string; target?: PlannotatorTarget; tailnet?: { ask: boolean } }
1103  > {
1104    if (kind === 'annotate') {
1105      // Strict gates and --hook answer on the CLI's exit code, stdout or result
1106      // file, which nothing reads under a detached launch: refuse up front.
1107      const flag = scriptOnlyAnnotateFlag(wordsOf(args))
1108      if (flag) return { state: 'error', text: scriptOnlyAnnotateFlagText(flag) }
1109    }
1110    let stdin = ''
1111    let extra: string | undefined
1112    const side: { messages?: string } = {}
1113    if (kind === 'last') {
1114      const texts = recentAssistantTexts(await this.host.messages())
1115      const text = texts[0]
1116      if (!text) return { state: 'error', text: 'There is no assistant message to annotate yet.' }
1117      // stdin always carries the newest text: all an older CLI reads.
1118      stdin = text
1119      const picker = await pickerFile(texts, (value) => this.host.sha256(value))
1120      if (picker.messages.length > 1) {
1121        side.messages = picker.json
1122        subject = RECENT_MESSAGES_SUBJECT
1123        extra = `${picker.messages.length} messages, newest first`
1124      } else {
1125        const words = text.trim().split(/\s+/).length
1126        extra = `${words} ${words === 1 ? 'word' : 'words'}`
1127      }
1128    }
1129    const started = await this.launch(kind, cliArgvFor(kind, args), subject, stdin, record, side)
1130    if ('error' in started) return { state: 'error', text: `Plannotator could not start: ${started.error}` }
1131
1132    const outcome = await this.awaitReady(started, kind === 'review' ? READY_WAIT_MS.review : READY_WAIT_MS.other)
1133    if (outcome === 'exited') return { state: 'error', text: await this.startupFailure(started) }
1134    const sessionId = sessionIdOf(started)
1135    // The launch's subject, told apart from a same-named open review, and its full target.
1136    const named = { subject: started.subject, ...(started.target !== undefined ? { target: started.target } : {}) }
1137    if (outcome === 'timeout') return { state: 'starting', sessionId, ...named }
1138    return {
1139      state: 'ready',
1140      url: started.url as string,
1141      sessionId,
1142      ...named,
1143      ...(extra ? { extra } : {}),
1144      ...(started.tailnet ? { tailnet: started.tailnet } : {}),
1145    }
1146  }
1147
1148  // --- Plan review -------------------------------------------------------------
1149
1150  /** Resolve the plan an ExitPlanMode call carries: the plan file when trustworthy (#1667), else the inline plan. */
1151  async resolvePlan(input: { plan?: unknown; planFilePath?: unknown }): Promise<string> {
1152    const inline = typeof input.plan === 'string' ? input.plan : ''
1153    const path = input.planFilePath
1154    if (!isTrustablePlanPath(path)) return inline
1155    try {
1156      const size = await this.host.fileSize(path)
1157      if (size === null || size > MAX_PLAN_FILE_BYTES) return inline
1158      return (await this.host.readFile(path)) || inline
1159    } catch {
1160      return inline
1161    }
1162  }
1163
1164  private openPlanReview(): (LiveLaunch & { version: number }) | null {
1165    for (const launch of this.launches.values()) {
1166      if (launch.kind === 'plan' && !launch.settling) return launch as LiveLaunch & { version: number }
1167    }
1168    return null
1169  }
1170
1171  /**
1172   * The `tool.call` hook on ExitPlanMode. `pass` lets the call through (the
1173   * approved plan, or a fallback to Claude Code's own flow); otherwise the
1174   * call is answered with `deny` text Claude reads.
1175   */
1176  async onPlanCall(input: { tool_use_id: string; plan?: unknown; planFilePath?: unknown }): Promise<{ pass: true } | { deny: string }> {
1177    // Another Claude Code process on this session may have received the
1178    // approval (or used it), or opened the plan review this call revises.
1179    await this.loadApproval()
1180    await this.adoptNewStoredLaunches()
1181    await this.touchLaunches()
1182    const plan = await this.resolvePlan(input)
1183    if (!plan.trim()) return { pass: true }
1184    const hash = await this.host.sha256(normalizePlanForHash(plan))
1185    const open = this.openPlanReview()
1186    const openState: OpenPlanReview | null = open
1187      ? { launchId: open.id, dir: open.dir, version: open.version, revisionSeq: open.revisionSeq ?? 0, url: open.url }
1188      : null
1189    const action = planCallAction(hash, { approval: this.approval, open: openState })
1190
1191    if (action.kind === 'pass-approved') {
1192      this.passing.set(input.tool_use_id, action.approval)
1193      this.approval = null
1194      await this.persistApproval()
1195      await this.recordPassingApproval(input.tool_use_id, action.approval)
1196      return { pass: true }
1197    }
1198
1199    // A different plan than the approved one needs its own review.
1200    if (this.approval) {
hooks/mod/enabled.ts 181 lines
1/**
2 * Whether the mod is switched on. It is ON BY DEFAULT wherever Claude Code
3 * runs hooks modules (register.ts still stands down in `-p` / SDK sessions
4 * and where there is no `/bin/sh`). The user turns it off with:
5 *
6 *   PLANNOTATOR_CLAUDE_MOD=0            (env; also false/off/disabled; wins over the config file)
7 *   { "claudeCodeMod": false }          (config.json in the data dir)
8 *
9 * Off, the mod is inert: every hook passes straight through, nothing is
10 * registered, no environment is set, and the classic PermissionRequest hook
11 * and `/plannotator-*` skills run exactly as they do without mods.
12 *
13 * Mirrors `resolveClaudeCodeMod` in packages/shared/config.ts (a hooks module
14 * may import only its own files); `enabled.test.ts` keeps the two in step.
15 */
16
17import { inboxReminderCustomText } from './inbox-contract'
18
19/** The env override: true/false, or undefined when it does not decide (unset, empty, unrecognized). */
20export function parseClaudeModEnv(value: string | undefined): boolean | undefined {
21  const v = value?.trim().toLowerCase()
22  if (v === '1' || v === 'true' || v === 'on') return true
23  if (v === '0' || v === 'false' || v === 'off' || v === 'disabled') return false
24  return undefined
25}
26
27/**
28 * config.json's `claudeCodeMod`, coerced like the CLI's other boolean keys
29 * (`coerceConfigBoolean`): a boolean, or the strings true/1 and false/0.
30 * Anything else, a missing key, or an unreadable file is the default: on.
31 */
32export function parseClaudeModConfig(configText: string | null | undefined): boolean {
33  if (!configText) return true
34  let value: unknown
35  try {
36    value = (JSON.parse(configText) as Record<string, unknown> | null)?.claudeCodeMod
37  } catch {
38    return true
39  }
40  if (typeof value === 'boolean') return value
41  if (typeof value === 'string') {
42    const v = value.trim().toLowerCase()
43    if (v === 'true' || v === '1') return true
44    if (v === 'false' || v === '0') return false
45  }
46  return true
47}
48
49export function resolveClaudeModEnabled(envValue: string | undefined, configText: string | null | undefined): boolean {
50  return parseClaudeModEnv(envValue) ?? parseClaudeModConfig(configText)
51}
52
53/**
54 * Whether the mod registers Claude's `plannotator` tool when nothing is set.
55 * Mirrors the claude-code entry of `AGENT_TOOL_DEFAULTS` in
56 * packages/shared/config.ts (enabled.test.ts keeps them equal): on here, where
57 * the tool is deferred behind tool search and costs only its name until used.
58 */
59export const AGENT_TOOL_DEFAULT = true
60
61/**
62 * Whether the mod registers the `plannotator` tool (the rest of the mod is
63 * unaffected). Off with:
64 *
65 *   PLANNOTATOR_AGENT_TOOL=0            (env; also false/off/disabled; wins over the config file)
66 *   { "agentTool": false }              (config.json in the data dir)
67 *
68 * Mirrors `resolveAgentTool(config, env, 'claude-code')` in packages/shared/config.ts. Read once, at the
69 * first session.start of the Claude Code process: the tool list is part of
70 * the prompt, so it never changes under a running session.
71 */
72export function resolveAgentToolEnabled(envValue: string | undefined, configText: string | null | undefined): boolean {
73  const fromEnv = parseClaudeModEnv(envValue)
74  if (fromEnv !== undefined) return fromEnv
75  if (!configText) return AGENT_TOOL_DEFAULT
76  let value: unknown
77  try {
78    value = (JSON.parse(configText) as Record<string, unknown> | null)?.agentTool
79  } catch {
80    return AGENT_TOOL_DEFAULT
81  }
82  if (typeof value === 'boolean') return value
83  if (typeof value === 'string') {
84    const v = value.trim().toLowerCase()
85    if (v === 'true' || v === '1') return true
86    if (v === 'false' || v === '0') return false
87  }
88  return AGENT_TOOL_DEFAULT
89}
90
91/**
92 * Whether the mod registers the `plannotator_inbox` tool and runs the reply
93 * wake when nothing is set. Mirrors the claude-code
94 * entry of `INBOX_TOOL_DEFAULTS` in packages/shared/config.ts.
95 */
96export const INBOX_TOOL_DEFAULT = true
97
98/**
99 * Whether the mod connects this session to the Plannotator Inbox (the
100 * `plannotator_inbox` tool and the reply wake). The tool is registered even
101 * before the Inbox ever ran here (a bundled tool list; the first call starts
102 * it), and the wake starts polling once `inbox/inbox.json` exists. Off with:
103 *
104 *   PLANNOTATOR_INBOX_TOOL=0            (env; also false/off/disabled; wins over the config file)
105 *   { "inboxTool": false }              (config.json in the data dir, every host)
106 *   { "inboxTool": { "claude-code": false } }   (this host only; the Inbox's Settings writes this)
107 *
108 * Mirrors `resolveInboxTool(config, env, 'claude-code')` in
109 * packages/shared/config.ts. Read once, at the first session.start of the
110 * Claude Code process, like the agent tool switch.
111 */
112export function resolveInboxToolEnabled(envValue: string | undefined, configText: string | null | undefined): boolean {
113  const fromEnv = parseClaudeModEnv(envValue)
114  if (fromEnv !== undefined) return fromEnv
115  if (!configText) return INBOX_TOOL_DEFAULT
116  let value: unknown
117  try {
118    value = (JSON.parse(configText) as Record<string, unknown> | null)?.inboxTool
119  } catch {
120    return INBOX_TOOL_DEFAULT
121  }
122  if (value && typeof value === 'object' && !Array.isArray(value)) value = (value as Record<string, unknown>)['claude-code']
123  if (typeof value === 'boolean') return value
124  if (typeof value === 'string') {
125    const v = value.trim().toLowerCase()
126    if (v === 'true' || v === '1') return true
127    if (v === 'false' || v === '0') return false
128  }
129  return INBOX_TOOL_DEFAULT
130}
131
132/**
133 * Whether a session that has the `plannotator_inbox` tool starts with the
134 * Inbox's one-line reminder (a `prompt.context` block; register.ts also
135 * requires that the Inbox has run here). Never without the tool; then on
136 * unless turned off in config.json with:
137 *
138 *   { "inboxReminder": false }                       (every host)
139 *   { "inboxReminder": { "claude-code": false } }    (this host only)
140 *
141 * There is no env var of its own: PLANNOTATOR_INBOX_TOOL decides it through
142 * the tool. Mirrors `resolveInboxReminder(config, env, 'claude-code')` in
143 * packages/shared/config.ts. Read once, at the first session.start, with the tool.
144 */
145export function resolveInboxReminderEnabled(inboxToolEnv: string | undefined, configText: string | null | undefined): boolean {
146  if (!resolveInboxToolEnabled(inboxToolEnv, configText)) return false
147  if (!configText) return true
148  let value: unknown
149  try {
150    value = (JSON.parse(configText) as Record<string, unknown> | null)?.inboxReminder
151  } catch {
152    return true
153  }
154  if (value && typeof value === 'object' && !Array.isArray(value)) value = (value as Record<string, unknown>)['claude-code']
155  if (typeof value === 'boolean') return value
156  if (typeof value === 'string') {
157    const v = value.trim().toLowerCase()
158    if (v === 'true' || v === '1') return true
159    if (v === 'false' || v === '0') return false
160  }
161  return true
162}
163
164/**
165 * The person's own Inbox reminder for Claude Code, from config.json
166 * (`prompts.inbox.runtimes["claude-code"].reminder`, then
167 * `prompts.inbox.reminder`), or null when none is usable (the built-in line
168 * then goes, byte for byte as before). `inboxReminderFor(custom, toolName)`
169 * makes the line. Mirrors `resolveInboxReminderText(config, 'claude-code', {
170 * toolName })` in packages/shared/config.ts (inbox-reminder-custom.test.ts
171 * keeps the two equal). Read once, at the first session.start, with the switch.
172 */
173export function resolveInboxReminderCustom(configText: string | null | undefined): string | null {
174  if (!configText) return null
175  try {
176    return inboxReminderCustomText(JSON.parse(configText), 'claude-code')
177  } catch {
178    return null
179  }
180}
181
hooks/mod/host.ts 106 lines
1/**
2 * What the mod's logic needs from Claude Code, as plain closures over `$`.
3 *
4 * `register.ts` builds one from the engine's `$` at `session.start`; unit
5 * tests (bun) build one from memory. Keeping every `$` call in register.ts is
6 * also what `claude plugin validate` needs to follow `$`.
7 */
8
9export interface ProcessResult {
10  exitCode: number
11  stdout: string
12  stderr: string
13}
14
15export interface HttpResult {
16  status: number
17  ok: boolean
18  text: string
19}
20
21export interface TranscriptMessage {
22  role: 'user' | 'assistant'
23  text: string
24}
25
26/** What this process loaded: the Inbox poll's `plugin` field. */
27export interface LoadedPluginInfo {
28  /** plugin.json's version; null when unreadable. */
29  version: string | null
30  /** The plugin's folder (`$.plugin.root`); null when it could not be read. */
31  root: string | null
32  /** When the module loaded, ms since the epoch. */
33  loaded_at: number
34}
35
36export interface TimerHandle {
37  cancel: () => void
38}
39
40export interface Host {
41  now(): Promise<number>
42  /**
43   * `$.clock.sleep`: counts against a hook's 10 s budget while it waits, so
44   * never used inside one, except as a short bound raced against a `$` call
45   * (inbox.ts `within`), aborted through `signal` the moment that call settles.
46   */
47  sleep(ms: number, signal?: AbortSignal): Promise<void>
48  /**
49   * Resolve once any of `paths` exists, or after `timeoutMs`. Waits inside a
50   * `$.process.run` call, which (unlike a `$.clock` wait) does not count
51   * against a hook's budget.
52   */
53  waitForAny(paths: readonly string[], timeoutMs: number): Promise<void>
54  every(ms: number, fn: () => void): TimerHandle
55  run(argv: readonly string[], init?: { cwd?: string; env?: Record<string, string>; stdin?: string; timeoutMs?: number }): Promise<ProcessResult>
56  readFile(path: string): Promise<string>
57  writeFile(path: string, text: string): Promise<void>
58  exists(path: string): Promise<boolean>
59  /** Size in bytes, or null when the path is not a regular file. */
60  fileSize(path: string): Promise<number | null>
61  storeGet(key: string): Promise<unknown>
62  storeSet(key: string, value: unknown): Promise<void>
63  /** `$.prompt.submit`: runs once the session is idle, read under the plugin's name. */
64  submit(text: string): Promise<void>
65  /**
66   * `$.session.append` of a user-role row (the model reads it; the person
67   * does not see it as typed): in a running turn it is in the turn's next
68   * model request, the one way a plugin puts words into a running turn
69   * (`$.prompt.submit` never folds into one). Rejects when the row was
70   * refused, or the engine has no `$.session.append`. Optional for hosts
71   * (tests) that model an engine without it.
72   */
73  appendUserRow?(text: string): Promise<void>
74  /**
75   * Whether this engine has `$.session.append` (a build that documents it;
76   * `claude plugin validate` refuses reading `$.session.append` as a value,
77   * so it is decided from the engine's version). Absent or false: Send now
78   * is never advertised.
79   */
80  sessionAppendAvailable?(): Promise<boolean>
81  /**
82   * The plugin this process loaded: its plugin.json version, its folder
83   * (`$.plugin.root`) and when the module loaded (ms). Read once per process.
84   * The Inbox poll carries it, so the Inbox can say when a restart would
85   * load a newer plugin. The engine's host always answers (with null parts
86   * when a read failed); optional for test hosts, which then send nothing.
87   */
88  loadedPlugin?(): Promise<LoadedPluginInfo | null>
89  /** Claude Code's own version (`$.session.version()`'s `base`); null when unknown. Optional. */
90  engineVersion?(): Promise<string | null>
91  /** `$.session.append` of a notice the transcript shows and the model never reads. */
92  appendNotice?(text: string): Promise<void>
93  suggest(text: string): Promise<void>
94  status(text: string | undefined): void
95  log(text: string): void
96  toast(text: string): void
97  messages(): Promise<TranscriptMessage[]>
98  /** `body` absent for a GET. */
99  fetch(url: string, init: { method: string; headers: Record<string, string>; body?: string }): Promise<HttpResult>
100  abortTurn(turnId: string): Promise<void>
101  randomHex(bytes: number): string
102  /** A line in the mod's debug log (PLANNOTATOR_MOD_DEBUG=1); a no-op otherwise. */
103  debug(text: string): void
104  sha256(text: string): Promise<string>
105}
106
hooks/mod/inbox.ts 962 lines
1/**
2 * The Claude Code connection to the Plannotator Inbox (plan step 6): the
3 * `plannotator_inbox` tool and the reply wake. One `InboxLink` per session,
4 * owned by that session's `PlannotatorMod`.
5 *
6 * Registered wherever the inbox tool switch allows it
7 * (`resolveInboxToolEnabled`, on by default), also before this computer ever
8 * ran the Inbox. The tool's actions are the Inbox's own MCP tools, read from
9 * its `/mcp` once at session start (`discoverInboxTools`): from a running
10 * Inbox, else the list one last answered with, else the list bundled with the
11 * mod (`INBOX_DEFAULT_TOOLS`, generated from a real Inbox). An older Inbox
12 * offers fewer, and the tool simply has fewer actions. The tool list never
13 * changes under a running session. With no `inbox/inbox.json` the link stays
14 * silent (no HTTP, no files) until a call starts the Inbox.
15 *
16 * The tool: each call re-reads the registry (never caching the port or
17 * token), starts a stopped Inbox with `plannotator inbox --background` (it
18 * detaches into its own session and never opens a browser), and proxies the
19 * call to the Inbox's `/mcp` with `project_path` the session's working folder
20 * (or the folder the agent named, resolved against it and checked to exist)
21 * and `agent_session` the host's real session id.
22 *
23 * The wake: a 1 s tick long-polls `POST /api/inbox/bridge/poll` (bearer token,
24 * no Origin) for the person's replies to this session's messages, with a 5 to
25 * 60 s backoff that never gives up for good. A reply waits HERE until the
26 * session has been idle for a tick (a pending `$.prompt.submit` cannot be
27 * withdrawn, and a prompt the person typed, or a `/clear`, queued during a
28 * turn goes first), is checked once more with the Inbox, claimed once across
29 * processes, submitted as a turn (`inboxWakeText`), and acknowledged
30 * (`delivered`), which the thread shows as "Delivered to Claude Code, <time>".
31 * Send now (the person pressed it in the Inbox; the command's `now`) does not
32 * wait for idle: while a turn runs the reply goes INTO it as a user row
33 * (`$.session.append`, which the turn's next model request carries; a
34 * plugin's `$.prompt.submit` never folds into a running turn), else as a turn
35 * at once. A row that landed as the turn made its last request is pointed at
36 * by one short turn after (`inboxSentNowFollowUpText`). The poll says the
37 * engine can (`send_now`), so the window offers Send now only then.
38 * A New message the person addressed to this session (plan step 8) arrives
39 * on the same poll and takes the same path. Each poll also tells the Inbox
40 * where the session works and whether a turn runs, and a `state` event tells
41 * it when a turn starts or ends: the Inbox lists live sessions from these.
42 *
43 * Two Claude Code processes on one session (`claude --continue` while the
44 * first still runs): one of them polls and delivers, the holder of the
45 * session's inbox lease (`watcher.json`, the person's last process wins, as
46 * for reviews); a delivery is also claimed once per reply (mkdir), so a lease
47 * race can never deliver twice. A reply another process claimed and never
48 * delivered (it quit while the turn waited) is said once, with a toast.
49 */
50
51import type { Host, HttpResult, LoadedPluginInfo } from './host'
52import {
53  INBOX_BRIDGE_EVENT_PATH,
54  INBOX_BRIDGE_POLL_PATH,
55  inboxReminderFor,
56  inboxToolCall,
57  inboxToolCallParams,
58  inboxToolResultText,
59  INBOX_SEND_NOW_POLL_FIELD,
60  INBOX_TAGS_POLL_FIELD,
61  inboxSentNowFollowUpText,
62  inboxWakeText,
63  mcpAnswerOfResponse,
64  parseInboxBridgeCommands,
65  parseInboxRegistry,
66  parseInboxToolList,
67  type InboxRegistryView,
68  type InboxReplyCommand,
69  type InboxToolInfo,
70} from './inbox-contract'
71import { INBOX_DEFAULT_TOOLS } from './inbox-default-tools'
72import { privateDirArgv } from './launch'
73
74/**
75 * The first Claude Code whose published hooks-module API documents
76 * `$.session.append` (the 2.1.301 plugin-authoring types): the oldest engine
77 * Send now is offered on. A module cannot test for the noun itself
78 * (`claude plugin validate` refuses reading `$.session.append` as a value),
79 * so the engine's version decides; an older or unknown one never advertises
80 * Send now.
81 */
82export const SESSION_APPEND_MIN_ENGINE = '2.1.301'
83
84/** Whether an engine version (`$.session.version()`'s `base`, else `version`) is at least SESSION_APPEND_MIN_ENGINE. */
85export function engineHasSessionAppend(version: string | null | undefined): boolean {
86  const parts = /^(\d+)\.(\d+)\.(\d+)/.exec(typeof version === 'string' ? version.trim() : '')
87  if (!parts) return false
88  const min = SESSION_APPEND_MIN_ENGINE.split('.').map(Number)
89  const have = parts.slice(1, 4).map(Number)
90  for (let i = 0; i < 3; i++) {
91    if (have[i]! !== min[i]!) return have[i]! > min[i]!
92  }
93  return true
94}
95
96/** plugin.json's `version` (the plugin this process loaded); null when unreadable. */
97export function pluginVersionOf(text: string | null): string | null {
98  if (!text) return null
99  try {
100    const parsed = JSON.parse(text) as { version?: unknown }
101    return typeof parsed?.version === 'string' && parsed.version.trim() && parsed.version.length <= 64 ? parsed.version.trim() : null
102  } catch {
103    return null
104  }
105}
106
107/** The host this connection names on its messages and deliveries. */
108export const INBOX_HOST = 'claude-code'
109/** How the person sees this agent in the Inbox. */
110export const INBOX_AGENT_NAME = 'Claude Code'
111/** The `prompt.context` block that carries the Inbox reminder. */
112export const INBOX_REMINDER_BLOCK = 'plannotatorInbox'
113
114/**
115 * The first message's context blocks with the Inbox reminder last
116 * (`inboxReminderFor(custom, toolName)`: the person's own text from
117 * config.json, else the fixed line, naming the tool as the engine registered
118 * it, so tool search finds the deferred tool). Never twice: a block of that
119 * name already there (a hook above added it) is left as it is.
120 */
121export function withInboxReminder<T extends { name: string; text: string }>(blocks: readonly T[], toolName: string, custom: string | null = null): Array<T | { name: string; text: string }> {
122  if (blocks.some((block) => block?.name === INBOX_REMINDER_BLOCK)) return [...blocks]
123  return [...blocks, { name: INBOX_REMINDER_BLOCK, text: inboxReminderFor(custom, toolName) }]
124}
125
126/**
127 * `$.store` key: whether this machine's Claude Code runs the mod's
128 * `prompt.context` hook. `true`: seen running (the block reaches the model);
129 * `false`: a conversation's first turn completed without it (a guard plugin
130 * seated above the mod, Claude Code's `cc-plugin-sec-default` on
131 * Team/Enterprise accounts, sent the event past it, #2159); absent: not
132 * learned yet. Read once per process.
133 */
134export const STORE_INBOX_REMINDER_CONTEXT_WORKS = 'inboxReminderContextWorks'
135
136/**
137 * The variable the mod sets to the reminder text (with the tool's full
138 * registered name) at session start, for the plugin's `SessionStart` command
139 * hook matched on `compact` (hooks.json): after a compaction that hook prints
140 * it, and the engine adds the line to the conversation. Unset when the
141 * reminder is off. `$.env.set` needs the name spelled as a literal in
142 * register.ts; register.test.ts keeps that spelling equal to this constant.
143 */
144export const INBOX_REMINDER_ENV = 'PLANNOTATOR_INBOX_REMINDER'
145
146/**
147 * A session whose `$.session.usage().startedAt` is this much older than the
148 * process's first `session.start` was started by an earlier process (a
149 * `--resume` / `--continue`, an in-process `/resume`): its first turn here is
150 * not the conversation's first, so it teaches nothing about `prompt.context`.
151 */
152export const INBOX_REMINDER_RESUMED_SLACK_MS = 60_000
153
154/** The stored `inboxReminderContextWorks`: a boolean, or undefined for anything else. */
155export function readReminderContextWorks(value: unknown): boolean | undefined {
156  return value === true || value === false ? value : undefined
157}
158
159/**
160 * Whether a `prompt.submit` carries the reminder as `context` (the learned
161 * fallback for a machine where `prompt.context` is skipped). Only on a
162 * conversation that has not had it by either path, only while this machine
163 * has no evidence that `prompt.context` runs, and never on a meta prompt or a
164 * slash command (a command may run no model turn, and the copy would be
165 * marked delivered for nothing).
166 */
167export function inboxReminderSubmitCopy(input: {
168  delivered: boolean
169  contextWorks: boolean | undefined
170  isMeta: boolean
171  command: boolean
172}): boolean {
173  return !input.delivered && input.contextWorks !== true && !input.isMeta && !input.command
174}
175
176/**
177 * What the first main-loop `turn.complete` of a conversation teaches.
178 * `done: false`: not decided yet, look again at the next one (an aborted turn
179 * may end before the first request was built, before `prompt.context` had its
180 * chance). `write: false`: store `inboxReminderContextWorks = false` (the
181 * conversation's first request went out without the mod's `prompt.context`).
182 */
183export function inboxReminderFirstTurnLesson(input: {
184  contextRan: boolean
185  aborted: boolean
186  resumed: boolean
187  contextWorks: boolean | undefined
188}): { done: boolean; write: false | null } {
189  if (input.aborted) return { done: false, write: null }
190  if (input.contextRan || input.resumed || input.contextWorks === false) return { done: true, write: null }
191  return { done: true, write: false }
192}
193
194/**
195 * Whether the session was started by an earlier process: `startedAt` is the
196 * session's first launch (`$.session.usage()`), `processStartedAt` this
197 * process's first `session.start`, both in `$.clock.now()` milliseconds. An
198 * unreadable `startedAt` counts as not resumed.
199 */
200export function reminderSessionResumed(startedAt: unknown, processStartedAt: number | null): boolean {
201  if (typeof startedAt !== 'number' || !Number.isFinite(startedAt) || processStartedAt === null) return false
202  return startedAt < processStartedAt - INBOX_REMINDER_RESUMED_SLACK_MS
203}
204
205/**
206 * The value of `PLANNOTATOR_INBOX_REMINDER`: the reminder naming the tool by
207 * its registered full name while the reminder is on, else undefined (unset,
208 * which also clears a value inherited from a parent Claude Code). The hook
209 * prints it with `printf "%s\n"` (hooks.json), so every byte comes out as it
210 * is, a custom text's backslashes, leading `-`, `%`, quotes and `$(...)`
211 * included, and nothing in it runs.
212 */
213export function inboxReminderEnvValue(on: boolean, toolName: string | null, custom: string | null = null): string | undefined {
214  if (!on || !toolName) return undefined
215  return inboxReminderFor(custom, toolName)
216}
217
218/** `$.store` key: the Inbox tool list last read live, used when the Inbox is stopped at session start. */
219export const STORE_INBOX_TOOLS = 'inboxTools'
220
221/** Poll wait we ask for: under the server's 25 s hold and `$.http.fetch`'s 30 s. */
222export const INBOX_POLL_WAIT_MS = 20_000
223/** After a failed poll: 5 s, doubling to 60 s while the Inbox stays away, never giving up. */
224export const INBOX_RETRY_MS = { first: 5_000, max: 60_000 } as const
225/**
226 * wait_for_reply's longest hold through this tool: `$.http.fetch` gives up at
227 * 30 s, so the call asks the Inbox for at most 25 s (the Inbox's own default
228 * is 50 s, for MCP hosts with a 60 s tool timeout).
229 */
230export const INBOX_WAIT_MAX_SECONDS = 25
231/** The tick: one per second, as the mod's review watcher. */
232export const INBOX_TICK_MS = 1_000
233/** How often the lease is renewed or re-read. */
234const LEASE_EVERY_MS = 5_000
235/** A lease not renewed for this long belongs to a process that exited, slept or hung. */
236export const INBOX_LEASE_STALE_MS = 20_000
237/** A claimed reply whose claimant stopped saying it is alive for this long is reported as undelivered. */
238export const INBOX_UNDELIVERED_AFTER_MS = 60_000
239/**
240 * The longest session start waits for a running Inbox's `tools/list`. The
241 * person's first prompt waits for session.start, and `$.http.fetch` gives up
242 * only after 30 s, so an Inbox that accepts and never answers (stopped with
243 * Ctrl-Z, or a port another server reused and holds) would hold that prompt
244 * for 30 s; past this bound the remembered list stands.
245 */
246export const INBOX_DISCOVER_TIMEOUT_MS = 2_000
247/** `plannotator inbox --background` waits up to 20 s for the Inbox to answer. */
248const START_TIMEOUT_MS = 30_000
249
250export function inboxRegistryPathOf(dataDir: string): string {
251  return `${dataDir}/inbox/inbox.json`
252}
253
254/** This session's inbox folder in the mod's data: the lease and the delivery claims. */
255export function inboxSessionDirOf(dataDir: string, sessionId: string): string {
256  return `${dataDir}/claude-code-mod/${sessionId}/inbox`
257}
258
259/** Exit codes of `INBOX_CLAIM_SCRIPT`. */
260export const INBOX_CLAIM_EXIT = { won: 0, lost: 3, failed: 4 } as const
261
262/**
263 * Claims one reply's delivery across processes: mkdir is atomic, so exactly
264 * one process makes `$1`; the winner writes its id (`$2`) to `by`, so the same
265 * instance whose process call lost its answer wins again on retry.
266 */
267export const INBOX_CLAIM_SCRIPT = [
268  'd=$1; me=$2',
269  'umask 077',
270  'mkdir -p "$(dirname "$d")" || exit 4',
271  `if mkdir "$d" 2>/dev/null; then printf '%s' "$me" > "$d/by"; exit 0; fi`,
272  '[ "$(cat "$d/by" 2>/dev/null)" = "$me" ] && exit 0',
273  '[ -d "$d" ] && exit 3',
274  'exit 4',
275].join('\n')
276
277export function inboxClaimArgv(dir: string, claimant: string): string[] {
278  return ['/bin/sh', '-c', INBOX_CLAIM_SCRIPT, 'plannotator-inbox-claim', dir, claimant]
279}
280
281/**
282 * Gives back a claim nothing was submitted under (the turn it was to go into
283 * is busy, or Send now's row was refused): removes `$1` only while it is
284 * still `$2`'s and neither delivered nor reported, so whichever process the
285 * person works in can claim it again (exactly once still holds: mkdir has one
286 * winner, and nothing went in under the claim given back).
287 */
288export const INBOX_RELEASE_SCRIPT = [
289  'd=$1; me=$2',
290  '[ "$(cat "$d/by" 2>/dev/null)" = "$me" ] || exit 0',
291  '[ -e "$d/delivered" ] || [ -e "$d/reported" ] && exit 0',
292  'rm -rf "$d"',
293].join('\n')
294
295export function inboxReleaseArgv(dir: string, claimant: string): string[] {
296  return ['/bin/sh', '-c', INBOX_RELEASE_SCRIPT, 'plannotator-inbox-release', dir, claimant]
297}
298
299/**
300 * An agent's `project_path` as an existing folder: `$2` as given when
301 * absolute, else under the working folder `$1` (never through CDPATH, and
302 * `./` first so a name starting with `-` is a name). Prints the physical
303 * path; exit 3 when it is not a folder this process can enter.
304 */
305export const INBOX_PROJECT_DIR_SCRIPT = [
306  'CDPATH=',
307  'case "$2" in /*) cd -- "$2" ;; *) cd -- "$1" && cd -- "./$2" ;; esac 2>/dev/null || exit 3',
308  'pwd -P',
309].join('\n')
310
311export function inboxProjectDirArgv(cwd: string, given: string): string[] {
312  return ['/bin/sh', '-c', INBOX_PROJECT_DIR_SCRIPT, 'plannotator-inbox-project', cwd, given]
313}
314
315async function mcpCall(host: Host, port: number, method: string, params: Record<string, unknown>): Promise<{ result?: unknown; error?: { message?: string } } | null> {
316  const response = await host.fetch(`http://127.0.0.1:${port}/mcp`, {
317    method: 'POST',
318    headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
319    body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
320  })
321  return mcpAnswerOfResponse(response.status, response.text)
322}
323
324/** `work`'s answer, or null once `ms` passed first; the bounding sleep is aborted as soon as `work` settles. */
325async function within<T>(host: Host, ms: number, work: Promise<T>): Promise<T | null> {
326  const stop = new AbortController()
327  const late = host.sleep(ms, stop.signal).then(
328    () => null,
329    () => null,
330  )
331  try {
332    return await Promise.race([work, late])
333  } finally {
334    stop.abort()
335  }
336}
337
338/**
339 * The Inbox tools this session's `plannotator_inbox` tool carries, decided
340 * once at session start. A running Inbox is asked (`tools/list`) and its
341 * answer remembered; a stopped one is described by the list it last answered
342 * with; with neither (this computer never ran the Inbox, or nothing was
343 * remembered), the list bundled with the mod. The first call starts a stopped
344 * Inbox (`plannotator inbox --background`).
345 */
346export async function discoverInboxTools(host: Host, dataDir: string): Promise<InboxToolInfo[]> {
347  const path = inboxRegistryPathOf(dataDir)
348  const registry = (await host.exists(path)) ? parseInboxRegistry(await host.readFile(path).catch(() => null)) : null
349  if (registry) {
350    const answer = await within(host, INBOX_DISCOVER_TIMEOUT_MS, mcpCall(host, registry.port, 'tools/list', {})).catch(() => null)
351    const tools = answer && 'result' in answer ? parseInboxToolList(answer.result) : []
352    if (tools.length > 0) {
353      await host.storeSet(STORE_INBOX_TOOLS, { tools }).catch(() => undefined)
354      return tools
355    }
356  }
357  const remembered = parseInboxToolList(await host.storeGet(STORE_INBOX_TOOLS).catch(() => null))
358  return remembered.length > 0 ? remembered : INBOX_DEFAULT_TOOLS.map((tool) => ({ ...tool }))
359}
360
361interface InboxLease {
362  owner: string | null
363  at: number
364  touchedAt: number
365}
366
367function parseLease(text: string): InboxLease | null {
368  try {
369    const value = JSON.parse(text) as Record<string, unknown>
370    if (typeof value.at !== 'number') return null
371    return { owner: typeof value.owner === 'string' && value.owner ? value.owner : null, at: value.at, touchedAt: typeof value.touchedAt === 'number' ? value.touchedAt : 0 }
372  } catch {
373    return null
374  }
375}
376
377export interface InboxLinkOptions {
378  host: Host
379  dataDir: string
380  sessionId: string
381  tools: readonly InboxToolInfo[]
382  /**
383   * The name the engine registered the tool under (`mcp__<server>__plannotator_inbox`),
384   * named in the wake's closing line so the model can find the tool. Absent: `plannotator_inbox`.
385   */
386  toolName?: string
387  /** A turn is running (or a question of Ask this session is in flight). */
388  isBusy: () => boolean
389  /**
390   * The main-loop turn running now when a Send now reply may go into it, else
391   * null: never the turn of this session's own "Ask this session" question
392   * (its answer streams to Plannotator), and null while that question is
393   * queued with no turn running. Absent: Send now is never advertised.
394   */
395  steerableTurn?: () => string | null
396  /** The session's working folder, sent with each poll so New message can find the session by project. */
397  cwd?: () => Promise<string>
398  /**
399   * The session's root (`$.session.root()`), read once when the link starts
400   * (a later /cd moves it) and sent as `session_folder`: the folder
401   * `claude --resume` runs in, for the Inbox's restart command.
402   */
403  root?: () => Promise<string>
404  /** Names this process in the lease and the claims. */
405  instanceId: string
406}
407
408export class InboxLink {
409  readonly tools: readonly InboxToolInfo[]
410  private readonly host: Host
411  private readonly dir: string
412  private timer: { cancel: () => void } | null = null
413  private disposed = false
414  private ticking = false
415  private polling = false
416  private retryAt = 0
417  private backoffMs = 0
418  private madeDir = false
419  private leader = false
420  private leaseCheckedAt = Number.NEGATIVE_INFINITY
421  /** When the person last acted in this process (created, typed, called the tool); the most recent touch wins the lease. */
422  private touchedAt = 0
423  /** Ticks in a row the session was idle; a reply goes in once it is idle for a whole tick. */
424  private idleTicks = 0
425  /** Replies handed out by the Inbox and not yet settled here, in arrival order. */
426  private pending = new Map<string, InboxReplyCommand>()
427  /** Replies settled here (delivered, dropped, claimed elsewhere, reported). */
428  private settled = new Set<string>()
429  /** Delivered here (or by a claimant that quit), not yet acknowledged to the Inbox. */
430  private unacked = new Set<string>()
431  /** Claimed by another process, watched until delivered or reported. */
432  private elsewhere = new Map<string, { command: InboxReplyCommand; since: number }>()
433  /** The reply whose turn this process is submitting, kept alive in its claim. */
434  private submitting: string | null = null
435  /**
436   * Every claim this process won and is submitting under (never one it waits
437   * on: a claim it cannot use at once is given back, `release`). Each one's
438   * `alive` is refreshed with the lease, so another process never reports a
439   * reply this one is still delivering.
440   */
441  private readonly held = new Set<string>()
442  /** The `alive` refresh in flight, which `release` waits for so no write lands in a claim it removed. */
443  private aliveRefresh: Promise<void> = Promise.resolve()
444  private delivering = false
445  /** When this link started (the session, near enough), and the turn state last told the Inbox (step 8). */
446  private startedAt = 0
447  private busy: boolean | null = null
448  private idleSince = 0
449  /**
450   * A reply Send now put into the running turn (`appendUserRow`), until that
451   * turn ends: `stepped` once a main-loop model request went out after it
452   * (that request carries it). A turn that ends with none read it, so a short
453   * turn points Claude at it.
454   */
455  private sentNow: { command: InboxReplyCommand; turnId: string; stepped: boolean }[] = []
456  /** Whether this engine has `$.session.append` (decided once, `Host.sessionAppendAvailable`). */
457  private appendOk: boolean | null = null
458  /** What the Inbox was last told about Send now (`send_now` on the poll and the state events). */
459  private lastSendNow: boolean | null = null
460  /** Send now could not go into the running turn (the engine refused the row): these wait for idle, as before. */
461  private noSteer = new Set<string>()
462  /** The engine refused a row once (an engine without `$.session.append`): stop offering Send now. */
463  private steerRefused = false
464  /** What this process loaded, read once (`loadedNow`). */
465  private loaded: Promise<{ plugin: LoadedPluginInfo | null; engine: string | null }> | null = null
466  /** Where the session started, read once (`folderNow`). */
467  private folder: Promise<string | null> | null = null
468
469  constructor(private readonly options: InboxLinkOptions) {
470    this.host = options.host
471    this.tools = options.tools
472    this.dir = inboxSessionDirOf(options.dataDir, options.sessionId)
473  }
474
475  get isDisposed(): boolean {
476    return this.disposed
477  }
478
479  /** Start the tick. The person is in this process now. */
480  start(): void {
481    if (this.timer || this.disposed) return
482    void this.host.now().then((now) => {
483      this.startedAt ||= now
484      this.idleSince ||= now
485    })
486    void this.touch()
487    this.timer = this.host.every(INBOX_TICK_MS, () => {
488      if (this.ticking) return
489      this.ticking = true
490      void this.tick()
491        .catch((error: unknown) => this.host.debug(`inbox tick: ${error instanceof Error ? error.message : String(error)}`))
492        .finally(() => {
493          this.ticking = false
494        })
495    })
496  }
497
498  /** The session ended (`session.end`, `/clear`): stop, and let another process take the lease at once. */
499  dispose(): void {
500    if (this.disposed) return
501    this.disposed = true
502    this.timer?.cancel()
503    this.timer = null
504    if (this.leader) void this.host.writeFile(this.leasePath, JSON.stringify({ owner: null, at: 0, touchedAt: 0 })).catch(() => undefined)
505    this.leader = false
506  }
507
508  /** The person acted in this process: replies should land here, from now on. */
509  async touch(): Promise<void> {
510    this.touchedAt = await this.host.now()
511    if (this.disposed) return
512    // No Inbox has ever run here: nothing to deliver, so nothing is written;
513    // the lease is taken on the first tick after a call starts the Inbox.
514    if (!(await this.host.exists(this.registryPath))) this.leaseCheckedAt = Number.NEGATIVE_INFINITY
515    else if (await this.ensureDir()) await this.holdLease(this.touchedAt)
516    else this.leaseCheckedAt = Number.NEGATIVE_INFINITY
517  }
518
519  /** This session's inbox folder, owner-only, made once. */
520  private async ensureDir(): Promise<boolean> {
521    if (this.madeDir) return true
522    const made = await this.host.run(privateDirArgv(this.dir), { timeoutMs: 5_000 }).catch(() => null)
523    this.madeDir = made?.exitCode === 0
524    return this.madeDir
525  }
526
527  /**
528   * Someone else's prompt entered the session. At idle (no turn id) its turn
529   * is about to start, so the idle count starts over; the person typing here
530   * also pulls the lease to this process.
531   */
532  onForeignPrompt(prompt: { turnId?: string; originKind?: string }): void {
533    if (!prompt.turnId) this.idleTicks = 0
534    if (prompt.originKind === 'composer') void this.touch()
535  }
536
537  // --- The tool --------------------------------------------------------------
538
539  /** A `plannotator_inbox` call: the Inbox tool it stands for, through the Inbox's `/mcp`. */
540  async callTool(input: unknown, cwd: string): Promise<{ text: string } | { deny: string }> {
541    await this.touch()
542    const call = inboxToolCall(input, this.tools, {
543      project_path: cwd,
544      agent_session: this.options.sessionId,
545      agent_host: INBOX_HOST,
546      agent_name: INBOX_AGENT_NAME,
547    })
548    if ('error' in call) return { deny: call.error }
549    if (call.projectPath !== undefined) {
550      // The agent named the project: an existing folder, relative to the working folder, or nothing reaches the Inbox.
551      const dir = await this.host.run(inboxProjectDirArgv(cwd, call.projectPath), { timeoutMs: 5_000 }).catch(() => null)
552      const resolved = dir?.exitCode === 0 ? dir.stdout.replace(/\n$/, '') : ''
553      if (!resolved.startsWith('/')) return { deny: `Invalid plannotator_inbox call: project_path ${call.projectPath} is not an existing folder.` }
554      call.arguments.project_path = resolved
555    }
556    if (call.name === 'wait_for_reply') {
557      const asked = typeof call.arguments.timeout_seconds === 'number' ? call.arguments.timeout_seconds : INBOX_WAIT_MAX_SECONDS
558      call.arguments.timeout_seconds = Math.max(1, Math.min(asked, INBOX_WAIT_MAX_SECONDS))
559    }
560    const running = await this.ensureRunning()
561    if ('error' in running) return { deny: running.error }
562    let answer: Awaited<ReturnType<typeof mcpCall>>
563    try {
564      // This session's wake delivers the reply as a turn: the send tools say to end the turn.
565      answer = await mcpCall(this.host, running.port, 'tools/call', inboxToolCallParams(call, { wakes: true }))
566    } catch (error) {
567      return { deny: `The Plannotator Inbox did not answer (${error instanceof Error ? error.message : String(error)}).` }
568    }
569    if (!answer) return { deny: 'The Plannotator Inbox gave an answer this session could not read.' }
570    if (answer.error) {
571      const message = answer.error.message ?? 'unknown error'
572      // An action this Inbox lost (a downgrade since session start).
573      if (/not found|unknown tool/i.test(message)) return { deny: `This Plannotator Inbox has no ${call.name}; update Plannotator. (${message})` }
574      return { deny: `The Plannotator Inbox refused the call: ${message}` }
575    }
576    const result = inboxToolResultText(answer.result)
577    return result.isError ? { deny: result.text } : { text: result.text }
578  }
579
580  private get registryPath(): string {
581    return inboxRegistryPathOf(this.options.dataDir)
582  }
583
584  private async registry(): Promise<InboxRegistryView | null> {
585    return parseInboxRegistry(await this.host.readFile(this.registryPath).catch(() => null))
586  }
587
588  /** Running: the registry's port answers health with the registry's serverSession. */
589  private async isRunning(registry: InboxRegistryView): Promise<boolean> {
590    const response = await this.host
591      .fetch(`http://127.0.0.1:${registry.port}/api/inbox/health`, { method: 'GET', headers: {} })
592      .catch(() => null)
593    if (!response || response.status !== 200) return false
594    try {
595      return (JSON.parse(response.text) as { serverSession?: unknown }).serverSession === registry.serverSession
596    } catch {
597      return false
598    }
599  }
600
601  /** The running Inbox, starting a stopped one detached (no browser) first. */
602  private async ensureRunning(): Promise<InboxRegistryView | { error: string }> {
603    const known = await this.registry()
604    if (known && (await this.isRunning(known))) return known
605    const started = await this.host
606      .run(['plannotator', 'inbox', '--background'], { env: { PLANNOTATOR_DATA_DIR: this.options.dataDir }, timeoutMs: START_TIMEOUT_MS })
607      .catch((error: unknown) => ({ exitCode: -1, stdout: '', stderr: error instanceof Error ? error.message : String(error) }))
608    if (started.exitCode !== 0) {
609      const why = started.stderr.trim() || started.stdout.trim() || `exit ${started.exitCode}`
610      if (/unknown command/i.test(why)) return { error: 'The plannotator on PATH has no Inbox (an older version); update Plannotator.' }
611      return { error: `The Plannotator Inbox did not start: ${why}` }
612    }
613    this.host.debug(`inbox: started with --background (${started.stdout.trim()})`)
614    const now = await this.registry()
615    return now ?? { error: 'The Plannotator Inbox started but wrote no registry.' }
616  }
617
618  // --- The wake --------------------------------------------------------------
619
620  private get leasePath(): string {
621    return `${this.dir}/watcher.json`
622  }
623
624  private claimDir(replyId: string): string {
625    return `${this.dir}/claims/${replyId}`
626  }
627
628  private async tick(): Promise<void> {
629    // Silent until an Inbox exists (the first plannotator_inbox call starts one): no HTTP, no files.
630    if (this.disposed || !(await this.host.exists(this.registryPath)) || !(await this.ensureDir())) return
631    const busy = this.options.isBusy()
632    this.idleTicks = busy ? 0 : this.idleTicks + 1
633    const now = await this.host.now()
634    // Whether a Send now reply could go in right now: never while this session's own Ask question holds it.
635    const sendNow = await this.sendNowNow()
636    if (busy !== this.busy || sendNow !== this.lastSendNow) {
637      const known = this.busy !== null
638      if (busy !== this.busy && !busy) this.idleSince = now
639      this.busy = busy
640      this.lastSendNow = sendNow
641      // A turn started or ended: the Inbox's live sessions say so (step 8), and whether Send now can go in.
642      if (known && this.leader) void this.bridge(INBOX_BRIDGE_EVENT_PATH, { type: 'state', busy, idle_since: this.idleSince, [INBOX_SEND_NOW_POLL_FIELD]: sendNow })
643    }
644    if (now - this.leaseCheckedAt >= LEASE_EVERY_MS) {
645      await this.holdLease(now)
646      this.aliveRefresh = (async () => {
647        for (const id of this.held) await this.host.writeFile(`${this.claimDir(id)}/alive`, String(now)).catch(() => undefined)
648      })()
649      await this.aliveRefresh
650      for (const id of [...this.elsewhere.keys()]) await this.watchElsewhere(id, now)
651    }
652    for (const id of [...this.unacked]) await this.acknowledge(id)
653    if (!this.leader) return
654    if (!this.polling && now >= this.retryAt) void this.poll()
655    // Send now (the person pressed it in the Inbox): the waiting replies go in without waiting for two
656    // idle ticks, oldest first (an urgent reply never overtakes an older one), but only when there is a
657    // turn they may go into or the session is idle: never into this session's own Ask question.
658    const urgent =
659      this.idleTicks < 2 &&
660      [...this.pending.values()].some((command) => command.now === true && !this.noSteer.has(command.id)) &&
661      (this.steerableTurn() !== null || !this.options.isBusy())
662    if (!this.delivering && this.pending.size > 0 && (this.idleTicks >= 2 || urgent)) {
663      this.delivering = true
664      void this.deliverNext(urgent).finally(() => {
665        this.delivering = false
666      })
667    }
668  }
669
670  private steerableTurn(): string | null {
671    return this.options.steerableTurn?.() ?? null
672  }
673
674  /** Where the session started, asked once (the first answer stands; a later /cd moves `$.session.root()`). */
675  private async folderNow(): Promise<string | null> {
676    this.folder ??= (async () => {
677      if (!this.options.root) return this.options.cwd ? await this.options.cwd().catch(() => null) : null
678      return (await this.options.root().catch(() => null)) ?? (this.options.cwd ? await this.options.cwd().catch(() => null) : null)
679    })()
680    return this.folder
681  }
682
683  /** What this process loaded (plugin and engine), asked once and remembered: it never changes while the process runs. */
684  private async loadedNow(): Promise<{ plugin: LoadedPluginInfo | null; engine: string | null }> {
685    this.loaded ??= (async () => ({
686      plugin: this.host.loadedPlugin ? await this.host.loadedPlugin().catch(() => null) : null,
687      engine: this.host.engineVersion ? await this.host.engineVersion().catch(() => null) : null,
688    }))()
689    return this.loaded
690  }
691
692  /** A main-loop model request of `turnId` is going out: the replies put into that turn are in it. */
693  onMainStep(turnId: string): void {
694    for (const entry of this.sentNow) if (entry.turnId === turnId) entry.stepped = true
695  }
696
697  /**
698   * A main-loop turn ended. A reply Send now put into it that no request
699   * carried (the turn was making its last request when the row landed) has
700   * not been read: a short turn of its own points Claude at it.
701   */
702  onMainTurnComplete(turnId: string): void {
703    const ended = this.sentNow.filter((entry) => entry.turnId === turnId)
704    this.sentNow = this.sentNow.filter((entry) => entry.turnId !== turnId)
705    if (this.disposed) return
706    for (const entry of ended) if (!entry.stepped) this.followUp(entry.command)
707  }
708
709  /** One short turn pointing Claude at a reply that went into the conversation but no request carried. */
710  private followUp(command: InboxReplyCommand): void {
711    this.host.debug(`inbox: ${command.id} landed as the turn ended; pointing Claude at it`)
712    void this.host.submit(inboxSentNowFollowUpText(command)).catch(() => undefined)
713  }
714
715  /**
716   * Whether this process polls and delivers: it holds the session's inbox
717   * lease unless another live process does and the person touched that one
718   * at least as recently.
719   */
720  private async holdLease(now: number): Promise<boolean> {
721    this.leaseCheckedAt = now
722    const lease = parseLease(await this.host.readFile(this.leasePath).catch(() => ''))
723    const foreign = !!lease?.owner && lease.owner !== this.options.instanceId && Math.abs(now - lease.at) < INBOX_LEASE_STALE_MS
724    if (foreign && lease && lease.touchedAt >= this.touchedAt) {
725      if (this.leader) this.host.debug('inbox: another Claude Code process on this session delivers replies now')
726      this.leader = false
727      return false
728    }
729    await this.host
730      .writeFile(this.leasePath, JSON.stringify({ owner: this.options.instanceId, at: now, touchedAt: this.touchedAt }))
731      .catch(() => undefined)
732    this.leader = true
733    return true
734  }
735
736  private async bridge(path: string, body: Record<string, unknown>): Promise<HttpResult | null> {
737    const registry = await this.registry()
738    if (!registry) return null
739    return this.host
740      .fetch(`http://127.0.0.1:${registry.port}${path}`, {
741        method: 'POST',
742        headers: { 'content-type': 'application/json', authorization: `Bearer ${registry.token}` },
743        body: JSON.stringify({ session: this.options.sessionId, host: INBOX_HOST, ...body }),
744      })
745      .catch(() => null)
746  }
747
748  /**
749   * The replies and messages the Inbox has for this session now (waitMs 0),
750   * or null when it did not answer. The poll says where the session works and
751   * whether a turn runs, for New message's live sessions (step 8).
752   */
753  private async pendingNow(waitMs: number): Promise<InboxReplyCommand[] | null> {
754    const cwd = this.options.cwd ? await this.options.cwd().catch(() => '') : ''
755    const loaded = await this.loadedNow()
756    const folder = await this.folderNow()
757    const response = await this.bridge(INBOX_BRIDGE_POLL_PATH, {
758      waitMs,
759      ...(cwd ? { project_path: cwd } : {}),
760      ...(this.startedAt ? { started_at: this.startedAt } : {}),
761      ...(this.busy === null ? {} : { busy: this.busy, idle_since: this.idleSince }),
762      // Send now: this engine can put a reply into a running turn (`$.session.append`).
763      ...((await this.sendNowNow()) ? { [INBOX_SEND_NOW_POLL_FIELD]: true } : {}),
764      // Tags (approval "inbox-tag-agents"): this connection words a reply it was tagged in truthfully.
765      [INBOX_TAGS_POLL_FIELD]: true,
766      // What this process loaded (additive): the Inbox says when a restart would load a newer plugin.
767      ...(loaded.plugin ? { plugin: loaded.plugin } : {}),
768      ...(loaded.engine ? { engine: loaded.engine } : {}),
769      ...(folder ? { session_folder: folder } : {}),
770    })
771    return response && response.status === 200 ? parseInboxBridgeCommands(response.text) : null
772  }
773
774  private async poll(): Promise<void> {
775    this.polling = true
776    try {
777      const commands = await this.pendingNow(INBOX_POLL_WAIT_MS)
778      if (this.disposed) return
779      if (commands === null) {
780        // No registry, a stopped Inbox, an older one without the route, a
781        // rotated token: wait and try again, longer each time, never for good.
782        this.backoffMs = this.backoffMs ? Math.min(this.backoffMs * 2, INBOX_RETRY_MS.max) : INBOX_RETRY_MS.first
783        this.retryAt = (await this.host.now()) + this.backoffMs
784        return
785      }
786      this.backoffMs = 0
787      this.retryAt = 0
788      for (const command of commands) {
789        if (this.settled.has(command.id) || this.elsewhere.has(command.id)) continue
790        const known = this.pending.get(command.id)
791        // A later poll carries `now` once the person pressed Send now: the newest command wins.
792        if (known && known.now === command.now) continue
793        this.host.debug(`inbox: ${command.type} ${command.id} for this session${command.now ? ' (send now)' : ''}`)
794        this.pending.set(command.id, command)
795      }
796    } finally {
797      this.polling = false
798    }
799  }
800
801  private settle(id: string): void {
802    this.pending.delete(id)
803    this.settled.add(id)
804    this.held.delete(id)
805  }
806
807  /**
808   * Whether a Send now reply could go in right now: the engine can, and the
809   * session is idle or runs a turn it may go into (not while this session's
810   * own Ask question holds it, running or queued). What the poll and the
811   * state events say, so the window offers Send now, and reads a pressed one
812   * as "Sending now", only then.
813   */
814  private async sendNowNow(): Promise<boolean> {
815    if (!(await this.canAppend())) return false
816    return this.steerableTurn() !== null || !this.options.isBusy()
817  }
818
819  /** Whether Send now can work here: the engine has `$.session.append`, it never refused a row, and the session tells its turns apart. */
820  private async canAppend(): Promise<boolean> {
821    if (!this.host.appendUserRow || !this.options.steerableTurn || this.steerRefused) return false
822    if (this.appendOk === null) this.appendOk = (await this.host.sessionAppendAvailable?.().catch(() => false)) ?? false
823    return this.appendOk
824  }
825
826  /**
827   * Deliver the oldest waiting reply as a turn, once; `urgent` (the person
828   * pressed Send now, the session not idle for two ticks yet): at once, into
829   * the running turn while one runs (`appendUserRow`), else as a turn.
830   */
831  private async deliverNext(urgent = false): Promise<void> {
832    const command = this.pending.values().next().value as InboxReplyCommand | undefined
833    if (!command) return
834    // Still waiting? An agent may have read it through the tool meanwhile, or
835    // another process delivered it.
836    const fresh = await this.pendingNow(0)
837    if (fresh === null) return
838    if (!fresh.some((candidate) => candidate.id === command.id)) {
839      this.settle(command.id)
840      return
841    }
842    if (this.disposed || !(await this.holdLease(await this.host.now()))) return
843    const dir = this.claimDir(command.id)
844    const claim = await this.host.run(inboxClaimArgv(dir, this.options.instanceId), { timeoutMs: 5_000 }).catch(() => null)
845    if (claim?.exitCode === INBOX_CLAIM_EXIT.lost) {
846      this.pending.delete(command.id)
847      this.elsewhere.set(command.id, { command, since: await this.host.now() })
848      return
849    }
850    if (claim?.exitCode !== INBOX_CLAIM_EXIT.won) return
851    this.submitting = command.id
852    this.held.add(command.id)
853    await this.host.writeFile(`${dir}/alive`, String(await this.host.now())).catch(() => undefined)
854    // Decided HERE, after every await above: the turn may have ended (or one started) meanwhile. Into the
855    // running turn only when the person asked, one runs that may take it, and the engine can; else as a
856    // turn when idle; else (this session's own Ask question holds it) it waits, its claim given back.
857    const turn = urgent && (await this.canAppend()) ? this.steerableTurn() : null
858    if (!turn && this.options.isBusy()) {
859      // Nothing went in: give the claim back, so the process the person works in delivers it (this one
860      // may lose the lease while the turn runs, and a claim it kept would leave the reply with nobody).
861      this.submitting = null
862      await this.release(command.id)
863      return
864    }
865    this.host.debug(`inbox: delivering ${command.type} ${command.id}${turn ? ` into the running turn ${turn}` : ''}`)
866    try {
867      if (turn) {
868        // Send now while Claude works: a user row in the running turn, read at its next model request.
869        try {
870          await this.host.appendUserRow!(inboxWakeText(command, this.options.toolName))
871        } catch (error) {
872          // Refused: nothing entered, so the claim is given back and it is delivered when the session is idle
873          // (here or in the process the person moves to), the window reads it as queued again, and Send now
874          // is no longer offered here.
875          this.submitting = null
876          await this.release(command.id)
877          this.noSteer.add(command.id)
878          this.steerRefused = true
879          void this.bridge(INBOX_BRIDGE_EVENT_PATH, { type: 'send_now_failed', id: command.id })
880          this.host.debug(`inbox: ${command.id} could not go into the running turn (${error instanceof Error ? error.message : String(error)}); it waits for idle`)
881          return
882        }
883        // The turn ended (or another began) while the row went in: no request of it will carry the row,
884        // so point Claude at it now. Otherwise the turn's next request does, or its end sends the pointer.
885        if (this.steerableTurn() === turn) this.sentNow.push({ command, turnId: turn, stepped: false })
886        else this.followUp(command)
887        await this.host
888          .appendNotice?.(`Plannotator Inbox: the person's ${command.type === 'message' ? 'message' : 'reply'} (${command.subject ?? 'a thread'}) went into this turn.`)
889          .catch(() => undefined)
890      } else {
891        // Resolves once Claude is idle and took the turn.
892        await this.host.submit(inboxWakeText(command, this.options.toolName))
893      }
894    } catch (error) {
895      this.submitting = null
896      this.settle(command.id)
897      await this.host.writeFile(`${dir}/reported`, '1').catch(() => undefined)
898      this.host.toast(
899        `${command.type === 'message' ? 'A message' : 'A reply'} in the Plannotator Inbox (${command.subject ?? 'a thread'}) could not be delivered to this session (${error instanceof Error ? error.message : String(error)}). Read it in the Inbox: ${command.url}`,
900      )
901      return
902    }
903    this.submitting = null
904    await this.host.writeFile(`${dir}/delivered`, String(await this.host.now())).catch(() => undefined)
905    this.settle(command.id)
906    this.unacked.add(command.id)
907    await this.acknowledge(command.id)
908  }
909
910  /** Give back a claim nothing was submitted under; it stays pending here, for a later claim. */
911  private async release(id: string): Promise<void> {
912    this.held.delete(id)
913    await this.aliveRefresh
914    await this.host.run(inboxReleaseArgv(this.claimDir(id), this.options.instanceId), { timeoutMs: 5_000 }).catch(() => null)
915  }
916
917  /** Tell the Inbox a reply was delivered (retried every tick until it answers). */
918  private async acknowledge(id: string): Promise<void> {
919    const response = await this.bridge(INBOX_BRIDGE_EVENT_PATH, { type: 'delivered', id })
920    if (!response) return
921    // 200, or a refusal that will not change (the reply is gone or not ours): done.
922    if (response.status === 200 || (response.status >= 400 && response.status < 500 && response.status !== 401)) this.unacked.delete(id)
923  }
924
925  /**
926   * A reply another process claimed: acknowledged on its behalf once it says
927   * delivered (its own acknowledgement may have been lost), and reported once,
928   * with a toast, when its claimant stopped saying it is alive before it did.
929   */
930  private async watchElsewhere(id: string, now: number): Promise<void> {
931    const entry = this.elsewhere.get(id)
932    if (!entry) return
933    const dir = this.claimDir(id)
934    if (!(await this.host.exists(dir))) {
935      // Its claimant gave it back without delivering it (`release`): it is pending here again.
936      this.elsewhere.delete(id)
937      if (!this.settled.has(id)) this.pending.set(id, entry.command)
938      return
939    }
940    if (await this.host.exists(`${dir}/delivered`)) {
941      this.elsewhere.delete(id)
942      this.settled.add(id)
943      this.unacked.add(id)
944      return
945    }
946    if (await this.host.exists(`${dir}/reported`)) {
947      this.elsewhere.delete(id)
948      this.settled.add(id)
949      return
950    }
951    const alive = Number((await this.host.readFile(`${dir}/alive`).catch(() => '')).trim())
952    const last = Number.isFinite(alive) && alive > 0 ? alive : entry.since
953    if (now - last < INBOX_UNDELIVERED_AFTER_MS || !this.leader) return
954    this.elsewhere.delete(id)
955    this.settled.add(id)
956    await this.host.writeFile(`${dir}/reported`, '1').catch(() => undefined)
957    this.host.toast(
958      `${entry.command.type === 'message' ? 'A message' : 'A reply'} in the Plannotator Inbox (${entry.command.subject ?? 'a thread'}) arrived for this session but was not delivered (the Claude Code process that took it quit). Read it in the Inbox: ${entry.command.url}`,
959    )
960  }
961}
962
hooks/mod/inbox-contract.ts 860 lines
1/**
2 * The Plannotator Inbox connection contract, a byte-for-byte copy of the
3 * CONTRACT section of packages/shared/inbox/connection.ts (a hooks module may
4 * import only its own folder). `inbox-contract.test.ts` fails when the two
5 * differ: edit the shared file, then paste.
6 */
7
8// --- CONTRACT (copied byte for byte into apps/hook/hooks/mod/inbox-contract.ts; edit packages/shared/inbox/connection.ts, then paste) ---
9
10/** The agent tool every connection registers. */
11export const INBOX_TOOL_NAME = 'plannotator_inbox'
12
13/**
14 * The Inbox MCP tools the agent tool may carry, in the order it lists them.
15 * Only those the running Inbox offers become actions; an Inbox without one
16 * (an older binary) simply has no such action.
17 */
18export const INBOX_TOOL_ACTIONS = [
19  'send_message',
20  'read_thread',
21  'search',
22  'wait_for_reply',
23  'resolve_message',
24  'submit_guide',
25  'get_guide_brief',
26  'card',
27] as const
28
29export type InboxToolAction = (typeof INBOX_TOOL_ACTIONS)[number]
30
31/**
32 * Arguments the connection fills itself, on the Inbox tools that take them:
33 * the session's working folder, the host's real session id, and who the
34 * person sees. They never appear in the agent's schema, except
35 * `project_path` (INBOX_AGENT_PROJECT_PATH).
36 */
37export const INBOX_FILLED_ARGUMENTS = ['project_path', 'agent_session', 'agent_host', 'agent_name'] as const
38
39export type InboxFilledArguments = Record<(typeof INBOX_FILLED_ARGUMENTS)[number], string>
40
41/**
42 * The one filled argument an agent may set itself: the repository or folder
43 * a call is about, when it is not the session's working folder (a session
44 * started in a notes subfolder). Optional in the agent's schema; absent, the
45 * working folder is filled as before. The connection resolves a relative path
46 * against the working folder and refuses a path that is not an existing
47 * folder before anything reaches the Inbox.
48 */
49export const INBOX_AGENT_PROJECT_PATH = 'project_path'
50
51export const INBOX_AGENT_PROJECT_PATH_DESCRIPTION = 'The repository or folder this is about; defaults to your working folder.'
52
53/** Why an agent's `project_path` is refused before any folder is looked at, or null when its shape passes. */
54export function inboxProjectPathShapeRefusal(value: unknown): string | null {
55  if (typeof value !== 'string' || value.trim() === '') return 'project_path: a folder path (absolute, or relative to your working folder).'
56  if (/[\u0000-\u001f\u007f]/.test(value)) return 'project_path: no control characters or line breaks.'
57  if (value.length > 4096) return 'project_path: at most 4096 characters.'
58  return null
59}
60
61/**
62 * The `_meta` key a connection sets to `true` on its `tools/call` when the
63 * person's reply reaches this session as a turn by itself (the session's wake
64 * runs). The send tools then say to end the turn instead of waiting with
65 * wait_for_reply. Without it (the stdio shim, a raw MCP client, OpenCode 1,
66 * an older connection) they keep the wait_for_reply advice. An older Inbox
67 * ignores it.
68 */
69export const INBOX_WAKES_META_KEY = 'ai.plannotator/inbox-wakes'
70
71/** The `tools/call` params for an Inbox tool call: `wakes` when this session's replies arrive as turns. */
72export function inboxToolCallParams(call: { name: string; arguments: Record<string, unknown> }, options: { wakes: boolean }): Record<string, unknown> {
73  return { name: call.name, arguments: call.arguments, ...(options.wakes ? { _meta: { [INBOX_WAKES_META_KEY]: true } } : {}) }
74}
75
76/** The bridge routes on the Inbox server (bearer token, loopback Host, no Origin). */
77export const INBOX_BRIDGE_POLL_PATH = '/api/inbox/bridge/poll'
78export const INBOX_BRIDGE_EVENT_PATH = '/api/inbox/bridge/event'
79/** The longest the server holds a poll open. */
80export const INBOX_BRIDGE_POLL_MAX_MS = 25_000
81
82/** One tool as the Inbox's `tools/list` describes it. */
83export interface InboxToolInfo {
84  name: string
85  description: string
86  inputSchema: Record<string, unknown>
87}
88
89/** The tools in a `tools/list` result that the agent tool can carry, in INBOX_TOOL_ACTIONS order. */
90export function parseInboxToolList(result: unknown): InboxToolInfo[] {
91  const listed = result && typeof result === 'object' ? (result as { tools?: unknown }).tools : undefined
92  if (!Array.isArray(listed)) return []
93  const byName = new Map<string, InboxToolInfo>()
94  for (const item of listed) {
95    if (!item || typeof item !== 'object') continue
96    const tool = item as { name?: unknown; description?: unknown; inputSchema?: unknown }
97    if (typeof tool.name !== 'string' || !(INBOX_TOOL_ACTIONS as readonly string[]).includes(tool.name)) continue
98    const schema = tool.inputSchema && typeof tool.inputSchema === 'object' ? (tool.inputSchema as Record<string, unknown>) : { type: 'object' }
99    byName.set(tool.name, { name: tool.name, description: typeof tool.description === 'string' ? tool.description : '', inputSchema: schema })
100  }
101  return INBOX_TOOL_ACTIONS.flatMap((name) => {
102    const tool = byName.get(name)
103    return tool ? [tool] : []
104  })
105}
106
107function propertiesOf(tool: InboxToolInfo): Record<string, Record<string, unknown>> {
108  const properties = tool.inputSchema.properties
109  return properties && typeof properties === 'object' ? (properties as Record<string, Record<string, unknown>>) : {}
110}
111
112function isFilled(name: string): boolean {
113  return (INBOX_FILLED_ARGUMENTS as readonly string[]).includes(name)
114}
115
116/** The first sentence of a description (up to the first ". " or line break). */
117function leadOf(description: string): string {
118  const line = description.split('\n', 1)[0] ?? ''
119  const stop = line.search(/\.\s/)
120  return (stop >= 0 ? line.slice(0, stop + 1) : line).trim()
121}
122
123/** What the agent tool says, before the per-action lines. Fixed text. */
124export const INBOX_TOOL_LEAD =
125  "The Plannotator Inbox on this machine: message the person and get their answer later, without holding this session open. Use it when the person may not be watching this chat: a decision only they can make (ask it as a :::question block, then go on with other work), finished long work to hand over (a short summary, files in `attachments`), or when they ask you to. Ask in the chat when they are there; never send routine progress. If another agent started you, report to it instead. Set `action` to a tool below and pass its fields; the project and this session are filled in."
126
127/**
128 * Fixed text: how a reply comes back. The connection delivers the person's
129 * reply to a message this session sent as a new turn once the session is idle.
130 * Host-neutral: Claude Code frames the turn as the plugin's message, Pi and
131 * OpenCode 2 as a user message, and all three carry the wake's first line.
132 */
133export const INBOX_TOOL_WAKE_NOTE =
134  "When the person replies to a message you sent, their reply arrives in this session by itself once it is idle, as a message headed `Plannotator Inbox: <subject> (<reply id>)`: end your turn, or go on with other work; do not call wait_for_reply. When they need to hear back, answer with send_message reply_to."
135
136/**
137 * Fixed text, the description's last line: where everything the tool's short
138 * field descriptions leave out lives (the full question guide, every field,
139 * examples), so an agent that needs more reads it once instead of every
140 * request carrying it.
141 */
142export const INBOX_TOOL_HELP_NOTE = "Every field and the full question syntax: `plannotator inbox --help`."
143
144/**
145 * The agent tool's own line for an action whose Inbox lead is long (the
146 * description must stay under Claude Code's 2,048 characters, and every Pi and
147 * OpenCode request carries it).
148 */
149export const INBOX_AGENT_ACTION_LEADS: Readonly<Record<string, string>> = {
150  read_thread: 'Read a thread (thread_id): open questions, the newest messages, earlier ones one line each; or list yours.',
151  search: 'Find messages by words (read-only).',
152  get_guide_brief: "Get Plannotator's method, the guide's JSON shape and the rules for writing a guided review, with a worked submit_guide call.",
153  card: "A Board card for work that outlasts this reply: create it, then move it and say where it is as the work moves.",
154}
155
156/**
157 * The agent tool's own words for the fields whose Inbox description is long
158 * (the MCP server's are written for a raw MCP client, which has no other
159 * guide): every Pi and OpenCode request carries the tool whole, so these keep
160 * only what an agent needs to call it well, and `plannotator inbox --help`
161 * keeps the rest. Keyed by action, then field: applied only to a field that
162 * action of the running Inbox offers (a field several actions share is
163 * described once, from the first action that has it, `send_message` for `body`).
164 */
165export const INBOX_AGENT_FIELD_DESCRIPTIONS: Readonly<Record<string, Readonly<Record<string, string>>>> = {
166  send_message: {
167    body: [
168      'The message, markdown. Ask what only the person can decide as a question block, which renders as an answerable card:',
169      '',
170      ':::question',
171      'Where should the edit that loses a sync conflict go?',
172      '',
173      'Context in one to three plain sentences: what it affects, what you know, why you recommend one. The person switches in cold.',
174      '',
175      '- [ ] Local only, purged after 30 days — cheap',
176      '- [ ] Server-side per user — needs a retention policy',
177      '',
178      'Recommended: Local only, purged after 30 days',
179      'Holds up: sync release',
180      ':::',
181      '',
182      '`:::question-multi` takes several choices, `:::question-text` free text. The person can always answer Other, add a note or skip, so never add an Other choice yourself. `Stopped: <why>` only when you cannot go on until it is answered (never `Stopped: no`); `Holds up: <work>` names work that waits while you go on. Ask only what you cannot decide alone, about 8 a round at most. Answers come back in the reply under "Answers to your questions".',
183      '',
184      'Optional lines after the question; most questions need none of these: `Stakes: <what it affects>` (give one with every Stopped or Holds up), `Shows: ![alt](path)` or `Shows: [name](file)` (the one picture or file it is about), `Why: <why your recommendation>` on its own line, `Reversible: no — <why>` only when it cannot be undone. Visual options can be picture choices, `- [ ] Label — ![alt](path)`: the picture picks it, the label comes back.',
185      '',
186      'Only for a true blocker the person must go and do outside this chat, that you cannot do yourself (approve a deploy, sign in, touch a security key, merge a PR you cannot merge), write a `:::action` block: first line the order, then why; optional `Where: <url>`, `Run: <command>`, `Stopped:`, `Watching: <what you watch>`. Never for a decision or a question, for what you can do yourself, or as a checklist or status update; most messages need none. Done or Can\'t do it comes back under "Action items you asked for".',
187    ].join('\n'),
188    thread: "A short thread name, one line, to keep separate work apart: the same name in this project is the same open thread, across sessions. Without it, your messages join your session's open thread. Ignored with reply_to, except when you are asked to name a thread the person started: then it names that thread, once.",
189    supersedes: 'Your own questions in this thread that are still open (read_thread state open or picked) and no longer apply: a newer message replaces them, or the reply settled them in words. "<message id>/<key>" for one, "<message id>" for all of that message\'s; send with reply_to into their thread. With one question in this message it replaces them, otherwise they read "No longer applies".',
190    done: 'Your own open action items (`:::action`) in this thread that you saw done yourself, e.g. the deploy you watch is Ready: "<message id>/<key>" (key a-…); send with reply_to into their thread. The card says you saw it done; nothing is sent to the person.',
191    attachments: 'Files to show the person beside the message, absolute or relative to project_path: a plan, a screenshot, an HTML mock, code, a video, any file. For something visual, a screenshot or image usually reads fastest; attach the HTML or source too when they should open or click through it. Link one from the body (`[the mock](mock.html)`) to open it beside the thread. Their comments on the files come back in the reply. Folders and .env files are refused.',
192  },
193  submit_guide: {
194    guide: "The guide in get_guide_brief's output_schema, as an object or its JSON.",
195    snapshot: 'Instead of guide and patch: a complete Plannotator guide snapshot, as an object or its JSON.',
196  },
197}
198
199/**
200 * The one-line reminder a session that has `plannotator_inbox` gets once, at
201 * its start (the Claude Code mod's `prompt.context` block, Pi's hidden
202 * before_agent_start message, OpenCode's fixed system line), when the
203 * `inboxReminder` switch allows it. Fixed text: it sits in the cached prompt
204 * prefix and must never change within a session. For hosts with the wake
205 * (the reply comes back as a turn).
206 */
207export const INBOX_REMINDER_TEXT =
208  "Plannotator Inbox is on: when you finish long work, or need a decision the person isn't here to give, send it with plannotator_inbox send_message and keep going. Their reply comes back here. Run `plannotator inbox --help` for how it works."
209
210/**
211 * The same line for a host without the wake (OpenCode 1): the reply does not
212 * come back by itself there, so it names wait_for_reply instead.
213 */
214export const INBOX_REMINDER_TEXT_NO_WAKE =
215  "Plannotator Inbox is on: when you finish long work, or need a decision the person isn't here to give, send it with plannotator_inbox send_message and keep going. Call wait_for_reply when you need their answer. Run `plannotator inbox --help` for how it works."
216
217/**
218 * The reminder naming the tool as the host registered it. Claude Code defers
219 * plugin tools behind tool search and names them `mcp__<server>__plannotator_inbox`,
220 * so the line carries that full name for the search to find; other hosts use
221 * the plain name. Fixed per process: the name never changes under a session.
222 */
223export function inboxReminderText(toolName: string = INBOX_TOOL_NAME, options: { wakes?: boolean } = {}): string {
224  const text = options.wakes === false ? INBOX_REMINDER_TEXT_NO_WAKE : INBOX_REMINDER_TEXT
225  return text.replace(INBOX_TOOL_NAME, toolName)
226}
227
228/**
229 * The most characters (UTF-16 code units, a string's `length`) a custom Inbox
230 * reminder may hold. Longer text is refused when saved and ignored when read,
231 * so the host falls back to the next text in line (the shared one, then the
232 * default).
233 */
234export const INBOX_REMINDER_MAX_CHARS = 4128
235
236/**
237 * The person's own reminder for a host, from config.json
238 * (`prompts.inbox.runtimes.<host>.reminder`, which wins, then the shared
239 * `prompts.inbox.reminder`), or null when neither holds usable text: a
240 * string with something besides whitespace, at most INBOX_REMINDER_MAX_CHARS
241 * long. Takes the parsed config.json object (anything else reads as unset).
242 */
243export function inboxReminderCustomText(config: unknown, host: string): string | null {
244  const record = (value: unknown): Record<string, unknown> | null =>
245    value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, unknown>) : null
246  const usable = (value: unknown): string | null =>
247    typeof value === 'string' && value.trim() !== '' && value.length <= INBOX_REMINDER_MAX_CHARS ? value : null
248  const inbox = record(record(record(config)?.prompts)?.inbox)
249  if (!inbox) return null
250  return usable(record(record(inbox.runtimes)?.[host])?.reminder) ?? usable(inbox.reminder)
251}
252
253/**
254 * The reminder a host sends: the person's own text when there is one (it
255 * REPLACES the line, for hosts with the wake and without it alike, every
256 * whole word `plannotator_inbox` in it renamed to the tool as the host
257 * registered it), else exactly `inboxReminderText(toolName, options)`.
258 */
259export function inboxReminderFor(custom: string | null | undefined, toolName: string = INBOX_TOOL_NAME, options: { wakes?: boolean } = {}): string {
260  if (typeof custom !== 'string' || custom.trim() === '') return inboxReminderText(toolName, options)
261  return custom.replace(/(^|[^A-Za-z0-9_])plannotator_inbox(?![A-Za-z0-9_])/g, (_match: string, before: string) => before + toolName)
262}
263
264/**
265 * The agent tool: name, description and input schema, built from the Inbox's
266 * own tools. Null when it offers none. `wakes: false` for a host that cannot
267 * deliver a reply as a turn (OpenCode 1): the description then says nothing
268 * about replies arriving by themselves.
269 */
270export function inboxAgentTool(
271  tools: readonly InboxToolInfo[],
272  options: { wakes?: boolean } = {},
273): { name: string; description: string; inputSchema: Record<string, unknown> } | null {
274  if (tools.length === 0) return null
275  const description = [
276    INBOX_TOOL_LEAD,
277    '',
278    ...tools.map((tool) => `- ${tool.name}: ${INBOX_AGENT_ACTION_LEADS[tool.name] ?? leadOf(tool.description)}`),
279    ...(options.wakes === false ? [] : ['', INBOX_TOOL_WAKE_NOTE]),
280    '',
281    INBOX_TOOL_HELP_NOTE,
282  ].join('\n')
283  const properties: Record<string, Record<string, unknown>> = {
284    action: { type: 'string', enum: tools.map((tool) => tool.name), description: 'Which Inbox tool to call.' },
285  }
286  const usedBy = new Map<string, string[]>()
287  for (const tool of tools) {
288    for (const [name, schema] of Object.entries(propertiesOf(tool))) {
289      if ((isFilled(name) && name !== INBOX_AGENT_PROJECT_PATH) || name === 'action') continue
290      const users = usedBy.get(name)
291      if (users) {
292        users.push(tool.name)
293        continue
294      }
295      usedBy.set(name, [tool.name])
296      if (name === INBOX_AGENT_PROJECT_PATH) {
297        // Optional, and described for the agent: the Inbox's own text is about the fill.
298        properties[name] = { type: 'string', description: INBOX_AGENT_PROJECT_PATH_DESCRIPTION }
299        continue
300      }
301      // The agent tool's own short words where the Inbox's are long; the rest is the Inbox's.
302      const own = INBOX_AGENT_FIELD_DESCRIPTIONS[tool.name]?.[name]
303      properties[name] = { ...schema, description: (own ?? (typeof schema.description === 'string' ? schema.description : '')).trim() }
304    }
305  }
306  for (const [name, users] of usedBy) {
307    const schema = properties[name]!
308    properties[name] = { ...schema, description: `(${users.join(', ')}) ${schema.description}`.trim() }
309  }
310  return { name: INBOX_TOOL_NAME, description, inputSchema: { type: 'object', properties, required: ['action'], additionalProperties: false } }
311}
312
313/**
314 * The Inbox tool call an agent tool call stands for: the action's own fields
315 * (any other field is refused, naming the action's fields) plus the filled
316 * arguments that tool takes. An agent's own `project_path` (shape-checked
317 * here) comes back as `projectPath`, with the working folder still in
318 * `arguments`: the connection resolves it against that folder, refuses a
319 * path that is not an existing folder, and puts the result in
320 * `arguments.project_path` before calling the Inbox.
321 */
322export function inboxToolCall(
323  input: unknown,
324  tools: readonly InboxToolInfo[],
325  filled: InboxFilledArguments,
326): { name: string; arguments: Record<string, unknown>; projectPath?: string } | { error: string } {
327  if (!input || typeof input !== 'object' || Array.isArray(input)) return { error: 'Invalid plannotator_inbox call: expected an object with an action.' }
328  const { action, ...rest } = input as Record<string, unknown>
329  const tool = tools.find((candidate) => candidate.name === action)
330  if (!tool) {
331    return {
332      error: `Invalid plannotator_inbox call: action must be one of ${tools.map((candidate) => candidate.name).join(', ')}${typeof action === 'string' && (INBOX_TOOL_ACTIONS as readonly string[]).includes(action) ? ` (this Plannotator Inbox has no ${action}; update Plannotator for it)` : ''}.`,
333    }
334  }
335  const own = propertiesOf(tool)
336  const args: Record<string, unknown> = {}
337  let projectPath: string | undefined
338  for (const [name, value] of Object.entries(rest)) {
339    if (value === undefined) continue
340    if (name === INBOX_AGENT_PROJECT_PATH && name in own) {
341      const refusal = inboxProjectPathShapeRefusal(value)
342      if (refusal) return { error: `Invalid plannotator_inbox call: ${refusal}` }
343      projectPath = value as string
344      continue
345    }
346    if (!(name in own) || isFilled(name)) {
347      const fields = Object.keys(own).filter((field) => !isFilled(field) || field === INBOX_AGENT_PROJECT_PATH)
348      return { error: `Invalid plannotator_inbox call: ${tool.name} takes no "${name}" (its fields: ${fields.join(', ') || 'none'}).` }
349    }
350    args[name] = value
351  }
352  for (const name of INBOX_FILLED_ARGUMENTS) if (name in own) args[name] = filled[name]
353  return projectPath === undefined ? { name: tool.name, arguments: args } : { name: tool.name, arguments: args, projectPath }
354}
355
356/**
357 * The `_meta` key an Inbox sets to `true` on a tool result whose text already
358 * says everything its structured content holds (read_thread, search,
359 * wait_for_reply): a compact transcript the model reads instead of JSON. A
360 * connection then hands the model the text alone. An older connection does
361 * not know the key and appends the structured content as before, which the
362 * Inbox keeps to the same trimmed shape.
363 */
364export const INBOX_TEXT_COMPLETE_META_KEY = 'ai.plannotator/text-complete'
365
366/**
367 * An MCP `tools/call` result as the text the agent tool answers with: the
368 * text, then any structured content as compact JSON (no indentation: it can
369 * be most of the bytes the model reads), unless the Inbox marked the text
370 * complete (INBOX_TEXT_COMPLETE_META_KEY).
371 */
372export function inboxToolResultText(result: unknown): { text: string; isError: boolean } {
373  const value = result && typeof result === 'object' ? (result as { content?: unknown; structuredContent?: unknown; isError?: unknown; _meta?: unknown }) : {}
374  const text = Array.isArray(value.content)
375    ? value.content
376        .map((part) => (part && typeof part === 'object' && typeof (part as { text?: unknown }).text === 'string' ? (part as { text: string }).text : ''))
377        .filter(Boolean)
378        .join('\n')
379    : ''
380  const meta = value._meta && typeof value._meta === 'object' ? (value._meta as Record<string, unknown>) : {}
381  const complete = meta[INBOX_TEXT_COMPLETE_META_KEY] === true
382  const structured = !complete && value.structuredContent && typeof value.structuredContent === 'object' ? `\n\n${JSON.stringify(value.structuredContent)}` : ''
383  return { text: `${text}${value.isError === true ? '' : structured}`.trim(), isError: value.isError === true }
384}
385
386/** The JSON-RPC message in an MCP answer: a JSON body, or the `data:` lines of an SSE body. */
387export function mcpAnswerOf(text: string): { result?: unknown; error?: { message?: string } } | null {
388  const candidates = /^\s*(event:|data:|:)/m.test(text)
389    ? text
390        .split(/\r?\n\r?\n/)
391        .map((block) =>
392          block
393            .split(/\r?\n/)
394            .filter((line) => line.startsWith('data:'))
395            .map((line) => line.slice(5).replace(/^ /, ''))
396            .join('\n'),
397        )
398        .filter((data) => data.trim())
399    : [text]
400  for (const candidate of candidates) {
401    try {
402      const value = JSON.parse(candidate) as { result?: unknown; error?: { message?: string } }
403      if (value && typeof value === 'object' && ('result' in value || 'error' in value)) return value
404    } catch {
405      // The next block.
406    }
407  }
408  return null
409}
410
411/**
412 * The one bound on a request body the Inbox reads, `/mcp` included: Bun's own
413 * default for `Bun.serve`, made explicit, and handed to the MCP SDK, whose
414 * default (4 MiB) refused ordinary large messages. A body is read whole and
415 * parsed in memory, so the long-lived Inbox that holds every thread keeps a
416 * bound; under it a message works, over it the request is refused at once
417 * with {@link inboxRequestTooLargeMessage}, never left to time out.
418 */
419export const INBOX_MAX_REQUEST_BYTES = 128 * 1024 * 1024
420
421/** The refusal for a request over {@link INBOX_MAX_REQUEST_BYTES}, naming the bound. */
422export function inboxRequestTooLargeMessage(bytes?: number): string {
423  const size = bytes === undefined ? '' : ` (${bytes} bytes)`
424  return `The message is too large for the Plannotator Inbox${size}: one request may carry at most ${INBOX_MAX_REQUEST_BYTES} bytes (128 MiB). Send a smaller message, or attach the content as a file.`
425}
426
427/** {@link mcpAnswerOf} with the HTTP status: an unreadable 413 (the server's own refusal, no body) is the request bound. */
428export function mcpAnswerOfResponse(status: number, text: string): { result?: unknown; error?: { message?: string } } | null {
429  return mcpAnswerOf(text) ?? (status === 413 ? { error: { message: inboxRequestTooLargeMessage() } } : null)
430}
431
432/** The registry fields a connection reads (`inbox/inbox.json`), re-read on every call. */
433export interface InboxRegistryView {
434  pid: number
435  port: number
436  token: string
437  serverSession: string
438  url: string
439}
440
441export function parseInboxRegistry(text: string | null | undefined): InboxRegistryView | null {
442  if (!text) return null
443  try {
444    const value = JSON.parse(text) as Record<string, unknown>
445    if (
446      value.v === 1 &&
447      typeof value.pid === 'number' &&
448      typeof value.port === 'number' &&
449      Number.isInteger(value.port) &&
450      value.port > 0 &&
451      value.port < 65536 &&
452      typeof value.token === 'string' &&
453      value.token.length >= 32 &&
454      typeof value.serverSession === 'string' &&
455      typeof value.url === 'string'
456    ) {
457      return { pid: value.pid, port: value.port, token: value.token, serverSession: value.serverSession, url: value.url }
458    }
459  } catch {
460    // Unreadable: the same as none.
461  }
462  return null
463}
464
465/**
466 * One thing the person sent the polling session: a `reply` to a message it
467 * sent, or a `message` the person wrote to it with New message (plan step 8),
468 * which answers nothing (`reply_to` null). Both are delivered the same way.
469 */
470export interface InboxReplyCommand {
471  type: 'reply' | 'message'
472  /** The person's reply or message (a `msg_` id). */
473  id: string
474  thread_id: string
475  /** The agent message a reply answers; null for a message. */
476  reply_to: string | null
477  /** The thread's subject. */
478  subject: string | null
479  /** The reply or message, markdown, verbatim. */
480  body: string
481  /** The thread in the Inbox page. */
482  url: string
483  /**
484   * On a reply the person sent to this session because the session that
485   * asked had ended (they picked this one at Send): the asking agent's name,
486   * e.g. `Claude Code`. Absent on every other reply and message.
487   */
488  redirected_from?: string | null
489  /**
490   * On a `message` that starts a new thread the person wrote (compose): the
491   * wake takes INBOX_NEW_THREAD_INSTRUCTION instead of the New message line.
492   * An older connection ignores it and words it as a New message, which is
493   * still true. Absent on every other command.
494   */
495  new_thread?: boolean
496  /**
497   * On words the person added to a thread they started, handed to a session
498   * that has seen nothing of that thread (the person moved them to another
499   * session): the wake says to read the thread first (`inboxContinuesLine`).
500   * Absent on every other command.
501   */
502  continues_thread?: boolean
503  /**
504   * In a thread the person started that has no name yet, on a command handed
505   * to a session that may name it (`InboxStore.canNameThread`: the session it
506   * is addressed to): the wake adds INBOX_NAME_THREAD_LINE. Absent once a name
507   * is set (by the person in compose, or by an agent) and on every other
508   * command; an older connection ignores it.
509   */
510  name_thread?: boolean
511  /**
512   * The person pressed Send now in the Inbox: deliver it at once, into the
513   * running turn when one runs (Claude Code: `$.session.append`; Pi: a
514   * steer; OpenCode 2: `delivery: "steer"`), instead of waiting for the
515   * session to go idle. Only handed to a connection whose poll said it can
516   * (`INBOX_SEND_NOW_POLL_FIELD`). Absent on every other command.
517   */
518  now?: boolean
519  /**
520   * On the person's 👍 Looks good, delivered once its Undo window passed
521   * (amended 2026-10-16: it reaches the agent): the agent message they
522   * marked. The wake is `inboxAckLine` instead of a reply's instruction and
523   * words. The command stays a `reply`, so an older connection still
524   * delivers it, with its body (the same line) as the person's words.
525   * Absent on every other command.
526   */
527  ack_of?: string
528  /**
529   * On a reply handed to a session the person tagged with `@` that does not
530   * own the thread (approval "inbox-tag-agents"): the owning session's agent,
531   * named from its host (`Claude Code`). The wake takes
532   * INBOX_TAGGED_INSTRUCTION and `inboxTaggedLine` instead of the reply's
533   * instruction: it reads the thread first and answers only what is addressed
534   * to it. Only handed to a connection whose poll said it understands tags
535   * (`INBOX_TAGS_POLL_FIELD`), so an older one never words it as a reply to
536   * it. Absent on every other command.
537   */
538  tagged?: { owner: string }
539  /**
540   * On a reply that tags other sessions, handed to its owner: those sessions'
541   * agents, named from their hosts. The wake adds `inboxAlsoTaggedLine`. An
542   * older connection ignores it, and its wake ("the person replied to you")
543   * stays true. Absent on every other command.
544   */
545  also_tagged?: string[]
546  /**
547   * On the person's Re-ask note (approval "inbox-reask"): they asked the
548   * session to ask its open questions in the thread again, together in one
549   * message. The wake takes INBOX_REASK_INSTRUCTION instead of the reply's
550   * line ("it is their answer to you" would not be true); the body lists the
551   * questions and what to do. The command stays a `reply`, so an older
552   * connection still delivers it, with the reply's line. Absent on every
553   * other command.
554   */
555  reask?: boolean
556  /**
557   * On a Re-ask note that lists action items (#2059): `actions` when it lists
558   * only action items, `both` when questions too. The wake then names what
559   * the note lists (`inboxReaskInstruction`). Absent when it lists only
560   * questions, so that wake stays INBOX_REASK_INSTRUCTION byte for byte; an
561   * older connection ignores it and words every Re-ask as questions.
562   */
563  reask_items?: 'actions' | 'both'
564  /**
565   * On a Re-ask note that lists exactly one question or action item (owner,
566   * 2026-10-23: Re-ask shows for one question too): the wake words it in the
567   * singular (`inboxReaskInstruction`). Absent when the note lists more, so
568   * those wakes stay as they were; an older connection ignores it and words
569   * the wake in the plural, while the body still names the one question.
570   */
571  reask_one?: boolean
572}
573
574/**
575 * The poll field (`true`) by which a connection says it understands a reply
576 * it was tagged in (`tagged` on a command): only such a session can be tagged,
577 * and only it is handed what it was tagged in. An older connection never sends
578 * it; the window then says to update Plannotator to tag that session.
579 */
580export const INBOX_TAGS_POLL_FIELD = 'tags'
581
582/**
583 * The fixed second line of the wake of a session the person tagged in a
584 * thread another session owns: not a reply to anything it asked.
585 */
586export const INBOX_TAGGED_INSTRUCTION =
587  "The person tagged you in a Plannotator Inbox thread that another session owns. Their reply follows as they wrote it; parts of it may be meant for the other session, not for you."
588
589/**
590 * The line under INBOX_TAGGED_INSTRUCTION: whose thread it is, read it first,
591 * and answer only your part, in the thread.
592 */
593export function inboxTaggedLine(owner: string, id: string): string {
594  return `The thread belongs to another session (${owner}); you have not seen it. Read it first with read_thread (message_id ${id}). Answer only what is addressed to you, in the same thread: plannotator_inbox send_message with reply_to ${id}.`
595}
596
597/** The line under the instruction on the owner's wake of a reply that tags other sessions. */
598export function inboxAlsoTaggedLine(names: readonly string[]): string {
599  const list = names.length <= 1 ? (names[0] ?? 'another session') : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`
600  return `This reply also tags ${list} (other sessions); each gets it too. Leave what is addressed to them to them.`
601}
602
603/**
604 * The only agent names a wake line may carry about ANOTHER agent (the owner
605 * a tagged session is told about, the sessions also tagged, the session that
606 * asked a redirected reply): the hosts' own names. An agent chooses its own
607 * host string, and these lines go into another session's prompt, so any
608 * other value reads as "another agent" (`agent` in the redirected line).
609 */
610export const INBOX_WAKE_AGENT_NAMES: readonly string[] = ['Claude Code', 'Pi', 'OpenCode', 'Codex', 'Cursor']
611
612/** An agent name a wake line carries: one of INBOX_WAKE_AGENT_NAMES (spacing folded), else '' (the caller says "another agent"). */
613function wakeName(value: unknown): string {
614  if (typeof value !== 'string') return ''
615  const name = value.replace(/[\u0000-\u001f\u007f-\u009f\s]+/g, ' ').trim()
616  return INBOX_WAKE_AGENT_NAMES.includes(name) ? name : ''
617}
618
619/**
620 * The poll field (`true`) by which a connection says it can deliver a reply
621 * into a running turn: the window offers Send now only for such a session.
622 * An older Inbox ignores it; an older connection never sends it, so it is
623 * never offered there.
624 */
625export const INBOX_SEND_NOW_POLL_FIELD = 'send_now'
626
627/**
628 * The turn a connection submits when a reply it put into a running turn
629 * arrived as that turn ended, so the model never read it: the reply is in
630 * the conversation already, so this only points at it.
631 */
632export function inboxSentNowFollowUpText(command: Pick<InboxReplyCommand, 'id' | 'subject' | 'type'>): string {
633  const subject = (command.subject ?? '').replace(/\s+/g, ' ').trim() || (command.type === 'message' ? 'a message' : 'a reply')
634  return `Plannotator Inbox: ${subject} (${command.id})\nThe person's ${command.type === 'message' ? 'message' : 'reply'} above (${command.id}) arrived as your last turn was ending. If you have not answered it yet, answer it now.`
635}
636
637export function parseInboxBridgeCommands(text: string): InboxReplyCommand[] {
638  try {
639    const body = JSON.parse(text) as { commands?: unknown }
640    if (!Array.isArray(body.commands)) return []
641    return body.commands.filter((command): command is InboxReplyCommand => {
642      if (!command || typeof command !== 'object') return false
643      const c = command as Record<string, unknown>
644      return (c.type === 'reply' || c.type === 'message') && typeof c.id === 'string' && typeof c.thread_id === 'string' && typeof c.body === 'string'
645    })
646  } catch {
647    return []
648  }
649}
650
651/** The fixed second line of every wake: who is speaking, and how to answer. */
652export const INBOX_WAKE_INSTRUCTION =
653  "The person replied to you in the Plannotator Inbox. Their reply follows as they wrote it: it is their answer to you. When they need to hear back, answer in the same thread: plannotator_inbox send_message with reply_to set to the id in parentheses on the line above."
654
655/**
656 * The fixed second line of a Re-ask wake (approval "inbox-reask"): the person
657 * asked for the open questions again, in one message, and how to answer.
658 */
659export const INBOX_REASK_INSTRUCTION =
660  "The person asked, from the Plannotator Inbox, for the open questions in this thread to be asked again, together in one new message. The questions and what to do with each follow. Answer in the same thread: plannotator_inbox send_message with reply_to set to the id in parentheses on the line above."
661
662/** What a Re-ask note lists: only questions (absent), only action items, or both (#2059). */
663export type InboxReaskItems = 'actions' | 'both' | undefined
664
665const reaskWords = (items: InboxReaskItems): { what: string; they: string } =>
666  items === 'actions'
667    ? { what: 'open action items', they: 'The action items' }
668    : items === 'both'
669      ? { what: 'open questions and action items', they: 'They' }
670      : { what: 'open questions', they: 'The questions' }
671
672/** What a Re-ask note's ids (`<message id>/<key>`; an action item's key starts with a-) list. */
673export function inboxReaskItemsOf(ids: readonly string[] | undefined): InboxReaskItems {
674  const actions = (ids ?? []).filter((id) => id.includes('/a-')).length
675  if (actions === 0) return undefined
676  return actions === (ids ?? []).length ? 'actions' : 'both'
677}
678
679/**
680 * The Re-ask wake's second line, naming only what the note lists. With only
681 * questions, more than one, it is INBOX_REASK_INSTRUCTION byte for byte.
682 * `one`: the note lists a single question or action item.
683 */
684export function inboxReaskInstruction(items: InboxReaskItems, one = false): string {
685  if (one && items !== 'both') {
686    const what = items === 'actions' ? 'action item' : 'question'
687    return `The person asked, from the Plannotator Inbox, for the open ${what} in this thread to be asked again, in one new message. The ${what} and what to do with it follow. Answer in the same thread: plannotator_inbox send_message with reply_to set to the id in parentheses on the line above.`
688  }
689  if (items !== 'actions' && items !== 'both') return INBOX_REASK_INSTRUCTION
690  const { what, they } = reaskWords(items)
691  return `The person asked, from the Plannotator Inbox, for the ${what} in this thread to be asked again, together in one new message. ${they} and what to do with each follow. Answer in the same thread: plannotator_inbox send_message with reply_to set to the id in parentheses on the line above.`
692}
693
694/**
695 * The line under INBOX_REASK_INSTRUCTION on a Re-ask the person sent to this
696 * session because the session that asked had ended: the questions are
697 * another session's, and this one takes them over.
698 */
699export function inboxReaskRedirectedLine(asker: string, id: string, items?: InboxReaskItems, one = false): string {
700  if (one && items !== 'both') {
701    const what = items === 'actions' ? 'This action item' : 'This question'
702    return `${what} was asked by another ${asker} session, which has ended; the person picked you to take it over. Read the thread first with read_thread (message_id ${id}), then ask it again as below if it is still needed.`
703  }
704  const these = items === 'actions' ? 'These action items' : items === 'both' ? 'These questions and action items' : 'These questions'
705  return `${these} were asked by another ${asker} session, which has ended; the person picked you to take them over. Read the thread first with read_thread (message_id ${id}), then ask the ones still needed again as below.`
706}
707
708/** The fixed second line of a New message wake: the person wrote first, and how to answer. */
709export const INBOX_MESSAGE_INSTRUCTION =
710  "The person wrote to you from the Plannotator Inbox. Their message follows as they wrote it: it is from them, not from the Inbox. When they need to hear back, answer in the same thread: plannotator_inbox send_message with reply_to set to the id in parentheses on the line above."
711
712/**
713 * The fixed second line of a wake for a thread the person started from the
714 * Inbox (compose): their own idea or request, not an answer to something the
715 * agent asked, and possibly unrelated to its current work.
716 */
717export const INBOX_NEW_THREAD_INSTRUCTION =
718  "The person started a new thread with you in the Plannotator Inbox: an idea or a request of their own, not an answer to something you asked. Their message follows as they wrote it. It may be unrelated to what you were doing; say how you will handle it before you start. When they need to hear back, answer in the same thread: plannotator_inbox send_message with reply_to set to the id in parentheses on the line above."
719
720/**
721 * The line under the instruction (and any redirected or continues line) on a
722 * command that carries `name_thread`: the agent names the thread the person
723 * started, with send_message's `thread` on its reply (approval
724 * "inbox-agent-names-own-thread"; the name is the thread's chip).
725 */
726export const INBOX_NAME_THREAD_LINE =
727  "Name this thread in your reply: pass `thread` with a few words saying what it is about. The first name you give sets it, once."
728
729/**
730 * The line under the instruction on a message that adds to a thread the
731 * person started with another session: the session reading it has not seen
732 * that thread, so it reads it first.
733 */
734export function inboxContinuesLine(id: string): string {
735  return `This continues a thread the person started with another session; you have not seen it. Read it first with read_thread (message_id ${id}), then answer in it with reply_to ${id}.`
736}
737
738/**
739 * The longest asking-agent name a redirected wake carries. The server names
740 * it from the host (`Claude Code`); the wake takes only a host's own name
741 * (INBOX_WAKE_AGENT_NAMES), because it goes into another session's prompt.
742 */
743export const INBOX_REDIRECTED_NAME_MAX = 40
744
745/**
746 * The line under the instruction on a reply written to another session that
747 * has ended: the session reading it never asked, so it reads the thread first.
748 */
749export function inboxRedirectedLine(asker: string, id: string): string {
750  return `This reply was written to another ${asker} session that has ended. Read the thread with read_thread to see what it asked, then answer with reply_to ${id}.`
751}
752
753/**
754 * The whole of a 👍 Looks good wake under its first line, and the body of
755 * the note the Inbox stores for it: the person read the message and needs
756 * nothing more.
757 */
758export function inboxAckLine(messageId: string): string {
759  return `The person marked your message 👍 Looks good (${messageId}). No reply needed unless you have a question.`
760}
761
762/**
763 * The thread id a wake's closing line names: the Inbox's own id shape only
764 * (`msg_` + a ULID today), so nothing else a command carries reaches the
765 * prompt there. Anything else (an older Inbox without the field) is ''.
766 */
767function wakeThreadId(value: unknown): string {
768  return typeof value === 'string' && /^msg_[0-9A-Za-z]{1,64}$/.test(value) ? value : ''
769}
770
771/**
772 * The closing line of every wake, after the body: which thread it is, how to
773 * read more of it, and where the Inbox explains itself.
774 * `[thread <id> · more: <tool> read_thread · how it works: plannotator inbox --help]`,
775 * with the tool named as the host registered it (the mod's
776 * `mcp__<server>__plannotator_inbox`). Without a thread id (an older Inbox)
777 * the thread part is left out.
778 */
779export function inboxWakeClosingLine(threadId: unknown, toolName: string = INBOX_TOOL_NAME): string {
780  const thread = wakeThreadId(threadId)
781  const tool = typeof toolName === 'string' && /^[A-Za-z0-9_.-]{1,128}$/.test(toolName.trim()) ? toolName.trim() : INBOX_TOOL_NAME
782  return `[${thread ? `thread ${thread} · ` : ''}more: ${tool} read_thread · how it works: plannotator inbox --help]`
783}
784
785/**
786 * The turn a reply or a message becomes: `Plannotator Inbox: <subject> (<id>)`,
787 * the fixed instruction line for its type (a reply, a New message, or a
788 * thread the person started; on a redirected reply, the line
789 * saying so under it), then the words verbatim, then the closing line
790 * (`inboxWakeClosingLine`, naming `toolName`, the tool as the host
791 * registered it). Never the thread re-sent. A 👍 Looks good (`ack_of`) is the
792 * first line and `inboxAckLine`, closed by `[thread <id>]` alone.
793 */
794export function inboxWakeText(
795  command: Pick<InboxReplyCommand, 'id' | 'subject' | 'body'> & {
796    type?: InboxReplyCommand['type']
797    thread_id?: unknown
798    redirected_from?: string | null
799    new_thread?: boolean
800    continues_thread?: boolean
801    name_thread?: boolean
802    ack_of?: string
803    tagged?: { owner?: unknown } | null
804    also_tagged?: unknown
805    reask?: boolean
806    reask_items?: unknown
807    reask_one?: unknown
808  },
809  toolName: string = INBOX_TOOL_NAME,
810): string {
811  if (typeof command.ack_of === 'string' && command.ack_of !== '') {
812    const ackSubject = (command.subject ?? '').replace(/\s+/g, ' ').trim() || 'a message'
813    const thread = wakeThreadId(command.thread_id)
814    return `Plannotator Inbox: ${ackSubject} (${command.id})\n${inboxAckLine(command.ack_of)}${thread ? `\n\n[thread ${thread}]` : ''}`
815  }
816  const closing = `\n\n${inboxWakeClosingLine(command.thread_id, toolName)}`
817  const subject = (command.subject ?? '').replace(/\s+/g, ' ').trim() || (command.type === 'message' ? 'a message' : 'a reply')
818  // Tagged into a thread another session owns: what it is, then read the thread first.
819  if (command.tagged && typeof command.tagged === 'object') {
820    const owner = wakeName(command.tagged.owner) || 'another agent'
821    return `Plannotator Inbox: ${subject} (${command.id})\n${INBOX_TAGGED_INSTRUCTION}\n${inboxTaggedLine(owner, command.id)}\n\n${command.body}${closing}`
822  }
823  const others = Array.isArray(command.also_tagged)
824    ? command.also_tagged
825        .filter((name) => typeof name === 'string' && name.trim() !== '')
826        .map((name) => wakeName(name) || 'another agent')
827        .slice(0, 8)
828    : []
829  const also = others.length > 0 ? `\n${inboxAlsoTaggedLine(others)}` : ''
830  const reaskItems: InboxReaskItems = command.reask_items === 'actions' || command.reask_items === 'both' ? command.reask_items : undefined
831  const reaskOne = command.reask_one === true
832  const instruction =
833    command.type === 'message'
834      ? command.new_thread === true
835        ? INBOX_NEW_THREAD_INSTRUCTION
836        : INBOX_MESSAGE_INSTRUCTION
837      : command.reask === true
838        ? inboxReaskInstruction(reaskItems, reaskOne)
839        : INBOX_WAKE_INSTRUCTION
840  const asker =
841    command.type !== 'message' && typeof command.redirected_from === 'string' && command.redirected_from.trim() !== ''
842      ? wakeName(command.redirected_from) || 'agent'
843      : ''
844  const redirected = asker
845    ? `\n${command.reask === true ? inboxReaskRedirectedLine(asker, command.id, reaskItems, reaskOne) : inboxRedirectedLine(asker, command.id)}`
846    : command.continues_thread === true
847      ? `\n${inboxContinuesLine(command.id)}`
848      : ''
849  const naming = command.name_thread === true ? `\n${INBOX_NAME_THREAD_LINE}` : ''
850  return `Plannotator Inbox: ${subject} (${command.id})\n${instruction}${redirected}${also}${naming}\n\n${command.body}${closing}`
851}
852
853/**
854 * A session is live while its connection polled within this long (plan step
855 * 8): New message is addressed only to a live session. A connection polls
856 * again at once after each held poll (at most 25 s), so a running session is
857 * never this long without one.
858 */
859export const INBOX_SESSION_LIVE_MS = 30_000
860
hooks/mod/inbox-default-tools.ts 360 lines
1// GENERATED by scripts/sync-mod-inbox-tools.ts from a real Inbox's /mcp tools/list. Do not edit;
2// run `bun run scripts/sync-mod-inbox-tools.ts` after changing an Inbox MCP tool.
3//
4// The tools `plannotator_inbox` carries in a Claude Code session that starts before
5// this computer ever ran the Inbox (no inbox/inbox.json, nothing remembered): the
6// first call starts the Inbox with `plannotator inbox --background`.
7import type { InboxToolInfo } from './inbox-contract'
8
9export const INBOX_DEFAULT_TOOLS: readonly InboxToolInfo[] = [
10  {
11    "name": "send_message",
12    "description": "Message the person in the Plannotator Inbox (markdown), in your session's open thread (see `thread`). One message per real need.\n\n## Asking the reviewer questions\n\nAsk what only the reviewer can decide as a question block. Answers come back at the top of their feedback (\"Answers to your questions\", then \"Unanswered\").\n\n```markdown\n:::question\nWhere should we keep the edit that loses a sync conflict?\n\nWhen two devices edit one note offline, the later save wins and the other edit is lost. Local storage keeps it with no server work.\n\n- [ ] Local only, purged after 30 days — cheap, no server change\n- [ ] Server-side per user — survives reinstall, needs a retention policy\n- [ ] Nowhere — accept silent loss for v1\n\nRecommended: Local only, purged after 30 days\n:::\n```\n\n- `:::question` picks one choice, `:::question-multi` any number, `:::question-text` free text (so does a block with no choices).\n- The first line is the question; the lines after it are context. Never send a bare question: the reviewer switches in cold, thinks at the level of the product, and does not know what you know.\n  - Say what the choice affects, what you know or tried, and why you recommend it, so they can decide without opening anything else.\n  - Be terse: one to three short sentences, plain words, no jargon or internal names.\n  - Add a screenshot (`![alt](path)`) for anything visual.\n  - Link a file that shows it better (a plan, a mock): `[the mock](mock.html)`. In the Inbox, attach it too; the link opens it beside the thread.\n- Choices: `- [ ] label`, optionally `- [ ] label — why`. The reviewer can also answer \"Other\", add a note, or skip.\n- `Recommended: <label>` marks yours (`A, B and C` on `:::question-multi`); other text shows as one more answer, tagged Recommended.\n- Ask only what you cannot decide alone, about 8 a round at most. Do not ask rhetorical questions or questions the codebase answers.\n- `- [x]` marks a settled choice. On resubmit, check the chosen answer, or drop the block and state the decision in prose.\n- Leave blank lines between the parts so the block reads well on GitHub.\n- Each answer comes back under its question (`### Q2. <question> (line N)`) as `Answer: <choice>`, marked `(your recommendation)` when the reviewer took yours, or as `Other: …`, free text in a quote, or `Skipped`, plus any `Note:`. A question you marked `- [x]` is settled and only comes back if the reviewer changed it or added a note.\n- In the Inbox, withdraw your own questions that are still open (read_thread state `open` or `picked`) as the thread moves on: when a newer message replaces them, makes them moot or follows up on them, or the person's reply settled them in words, name them in `supersedes` (or a `Replaces:` line) so they stop keeping the thread at the top of the person's list.\n",
13    "inputSchema": {
14      "type": "object",
15      "$schema": "https://json-schema.org/draft/2020-12/schema",
16      "properties": {
17        "body": {
18          "type": "string",
19          "minLength": 1,
20          "description": "The message, markdown. Question blocks render as answerable cards.\n\nTwo Inbox-only lines a question block can carry, each on its own line after the question:\n- `Stopped: <why>` only when you truly cannot go on until this is answered: the thread goes first in the person's list, under \"Stopped on you\". Otherwise leave the line out. A negative value (`no`, `none`, `n/a`, `-`) means no stop, so never write `Stopped: no`.\n- `Holds up: <work>; <work>` names the work that waits on the answer while you go on: listed under \"Holding up work\" (a `Stopped:` line wins). A `none` entry holds nothing up.\n\n:::question\nWhich database password should I use for staging?\n\nStopped: can't run the migration without it\nHolds up: staging deploy; release notes\n\n- [ ] The one in 1Password \"staging-db\"\n- [ ] Make a new one\n:::\n\nOptional lines after the question, for a decision that needs them. Most questions need none of these:\n- `Stakes: <one sentence>`: what the choice affects, in product terms. Give one whenever you write `Stopped:` or `Holds up:`.\n- `Shows: ![alt](path)` or `Shows: [name](file)`: the one picture or file the decision is about (put long detail in that file, not the block).\n- `Why: <one line>`, on its own line after `Recommended:`: why you recommend it.\n- `Reversible: no — <why>`: only when the answer cannot be taken back.\n- A picture choice, when the options are visual: `- [ ] Label — ![alt](path) consequence`. The picture picks it; the label is the answer you get back.\n\n:::question\nWhich checkout drawer should ship?\nStakes: ships to all of checkout on Thursday; changing it later costs a week of QA.\n\n- [ ] A · Total on top — ![Drawer A](drawer-a.png) closest to today\n- [ ] B · Total pinned with Pay — ![Drawer B](drawer-b.png) the total never scrolls away\n\nRecommended: B · Total pinned with Pay\n\nWhy: on a phone only B keeps the total next to the button.\n:::\n\nAn action item, only for a true blocker: something the person must go and do outside this conversation before you can go on, that you cannot do yourself (approve a deploy, sign in, touch a security key, click something in another app, merge a pull request you cannot merge). Write it as an Inbox-only `:::action` block: the first line is what to do, as an order; then why, in a line or two. Optional lines: `Where: <url or place>` (a URL becomes an Open button), `Run: <command>` (a command to copy), `Stopped:` / `Holds up:` as for questions, and `Watching: <what you watch>` when you will notice it done by yourself (then pass its id in `done`).\nNever use it for a decision or a question (ask a :::question), for anything you can do yourself, or as a checklist or a status update: one block per real blocker, and most messages need none. The person marks it Done or Can't do it (with a reason); that comes back in their reply under \"Action items you asked for\".\n\n:::action\nApprove the production deploy on Vercel\nThe 4.2 build passed every check and waits under \"Promote to Production\". Nothing else needs changing.\n\nWhere: https://vercel.com/acme/web/deployments\nStopped: release 4.2 cannot go out until it is approved\nWatching: the deployment; I go on by myself once it is Ready\n:::"
21        },
22        "project_path": {
23          "description": "Absolute path of the repository or folder you work in; the thread lands in that project's row. The `plannotator inbox mcp` shim fills it from its working folder.",
24          "type": "string"
25        },
26        "subject": {
27          "description": "A short one-line subject when this starts a thread (ignored when it joins one). Plain text: no line breaks. Default: the first question's prompt, else the first line.",
28          "type": "string"
29        },
30        "thread": {
31          "description": "A short thread name (1-120 characters, one line). Without it, your messages join your session's open thread in this project (a new one the first time, or once the person resolved it; a thread keeps its first subject). With it, the same name in this project is the same open thread, across sessions (compared without case, spacing or invisible characters). Use it to split separate work, or to join another session's thread. Ignored with reply_to, with one exception: in a thread the person started (read_thread or wait_for_reply says name_this_thread: true, or the Inbox's message asks you to name it), your reply's `thread` names that thread, once: a few words saying what it is about, not the name of another open thread in the project.",
32          "type": "string"
33        },
34        "reply_to": {
35          "description": "A message id: post this as a reply in that message's thread.",
36          "type": "string"
37        },
38        "supersedes": {
39          "description": "Earlier questions in this thread that no longer apply, so the person cannot answer them any more. Withdraw your own questions that are still open (read_thread state open or picked; a sent, skipped or closed one is refused) this way as the thread moves on: when this message replaces them, makes them moot or follows up on them, or the person's reply settled them in words, so they stop keeping the thread at the top of the person's list. \"<message id>/<key>\" for one question (read_thread gives each question's key) or \"<message id>\" for every open question of that message. With exactly one question in this message, it replaces them; otherwise they read \"No longer applies\". To replace one with a particular new question, put `Replaces: <message id>/<key>` in that question's block instead. The person's pick on a superseded question is never sent. Every id must name an open question of the thread this message lands in (use reply_to); otherwise nothing is sent and the refusal, invalid_supersedes, lists the thread's open questions.",
40          "type": "array",
41          "items": {
42            "type": "string"
43          }
44        },
45        "done": {
46          "description": "Your own action items (`:::action` blocks) in this thread that you saw done yourself, e.g. the deployment you were watching is Ready: \"<message id>/<key>\" for one (the key starts with a-; read_thread gives it) or \"<message id>\" for every open action item of that message. The card then says you saw it done, and nothing is sent to the person. Only your own action items that are still open (not one the person already marked) in the thread this message lands in (use reply_to); otherwise nothing is sent and the refusal, invalid_done, lists the thread's open action items. Never mark done what you did not see happen.",
47          "type": "array",
48          "items": {
49            "type": "string"
50          }
51        },
52        "idempotency_key": {
53          "description": "Any unique string; sending again with the same key answers the first message instead of posting twice.",
54          "type": "string"
55        },
56        "agent_session": {
57          "description": "Your session id. The `plannotator inbox mcp` shim fills it. send_message joins your session's thread by it; read_thread's asked_by \"me\" and wait_for_reply without a thread match on it.",
58          "type": "string"
59        },
60        "agent_name": {
61          "description": "How the person sees you, e.g. \"Claude Code\".",
62          "type": "string"
63        },
64        "agent_host": {
65          "description": "Your agent host, e.g. claude-code, codex, cursor.",
66          "type": "string"
67        },
68        "attachments": {
69          "description": "Files to show the person beside your message, e.g. [\"docs/plan.md\", \"/tmp/checkout.png\", \"src/retry.mjs\"]: absolute (anywhere you can read) or relative to project_path. For something visual, a screenshot or image usually reads fastest; attach the HTML or source too when they should open or click through it. Any regular file, any size. Markdown, plain text, config and data files, Mermaid and Graphviz sources and HTML (its relative images and frames load from its folder) open in Plannotator's viewers; images (PNG, JPEG, GIF, WebP, SVG, AVIF, BMP, ICO) show in the message; videos (MP4, MOV, WebM) play beside it, and the person comments at moments (each comment comes back with its time and the paused frame's path); source code, scripts and other text open as code with line comments; PDFs and anything else are offered as a download. Folders and .env files are refused. The Inbox keeps the version you sent and shows the file as it is now, saying when it changed. The person's annotations, including comments on images and code lines, come back in their reply. Each attachment's kind in the result is markdown, text, html, mermaid, graphviz, code, image, video, pdf or file; treat any other as file. A markdown link to an attached file in the body, e.g. [the mock](proto/admin.html), opens it beside the thread.",
70          "type": "array",
71          "items": {
72            "type": "string"
73          }
74        }
75      },
76      "required": [
77        "body"
78      ],
79      "additionalProperties": false
80    }
81  },
82  {
83    "name": "read_thread",
84    "description": "Read one Inbox thread (thread_id, or message_id to show that message in full) as a transcript: the questions still waiting on the person (key, state, prompt, choices), the newest messages in full (`limit`, default 6), the person's earlier messages in full (up to 12.0 KB), and every other earlier message as one line with its questions' states and answers; a body over 16.0 KB is cut. `expand` shows messages in full, `before` reads further back, `after` (the result's cursor, or a message id) returns only what is new; `format: \"full\"` returns every full record. A message the person marked 👍 Looks good carries `ack` (they read it and need nothing more; no reply is needed). Without an id, list this project's threads, newest activity first, one short row each (subject, name, section in the person's list, open questions, last author and time, the person's last message, `unread`: the person wrote something you have not read): only the ones you sent in unless asked_by is \"anyone\", and only open ones unless include_resolved.",
85    "inputSchema": {
86      "type": "object",
87      "$schema": "https://json-schema.org/draft/2020-12/schema",
88      "properties": {
89        "thread_id": {
90          "type": "string"
91        },
92        "message_id": {
93          "type": "string"
94        },
95        "project_path": {
96          "description": "Absolute path of the repository or folder you work in; the thread lands in that project's row. The `plannotator inbox mcp` shim fills it from its working folder.",
97          "type": "string"
98        },
99        "asked_by": {
100          "description": "Default \"me\" when your session is known.",
101          "type": "string",
102          "enum": [
103            "me",
104            "anyone"
105          ]
106        },
107        "include_resolved": {
108          "type": "boolean"
109        },
110        "limit": {
111          "description": "How many: a thread's messages in full (default 6), listed threads (20), search results (10, at most 50).",
112          "type": "integer",
113          "minimum": 1,
114          "maximum": 100
115        },
116        "expand": {
117          "description": "Message ids of this thread to show in full.",
118          "type": "array",
119          "items": {
120            "type": "string"
121          }
122        },
123        "before": {
124          "description": "Only messages before this message id or cursor.",
125          "anyOf": [
126            {
127              "type": "string"
128            },
129            {
130              "type": "number",
131              "minimum": 0
132            }
133          ]
134        },
135        "after": {
136          "description": "Only messages after this message id or cursor (what is new).",
137          "anyOf": [
138            {
139              "type": "string"
140            },
141            {
142              "type": "number",
143              "minimum": 0
144            }
145          ]
146        },
147        "format": {
148          "description": "Every message as its full record (large).",
149          "type": "string",
150          "enum": [
151            "full"
152          ]
153        },
154        "agent_session": {
155          "description": "Your session id. The `plannotator inbox mcp` shim fills it. send_message joins your session's thread by it; read_thread's asked_by \"me\" and wait_for_reply without a thread match on it.",
156          "type": "string"
157        }
158      },
159      "additionalProperties": false
160    }
161  },
162  {
163    "name": "search",
164    "description": "Search the Inbox's messages (yours, other agents' and the person's) by words, read-only: in this project unless all_projects. Up to `limit` results (default 10, at most 50; a larger limit answers 50). Every word must match (the last may be the start of a word), questions' prompts, choices and answers included. Each result is one line: the thread, the message, who wrote it, when, and the words around the match. read_thread with that thread_id and message_id shows the message in full.",
165    "inputSchema": {
166      "type": "object",
167      "$schema": "https://json-schema.org/draft/2020-12/schema",
168      "properties": {
169        "query": {
170          "type": "string",
171          "minLength": 1,
172          "description": "Words to find."
173        },
174        "project_path": {
175          "description": "Absolute path of the repository or folder you work in; the thread lands in that project's row. The `plannotator inbox mcp` shim fills it from its working folder.",
176          "type": "string"
177        },
178        "all_projects": {
179          "description": "Search every project.",
180          "type": "boolean"
181        },
182        "limit": {
183          "description": "Results (default 10, at most 50).",
184          "type": "integer",
185          "minimum": 1,
186          "maximum": 100
187        }
188      },
189      "required": [
190        "query"
191      ],
192      "additionalProperties": false
193    }
194  },
195  {
196    "name": "wait_for_reply",
197    "description": "Wait for the person's reply in a thread (thread_id or message_id), or in any open thread you asked when neither is given. Returns the reply as soon as it lands, { status: \"acknowledged\" } when the person marked your latest message 👍 Looks good instead (no reply is coming for it; go on), or { status: \"waiting\", cursor } after about 50 seconds: call again with that cursor to keep waiting. Without a cursor, any reply after your last message in the thread counts.",
198    "inputSchema": {
199      "type": "object",
200      "$schema": "https://json-schema.org/draft/2020-12/schema",
201      "properties": {
202        "thread_id": {
203          "type": "string"
204        },
205        "message_id": {
206          "type": "string"
207        },
208        "cursor": {
209          "description": "The cursor a previous call returned.",
210          "type": "integer",
211          "minimum": 0,
212          "maximum": 9007199254740991
213        },
214        "timeout_seconds": {
215          "description": "Wait at most this long (default 50).",
216          "type": "integer",
217          "minimum": 1,
218          "maximum": 50
219        },
220        "project_path": {
221          "description": "Absolute path of the repository or folder you work in; the thread lands in that project's row. The `plannotator inbox mcp` shim fills it from its working folder.",
222          "type": "string"
223        },
224        "agent_session": {
225          "description": "Your session id. The `plannotator inbox mcp` shim fills it. send_message joins your session's thread by it; read_thread's asked_by \"me\" and wait_for_reply without a thread match on it.",
226          "type": "string"
227        }
228      },
229      "additionalProperties": false
230    }
231  },
232  {
233    "name": "resolve_message",
234    "description": "Archive the thread a message belongs to for the person; use it only when nothing in it is left for them to read or answer. resolved: false reopens it. Its questions read as closed; the person sees the thread as Archived.",
235    "inputSchema": {
236      "type": "object",
237      "$schema": "https://json-schema.org/draft/2020-12/schema",
238      "properties": {
239        "message_id": {
240          "type": "string",
241          "description": "Any message id in the thread, or the thread id."
242        },
243        "resolved": {
244          "description": "Default true.",
245          "type": "boolean"
246        }
247      },
248      "required": [
249        "message_id"
250      ],
251      "additionalProperties": false
252    }
253  },
254  {
255    "name": "submit_guide",
256    "description": "Send the person a guided review of a code change. It lands in the Plannotator Inbox as a message with a \"Guided review\" card that opens in Plannotator's guide viewer. Pass `guide` (the shape get_guide_brief gives) and `patch` (the exact unified diff it describes), or `snapshot` (a complete Plannotator guide snapshot). Every file a section names must be in the patch, in one section only; a refusal names the file. Files you leave out show under \"Everything else\". `body` is your note above the card (default: the guide's intent). thread, reply_to, supersedes, done and idempotency_key work as in send_message; the person's answer comes back through wait_for_reply.\n\nExample: get_guide_brief's `example` is a call that works as it is.",
257    "inputSchema": {
258      "type": "object",
259      "$schema": "https://json-schema.org/draft/2020-12/schema",
260      "properties": {
261        "guide": {
262          "description": "The guide: { title, intent, sections: [{ title, overview, diffs: [{ file, summary }] }], unplacedFiles?, review?: { gitRef, base }, source?, generator? } (get_guide_brief's output_schema), as an object or its JSON.",
263          "anyOf": [
264            {
265              "type": "object",
266              "propertyNames": {
267                "type": "string"
268              },
269              "additionalProperties": {}
270            },
271            {
272              "type": "string"
273            }
274          ]
275        },
276        "patch": {
277          "description": "The exact unified diff the guide describes (get_guide_brief's diff_steps).",
278          "type": "string"
279        },
280        "snapshot": {
281          "description": "Instead of guide and patch: a complete Plannotator guide snapshot, as an object or its JSON.",
282          "anyOf": [
283            {
284              "type": "object",
285              "propertyNames": {
286                "type": "string"
287              },
288              "additionalProperties": {}
289            },
290            {
291              "type": "string"
292            }
293          ]
294        },
295        "body": {
296          "description": "Your note above the card, markdown. Default: the guide's intent.",
297          "type": "string"
298        },
299        "project_path": {
300          "description": "Absolute path of the repository or folder you work in; the thread lands in that project's row. The `plannotator inbox mcp` shim fills it from its working folder.",
301          "type": "string"
302        },
303        "subject": {
304          "description": "A short one-line subject when this starts a thread (ignored when it joins one). Plain text: no line breaks. Default: the first question's prompt, else the first line.",
305          "type": "string"
306        },
307        "thread": {
308          "description": "A short thread name (1-120 characters, one line). Without it, your messages join your session's open thread in this project (a new one the first time, or once the person resolved it; a thread keeps its first subject). With it, the same name in this project is the same open thread, across sessions (compared without case, spacing or invisible characters). Use it to split separate work, or to join another session's thread. Ignored with reply_to, with one exception: in a thread the person started (read_thread or wait_for_reply says name_this_thread: true, or the Inbox's message asks you to name it), your reply's `thread` names that thread, once: a few words saying what it is about, not the name of another open thread in the project.",
309          "type": "string"
310        },
311        "reply_to": {
312          "description": "A message id: post this as a reply in that message's thread.",
313          "type": "string"
314        },
315        "supersedes": {
316          "description": "Earlier questions in this thread that no longer apply, so the person cannot answer them any more. Withdraw your own questions that are still open (read_thread state open or picked; a sent, skipped or closed one is refused) this way as the thread moves on: when this message replaces them, makes them moot or follows up on them, or the person's reply settled them in words, so they stop keeping the thread at the top of the person's list. \"<message id>/<key>\" for one question (read_thread gives each question's key) or \"<message id>\" for every open question of that message. With exactly one question in this message, it replaces them; otherwise they read \"No longer applies\". To replace one with a particular new question, put `Replaces: <message id>/<key>` in that question's block instead. The person's pick on a superseded question is never sent. Every id must name an open question of the thread this message lands in (use reply_to); otherwise nothing is sent and the refusal, invalid_supersedes, lists the thread's open questions.",
317          "type": "array",
318          "items": {
319            "type": "string"
320          }
321        },
322        "done": {
323          "description": "Your own action items (`:::action` blocks) in this thread that you saw done yourself, e.g. the deployment you were watching is Ready: \"<message id>/<key>\" for one (the key starts with a-; read_thread gives it) or \"<message id>\" for every open action item of that message. The card then says you saw it done, and nothing is sent to the person. Only your own action items that are still open (not one the person already marked) in the thread this message lands in (use reply_to); otherwise nothing is sent and the refusal, invalid_done, lists the thread's open action items. Never mark done what you did not see happen.",
324          "type": "array",
325          "items": {
326            "type": "string"
327          }
328        },
329        "idempotency_key": {
330          "description": "Any unique string; sending again with the same key answers the first message instead of posting twice.",
331          "type": "string"
332        },
333        "agent_session": {
334          "description": "Your session id. The `plannotator inbox mcp` shim fills it. send_message joins your session's thread by it; read_thread's asked_by \"me\" and wait_for_reply without a thread match on it.",
335          "type": "string"
336        },
337        "agent_name": {
338          "description": "How the person sees you, e.g. \"Claude Code\".",
339          "type": "string"
340        },
341        "agent_host": {
342          "description": "Your agent host, e.g. claude-code, codex, cursor.",
343          "type": "string"
344        }
345      },
346      "additionalProperties": false
347    }
348  },
349  {
350    "name": "get_guide_brief",
351    "description": "Get what you need to write a guided review of a code change for the person: Plannotator's method, the JSON shape of the guide, how to read the diff, the rules, and a worked submit_guide call. Read the diff in your checkout, write the guide on your own model, then call submit_guide with the guide and that exact patch.",
352    "inputSchema": {
353      "type": "object",
354      "$schema": "https://json-schema.org/draft/2020-12/schema",
355      "properties": {},
356      "additionalProperties": false
357    }
358  }
359]
360
hooks/mod/launch.ts 656 lines
1/**
2 * Starting the `plannotator` CLI detached, and reading what it leaves behind.
3 *
4 * `$.process.run` is one shot and ends at ten minutes, so it cannot hold a
5 * review open. It runs a tiny `/bin/sh` wrapper instead that starts the CLI in
6 * the background with every stream on a file and returns at once. The CLI
7 * itself does the rest through files in the launch directory:
8 *
9 *   stdin        what the CLI reads on stdin (plan JSON, the last message)
10 *   ready        PLANNOTATOR_READY_FILE: one JSON line { url, isRemote, port, target? } once listening
11 *   result.json  PLANNOTATOR_HOST_RESULT_FILE: the decision record, written atomically
12 *   stdout/stderr  the CLI's own output (startup errors land in stderr)
13 *   pid          the CLI's pid, for the liveness check
14 *   exit         the CLI's exit code, written after it exits
15 *   revision.json / revision.json.ack   plan revisions pushed into an open review
16 *   messages.json  PLANNOTATOR_HOST_MESSAGES_FILE: `last`'s recent assistant messages, for the picker
17 *   watcher.json   which Claude Code process watches this launch (`{ owner, at, touchedAt }`, a heartbeat)
18 *   settled/by     the claim: made (mkdir) by the one process that settles the launch, naming it
19 *
20 * No listener in the mod: it looks at these files on a timer.
21 */
22
23import type { SessionKind } from './delivery'
24import { splitShellWords } from './shell-words'
25import { PLAN_APPROVALS_DIR } from './plan'
26import { looksLikeFilePath, plannotatorBundleSubject, plannotatorTargetSubject, type PlannotatorTarget } from './tool'
27
28/** The wrapper. `$1` is the launch directory; the CLI argv follows. */
29export const LAUNCH_SCRIPT = [
30  'dir=$1; shift',
31  '(',
32  "  trap '' HUP",
33  '  nohup "$@" < "$dir/stdin" > "$dir/stdout" 2> "$dir/stderr" &',
34  '  child=$!',
35  '  echo "$child" > "$dir/pid"',
36  '  wait "$child"',
37  '  code=$?',
38  '  echo "$code" > "$dir/exit.tmp" && mv "$dir/exit.tmp" "$dir/exit"',
39  ') < /dev/null > /dev/null 2>&1 &',
40].join('\n')
41
42export const LAUNCH_FILES = {
43  stdin: 'stdin',
44  ready: 'ready',
45  result: 'result.json',
46  stdout: 'stdout',
47  stderr: 'stderr',
48  pid: 'pid',
49  exit: 'exit',
50  revision: 'revision.json',
51  messages: 'messages.json',
52  watcher: 'watcher.json',
53  overflow: 'feedback.md',
54} as const
55
56/** The claim directory `claimArgv` makes, and the file in it naming the claimant. */
57export const SETTLED_DIR = 'settled'
58export const SETTLED_BY = 'settled/by'
59
60export function fileIn(dir: string, name: keyof typeof LAUNCH_FILES): string {
61  return `${dir}/${LAUNCH_FILES[name]}`
62}
63
64/** Polls for any of its arguments to exist, 100 ms apart, `$1` times. */
65export const WAIT_SCRIPT = [
66  'n=$1; shift',
67  'i=0',
68  'while [ "$i" -lt "$n" ]; do',
69  '  for f in "$@"; do [ -e "$f" ] && exit 0; done',
70  '  sleep 0.1',
71  '  i=$((i+1))',
72  'done',
73  'exit 1',
74].join('\n')
75
76/** `$.process.run` argv that waits for any of `paths` for up to `timeoutMs`. */
77export function waitArgv(paths: readonly string[], timeoutMs: number): string[] {
78  return ['/bin/sh', '-c', WAIT_SCRIPT, 'plannotator-wait', String(Math.max(1, Math.ceil(timeoutMs / 100))), ...paths]
79}
80
81/** `$.process.run` argv for a detached launch of `cliArgv` in `dir`. */
82export function launchArgv(dir: string, cliArgv: readonly string[]): string[] {
83  return ['/bin/sh', '-c', LAUNCH_SCRIPT, 'plannotator-launch', dir, ...cliArgv]
84}
85
86/**
87 * The data directory, as the CLI resolves it (`getPlannotatorDataDir`):
88 * `PLANNOTATOR_DATA_DIR` (with `~` expanded); else `~/.plannotator` when it
89 * exists; else `$XDG_DATA_HOME/plannotator` when that is absolute; else
90 * `~/.plannotator`. A relative `PLANNOTATOR_DATA_DIR` (resolved against the
91 * CLI's cwd) is refused: the mod could not name the same directory.
92 */
93export function dataDirOf(env: { home?: string; dataDir?: string; xdgDataHome?: string; legacyExists?: boolean }): string | null {
94  const home = env.home?.replace(/\/+$/, '')
95  const custom = env.dataDir?.trim()
96  if (custom) {
97    if (custom === '~') return home ?? null
98    if (custom.startsWith('~/')) return home ? `${home}/${custom.slice(2)}` : null
99    if (custom.startsWith('/')) return custom.replace(/\/+$/, '') || '/'
100    return null
101  }
102  if (!home) return null
103  const legacy = `${home}/.plannotator`
104  if (env.legacyExists) return legacy
105  const xdg = env.xdgDataHome?.trim()
106  if (xdg && xdg.startsWith('/')) return `${xdg.replace(/\/+$/, '')}/plannotator`
107  return legacy
108}
109
110/**
111 * Creates a launch directory owner-only (0700, and any parent it has to
112 * create) before anything is written into it: it holds the plan or message on
113 * stdin and the reviewer's feedback in stdout and result.json. Prints the
114 * working directory the CLI will run in (the session's), which the mod
115 * resolves relative targets against.
116 */
117export function privateDirArgv(dir: string): string[] {
118  return ['/bin/sh', '-c', 'umask 077 && mkdir -p "$1" && chmod 700 "$1" && pwd', 'plannotator-mkdir', dir]
119}
120
121/** `/a/b/../c/./d` → `/a/c/d` (no symlinks resolved: nothing is looked up). */
122function normalizeAbsolute(path: string): string {
123  const out: string[] = []
124  for (const segment of path.split('/')) {
125    if (segment === '' || segment === '.') continue
126    if (segment === '..') out.pop()
127    else out.push(segment)
128  }
129  return `/${out.join('/')}`
130}
131
132/** An absolute path word (`/a/b`, `@/a/b`), normalized; anything else (relative, `~`) is undefined. */
133function absoluteWord(word: string): string | undefined {
134  const path = word.replace(/^@/, '')
135  return path.startsWith('/') ? normalizeAbsolute(path) : undefined
136}
137
138/**
139 * The mod's own idea of what a launch shows, only for a CLI that predates
140 * naming its target in the ready file and result record. It never guesses:
141 * the CLI may resolve a bare or relative name somewhere else (it searches the
142 * project) and reads prose around a review directory as words to ignore, so a
143 * confidently wrong path would be worse than none. Only what the words state
144 * exactly counts: a URL or PR URL, an absolute path, and a review with no
145 * words at all (the session's directory, which the CLI reviews then). In
146 * every other case there is no fallback and the message carries no Target
147 * line from the mod.
148 */
149export function modTargetFor(
150  kind: SessionKind,
151  args: string | readonly string[],
152  cwd: string | undefined,
153): string | string[] | undefined {
154  const all = wordsOf(args)
155  const words: string[] = []
156  for (let index = 0; index < all.length; index += 1) {
157    const word = all[index] as string
158    // `--base <ref>` / `--diff-type <id>` take a value that is not a target.
159    if (word === '--base' || word === '--diff-type') {
160      index += 1
161      continue
162    }
163    if (!word.startsWith('-')) words.push(word)
164  }
165  switch (kind) {
166    case 'plan':
167    case 'last':
168      return undefined
169    case 'review': {
170      const pr = words.find((word) => PR_URL.test(word))
171      if (pr) return pr
172      if (words.length === 0) return cwd && cwd.startsWith('/') ? normalizeAbsolute(cwd) : undefined
173      return words.length === 1 ? absoluteWord(words[0] as string) : undefined
174    }
175    case 'annotate': {
176      if (isSeveralFilePaths(words)) {
177        const paths = [...new Set(words)].map(absoluteWord)
178        return paths.every((path): path is string => path !== undefined) ? paths : undefined
179      }
180      if (words.length !== 1) return undefined
181      const target = words[0] as string
182      if (/^https?:\/\//i.test(target)) return target
183      return absoluteWord(target)
184    }
185  }
186}
187
188/**
189 * Removes a settled launch's files, keeping `feedback.md` (Claude reads it
190 * later) and the directory when that file is there. Only names this module
191 * wrote; never a glob. The claim (`settled/`) goes only with the directory:
192 * while `feedback.md` keeps the directory, the claim keeps saying the launch
193 * was settled. Files go first, `stdin` among them, so a claim made after this
194 * started finds `stdin` gone and loses (`CLAIM_SCRIPT`).
195 */
196export function cleanupArgv(dir: string): string[] {
197  const names = Object.entries(LAUNCH_FILES)
198    .filter(([key]) => key !== 'overflow')
199    .map(([, name]) => name)
200  return [
201    '/bin/sh',
202    '-c',
203    [
204      'dir=$1; shift',
205      'for f in "$@"; do rm -f "$dir/$f"; done',
206      `if [ ! -e "$dir/${LAUNCH_FILES.overflow}" ]; then rm -f "$dir/${SETTLED_BY}" "$dir/${SETTLED_DIR}/delivered" "$dir/${SETTLED_DIR}/reported"; rmdir "$dir/${SETTLED_DIR}" 2>/dev/null; rmdir "$dir" 2>/dev/null; fi`,
207      'exit 0',
208    ].join('\n'),
209    'plannotator-cleanup',
210    dir,
211    ...names,
212    'revision.json.ack',
213    'exit.tmp',
214  ]
215}
216
217/** Exit codes of `CLAIM_SCRIPT`. */
218export const CLAIM_EXIT = { won: 0, lost: 3, failed: 4 } as const
219
220/**
221 * Claims one launch's settlement across Claude Code processes: two processes
222 * on one session id (`claude --continue` while the first still runs) both
223 * watch the launch, and only the one that makes `$1/settled` (mkdir is atomic
224 * and fails when it exists: exactly one winner) settles it, whichever file
225 * says it is settled (the result record, the exit code, or a dead pid). The
226 * winner writes its id (`$2`) to `settled/by`, so the same instance that
227 * claimed but lost the answer (a timed-out process call) wins again on retry
228 * (exit 0). A claim made once cleanup removed `stdin` is too late (exit 3).
229 * Neither made nor found: try again later (exit 4).
230 */
231export const CLAIM_SCRIPT = [
232  'd=$1; me=$2',
233  `if mkdir "$d/${SETTLED_DIR}" 2>/dev/null; then`,
234  `  printf '%s' "$me" > "$d/${SETTLED_BY}"`,
235  '  [ -e "$d/stdin" ] && exit 0',
236  '  exit 3',
237  'fi',
238  `[ "$(cat "$d/${SETTLED_BY}" 2>/dev/null)" = "$me" ] && exit 0`,
239  `[ -d "$d/${SETTLED_DIR}" ] && exit 3`,
240  '[ -d "$d" ] || exit 3',
241  'exit 4',
242].join('\n')
243
244export function claimArgv(dir: string, claimant: string): string[] {
245  return ['/bin/sh', '-c', CLAIM_SCRIPT, 'plannotator-claim', dir, claimant]
246}
247
248/**
249 * Prints each launch directory whose stored record can go. Arguments are
250 * directories in three groups, each started by a marker:
251 * - `--cleaned`: only when settled or cleaned up (no `stdin` — which the mod
252 *   writes before launching and only `cleanupArgv` removes — or no directory
253 *   at all; or a `settled/` claim marked delivered or reported, or with no
254 *   decision on disk). A claimed decision never marked delivered stays, so
255 *   its session can report it when resumed (`UNDELIVERED_AFTER_MS`);
256 * - `--dead`: also when no decision waits (`result.json`, `exit`) and the
257 *   server's pid no longer answers `kill -0` (or there is none);
258 * - `--expired`: also with a decision waiting, unless the server still runs
259 *   (a session nobody resumed for a long time).
260 * A live server always keeps its record.
261 */
262export const PRUNE_SCRIPT = [
263  'mode=cleaned',
264  'for d in "$@"; do',
265  '  case "$d" in --cleaned|--dead|--expired) mode=${d#--}; continue ;; esac',
266  '  if [ ! -e "$d/stdin" ]; then echo "$d"; continue; fi',
267  `  if [ -e "$d/${SETTLED_DIR}" ]; then`,
268  // Delivered, reported, or a claim on a server that stopped without a decision.
269  `    if [ -e "$d/${SETTLED_DIR}/delivered" ] || [ -e "$d/${SETTLED_DIR}/reported" ] || { [ ! -e "$d/result.json" ] && [ ! -e "$d/exit" ]; }; then echo "$d"; continue; fi`,
270  // Claimed and maybe never delivered: kept until its session reports it, or it expires.
271  '    [ "$mode" = expired ] || continue',
272  '  fi',
273  '  [ "$mode" = cleaned ] && continue',
274  '  pid=$(cat "$d/pid" 2>/dev/null)',
275  '  case "$pid" in',
276  '    "") alive=0 ;;',
277  '    *[!0-9]*) alive=1 ;;',
278  '    *) if kill -0 "$pid" 2>/dev/null; then alive=1; else alive=0; fi ;;',
279  '  esac',
280  '  [ "$alive" = 1 ] && continue',
281  '  if [ "$mode" = dead ]; then',
282  '    for f in result.json exit; do [ -e "$d/$f" ] && continue 2; done',
283  '  fi',
284  '  echo "$d"',
285  'done',
286].join('\n')
287
288export function pruneArgv(groups: { cleaned: readonly string[]; dead: readonly string[]; expired: readonly string[] }): string[] {
289  return [
290    '/bin/sh',
291    '-c',
292    PRUNE_SCRIPT,
293    'plannotator-prune',
294    '--cleaned',
295    ...groups.cleaned,
296    '--dead',
297    ...groups.dead,
298    '--expired',
299    ...groups.expired,
300  ]
301}
302
303/** Above this the debug log is moved to `<file>.1` before the next append. */
304export const DEBUG_LOG_MAX_BYTES = 1_048_576
305
306/**
307 * Appends stdin to the debug log, rotating it once it passes
308 * `DEBUG_LOG_MAX_BYTES`. Appending (O_APPEND) is what lets several Claude Code
309 * processes share one log: rewriting the whole file from each process's own
310 * buffer clobbered the other's lines and could leave NUL bytes behind. The
311 * rotation runs under a lock (`<file>.rotating`, mkdir; a lock older than a
312 * minute is a dead writer's and is removed) and re-checks the size inside it,
313 * so two writers past the limit at once rotate once instead of the second
314 * moving the fresh log over the first one's `<file>.1`.
315 */
316export const DEBUG_APPEND_SCRIPT = [
317  'f=$1; lock="$f.rotating"',
318  'mkdir -p "$(dirname "$f")" 2>/dev/null',
319  `size() { s=$(wc -c < "$f" 2>/dev/null | tr -d ' '); echo "\${s:-0}"; }`,
320  `if [ "$(size)" -gt ${DEBUG_LOG_MAX_BYTES} ]; then`,
321  '  [ -n "$(find "$lock" -maxdepth 0 -mmin +1 2>/dev/null)" ] && rmdir "$lock" 2>/dev/null',
322  '  if mkdir "$lock" 2>/dev/null; then',
323  `    [ "$(size)" -gt ${DEBUG_LOG_MAX_BYTES} ] && mv -f "$f" "$f.1" 2>/dev/null`,
324  '    rmdir "$lock" 2>/dev/null',
325  '  fi',
326  'fi',
327  'cat >> "$f"',
328].join('\n')
329
330export function debugAppendArgv(path: string): string[] {
331  return ['/bin/sh', '-c', DEBUG_APPEND_SCRIPT, 'plannotator-debug', path]
332}
333
334/** Liveness probe through the shell's own `kill` (no /bin/kill on every system). */
335export function aliveArgv(pid: string): string[] {
336  return ['/bin/sh', '-c', 'kill -0 "$1" 2>/dev/null', 'plannotator-alive', pid]
337}
338
339/** Exit codes of `STOP_SCRIPT`. */
340export const STOP_EXIT = { stopped: 0, decided: 3, notPlannotator: 4, failed: 5, cannotVerify: 6 } as const
341
342/**
343 * Stops a CLI that has no host close endpoint (an older Plannotator) with
344 * TERM, which ends the server without a decision and never deletes its draft.
345 * `$1` is the pid, the rest are files whose presence means the reviewer
346 * already decided (the result record, the exit code): then nothing is sent
347 * (exit 3), so that decision is still delivered. The pid must still name a
348 * `plannotator` process (exit 4 otherwise), so a pid reused after the CLI
349 * died (a reboot, a crash) is never signalled. Where `ps` cannot say (missing,
350 * as on Debian slim without procps, or without `-p`, as BusyBox's) nothing is
351 * signalled either (exit 6): the check is made on the script's own pid first.
352 */
353export const STOP_SCRIPT = [
354  'pid=$1; shift',
355  'for f in "$@"; do [ -e "$f" ] && exit 3; done',
356  '[ -n "$(ps -o args= -p $$ 2>/dev/null)" ] || exit 6',
357  'ps -o args= -p "$pid" 2>/dev/null | grep -q plannotator || exit 4',
358  'kill -TERM "$pid" 2>/dev/null || exit 5',
359].join('\n')
360
361export function stopArgv(pid: string, decidedFiles: readonly string[]): string[] {
362  return ['/bin/sh', '-c', STOP_SCRIPT, 'plannotator-stop', pid, ...decidedFiles]
363}
364
365/** Where the session's approved ExitPlanMode calls are recorded for the classic hook (plan.ts, #2007). */
366export function planApprovalPathOf(dataDir: string, sessionId: string, toolUseId: string): { dir: string; path: string } {
367  const safe = (value: string) => value.replace(/[^A-Za-z0-9._-]/g, '_')
368  const dir = `${dataDir}/claude-code-mod/${safe(sessionId)}/${PLAN_APPROVALS_DIR}`
369  return { dir, path: `${dir}/${safe(toolUseId)}.json` }
370}
371
372/** Removes one file the mod wrote; nothing else. */
373export function removeFileArgv(path: string): string[] {
374  return ['/bin/sh', '-c', 'rm -f "$1"', 'plannotator-rm', path]
375}
376
377export function launchDirOf(dataDir: string, sessionId: string, launchId: string): string {
378  const safe = (value: string) => value.replace(/[^A-Za-z0-9._-]/g, '_')
379  return `${dataDir}/claude-code-mod/${safe(sessionId)}/${safe(launchId)}`
380}
381
382export interface ReadyInfo {
383  url: string
384  port: number
385  isRemote: boolean
386  /** What the server shows, in full, as the CLI resolved it (absent from an older CLI). */
387  target?: string | string[]
388  /**
389   * A `--tailscale` session from a CLI that keeps "Ask this session" over the
390   * tailnet (#2166): `ask` true when the machine owner's tab gets it. Absent
391   * from every other session, and from an older CLI.
392   */
393  tailnet?: { ask: boolean }
394}
395
396function readyTargetOf(value: unknown): string | string[] | undefined {
397  if (typeof value === 'string') return value.trim() ? value : undefined
398  if (Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === 'string' && item.trim() !== '')) {
399    return value as string[]
400  }
401  return undefined
402}
403
404/** The first well-formed line of the ready file. */
405export function parseReadyFile(text: string): ReadyInfo | null {
406  for (const line of text.split('\n')) {
407    if (!line.trim()) continue
408    try {
409      const value = JSON.parse(line) as Record<string, unknown>
410      if (typeof value.url === 'string' && typeof value.port === 'number') {
411        const target = readyTargetOf(value.target)
412        const tailnet = value.tailnet
413        const ask = tailnet && typeof tailnet === 'object' && typeof (tailnet as { ask?: unknown }).ask === 'boolean' ? (tailnet as { ask: boolean }).ask : undefined
414        return {
415          url: value.url,
416          port: value.port,
417          isRemote: value.isRemote === true,
418          ...(target !== undefined ? { target } : {}),
419          ...(ask !== undefined ? { tailnet: { ask } } : {}),
420        }
421      }
422    } catch {
423      // A partial line: not ready yet.
424    }
425  }
426  return null
427}
428
429// --- Commands ---------------------------------------------------------------
430
431/** The slash commands the mod runs non-blocking, by the name the user types. */
432export const COMMANDS = {
433  'plannotator-review': {
434    kind: 'review',
435    description: "Open Plannotator's code review UI; your feedback comes back as a message when you send it.",
436    argumentHint: '[directory | PR URL] [--base <ref>] [--diff-type <type>]',
437  },
438  'plannotator-annotate': {
439    kind: 'annotate',
440    description: 'Annotate a file, URL or folder in Plannotator; your annotations come back as a message when you send them.',
441    argumentHint: '<file | URL | folder>',
442  },
443  'plannotator-last': {
444    kind: 'last',
445    description: "Annotate Claude's last message in Plannotator; your annotations come back as a message.",
446    argumentHint: '',
447  },
448} as const satisfies Record<string, { kind: SessionKind; description: string; argumentHint: string }>
449
450export type CommandName = keyof typeof COMMANDS
451
452export function isModCommand(name: string): name is CommandName {
453  return Object.prototype.hasOwnProperty.call(COMMANDS, name)
454}
455
456/** A slash command's typed arguments split like its shell line, or words that are already split (a tool call). */
457export function wordsOf(args: string | readonly string[]): string[] {
458  return typeof args === 'string' ? splitShellWords(args) : [...args]
459}
460
461/** The CLI argv for a command, with the user's words passed through unchanged. */
462export function cliArgvFor(kind: Exclude<SessionKind, 'plan'>, args: string | readonly string[]): string[] {
463  const words = wordsOf(args)
464  switch (kind) {
465    case 'review':
466      return ['plannotator', 'review', ...words]
467    case 'annotate':
468      return ['plannotator', 'annotate', ...words]
469    case 'last':
470      // `last` takes no words but `--tailscale` (the tool's `tailscale`, or a
471      // person who typed it after /plannotator-last).
472      return ['plannotator', 'annotate-last', '--stdin', ...(words.includes('--tailscale') ? ['--tailscale'] : [])]
473  }
474}
475
476const PR_URL = /^https?:\/\/[^\s/]+\/.+\/(?:pull|pull-requests|merge_requests)\/(\d+)\b/i
477
478function baseName(path: string): string {
479  const trimmed = path.replace(/\/+$/, '')
480  return trimmed.slice(trimmed.lastIndexOf('/') + 1) || trimmed
481}
482
483/**
484 * Whether annotate's words (flags ignored) are several file paths, i.e. a
485 * review of several files (the CLI checks they exist; this only reads their
486 * shape, for naming the session and for reading an older CLI's refusal).
487 */
488export function isSeveralFilePaths(words: readonly string[]): boolean {
489  const targets = [...new Set(words.filter((word) => !word.startsWith('-')))]
490  return targets.length > 1 && targets.every(looksLikeFilePath)
491}
492
493/** A review of the session's own working tree, opened with no target words. */
494export const LOCAL_CHANGES_SUBJECT = 'local changes'
495
496/**
497 * The subject a launch takes once its CLI reports the target it opened (the
498 * ready line), or null to keep `typed` (the subject from the typed words).
499 * Annotate and review are named from the target, since the CLI may have
500 * dropped words (a stray `.`, prose beside a file); plan and last keep theirs.
501 * A review typed with no target stays "local changes".
502 */
503export function subjectFromServerTarget(kind: SessionKind, typed: string, target: PlannotatorTarget | undefined): string | null {
504  if (kind === 'plan' || kind === 'last') return null
505  if (kind === 'review' && typed === LOCAL_CHANGES_SUBJECT) return null
506  return plannotatorTargetSubject(kind, target)
507}
508
509/** How the status line, the command output and the plugin turn name a session. */
510export function subjectFor(kind: SessionKind, args: string | readonly string[], version?: number): string {
511  const words = wordsOf(args).filter((word) => !word.startsWith('-'))
512  switch (kind) {
513    case 'plan':
514      return `Plan v${version ?? 1}`
515    case 'last':
516      return "Claude's last message"
517    case 'review': {
518      for (const word of words) {
519        const match = PR_URL.exec(word)
520        if (match) return /merge_requests/i.test(word) ? `MR !${match[1]}` : `PR #${match[1]}`
521      }
522      const directory = words[words.length - 1]
523      return directory ? `changes in ${baseName(directory)}` : LOCAL_CHANGES_SUBJECT
524    }
525    case 'annotate': {
526      // Several file paths open as one review: name it as a bundle.
527      if (isSeveralFilePaths(words)) return plannotatorBundleSubject([...new Set(words)])
528      const target = words.find((word) => /^https?:\/\//i.test(word) || /[./]/.test(word)) ?? words[0]
529      if (!target) return 'document'
530      if (/^https?:\/\//i.test(target)) {
531        try {
532          return new URL(target).host
533        } catch {
534          return target
535        }
536      }
537      return baseName(target)
538    }
539  }
540}
541
542/**
543 * `last`'s subject when the reviewer can pick among several messages: the
544 * feedback may be about an older one (its excerpt rides in the feedback).
545 */
546export const RECENT_MESSAGES_SUBJECT = "Claude's recent messages"
547
548/** The classic `annotate-last` picker's limit (RECENT_MESSAGES_LIMIT in the CLI). */
549export const RECENT_MESSAGES_LIMIT = 25
550/** The CLI's limits on the messages file (`apps/hook/server/host-messages.ts`): raw text per message. */
551export const MAX_PICKER_MESSAGE_BYTES = 2 * 1024 * 1024
552/** The CLI's cap on the whole SERIALIZED file. */
553export const MAX_PICKER_FILE_BYTES = 8 * 1024 * 1024
554/**
555 * What the mod lets the serialized file reach: under the CLI's cap with a
556 * margin. Measured on the JSON as written, since escaping inflates text
557 * (quotes and newlines double, a control character such as ESC becomes
558 * `\u001b`, six bytes).
559 */
560export const PICKER_FILE_BUDGET_BYTES = MAX_PICKER_FILE_BYTES - 256 * 1024
561
562/**
563 * The assistant messages that have text, newest first, at most `limit`.
564 * Consecutive assistant rows (no user row between them) are one response, so
565 * their texts are joined, as the transcript path groups chunks by message id.
566 */
567export function recentAssistantTexts(
568  messages: readonly { role: string; text: string }[],
569  limit: number = RECENT_MESSAGES_LIMIT,
570): string[] {
571  const texts: string[] = []
572  let run: string[] = []
573  const flush = () => {
574    const text = run.join('\n')
575    run = []
576    if (text.trim()) texts.push(text)
577  }
578  for (let index = messages.length - 1; index >= 0 && texts.length < limit; index -= 1) {
579    const message = messages[index]
580    if (!message) continue
581    if (message.role === 'assistant') {
582      if (message.text.trim()) run.unshift(message.text)
583    } else {
584      flush()
585    }
586  }
587  if (texts.length < limit) flush()
588  return texts
589}
590
591export interface PickerMessage {
592  messageId: string
593  text: string
594}
595
596export interface PickerFile {
597  messages: PickerMessage[]
598  /** Exactly what is written to `messages.json`, within PICKER_FILE_BUDGET_BYTES. */
599  json: string
600}
601
602/**
603 * The picker list the CLI reads from `messages.json`: `texts` newest first,
604 * each with an id derived from its content (stable across launches, so a
605 * message keeps its id as newer ones arrive), and the file text itself. The
606 * budget is the serialized size: older messages that would push the file past
607 * it (or are over the CLI's per-message limit) are left out. When the newest
608 * alone does not fit, the list is empty and the launch hands over stdin alone.
609 */
610export async function pickerFile(
611  texts: readonly string[],
612  sha256: (text: string) => Promise<string>,
613  budgetBytes: number = PICKER_FILE_BUDGET_BYTES,
614): Promise<PickerFile> {
615  const encoder = new TextEncoder()
616  const size = (text: string) => encoder.encode(text).length
617  const empty = { messages: [], json: JSON.stringify({ v: 1, messages: [] }) }
618  const picked: PickerMessage[] = []
619  const used = new Map<string, number>()
620  // `{"v":1,"messages":[]}`, then each entry's JSON plus a comma between entries.
621  let total = size(empty.json)
622  for (const [index, text] of texts.entries()) {
623    const fits = size(text) <= MAX_PICKER_MESSAGE_BYTES
624    const base = fits ? `cc-${(await sha256(text)).slice(0, 16)}` : ''
625    const seen = used.get(base) ?? 0
626    const message = { messageId: seen === 0 ? base : `${base}-${seen + 1}`, text }
627    const cost = size(JSON.stringify(message)) + (picked.length > 0 ? 1 : 0)
628    if (!fits || total + cost > budgetBytes) {
629      if (index === 0) return empty
630      continue
631    }
632    total += cost
633    used.set(base, seen + 1)
634    picked.push(message)
635  }
636  return { messages: picked, json: JSON.stringify({ v: 1, messages: picked }) }
637}
638
639/** The command's own output once the server is up. */
640export function openedText(kind: SessionKind, subject: string, url: string, extra?: string): string {
641  const detail = extra ? ` · ${extra}` : ''
642  const second = kind === 'review'
643    ? 'Take your time. Feedback comes back here when you send it.'
644    : 'Your annotations come back here as a message when you send them.'
645  return `Opened ${subject} in Plannotator${detail} · ${url}\n${second}`
646}
647
648/** Startup failure: what the CLI printed, trimmed for the transcript. */
649export function failedText(subject: string, stderr: string, stdout: string, exitCode: number | null): string {
650  const output = (stderr.trim() || stdout.trim()).slice(0, 4000)
651  const code = exitCode === null ? '' : ` (exit ${exitCode})`
652  return output
653    ? `Plannotator could not open ${subject}${code}:\n${output}`
654    : `Plannotator could not open ${subject}${code}.`
655}
656
hooks/mod/plan.ts 155 lines
1/**
2 * Non-blocking plan review: the decisions behind the `tool.call` hook on
3 * ExitPlanMode and the `classic.PermissionRequest` answer. Pure.
4 */
5
6/** Claude Code's plan-mode tool. */
7export const PLAN_TOOL = 'ExitPlanMode'
8
9/** The annotate cap the CLI applies to a plan file it trusts (MAX_ANNOTATABLE_FILE_BYTES). */
10export const MAX_PLAN_FILE_BYTES = 2 * 1024 * 1024
11
12/**
13 * Whether the plan file named by ExitPlanMode may be read instead of its
14 * inline `plan` (the #1667 stale-snapshot fix, mirrored from
15 * `apps/hook/server/claude-plan.ts`): an absolute `.md` path.
16 * The caller also requires a regular file within MAX_PLAN_FILE_BYTES.
17 */
18export function isTrustablePlanPath(path: unknown): path is string {
19  return typeof path === 'string' && path.startsWith('/') && /\.md$/i.test(path)
20}
21
22/** Hash input: trailing whitespace is not a different plan. */
23export function normalizePlanForHash(plan: string): string {
24  return plan.replace(/\s+$/, '')
25}
26
27/** The approval the reviewer gave, waiting for Claude's next ExitPlanMode. */
28export interface PendingApproval {
29  hash: string
30  plan: string
31  permissionMode?: string
32  version: number
33}
34
35/** The open review of this session, if any. */
36export interface OpenPlanReview {
37  launchId: string
38  dir: string
39  version: number
40  revisionSeq: number
41  url?: string
42}
43
44export type PlanCallAction =
45  | { kind: 'pass-approved'; approval: PendingApproval }
46  | { kind: 'revise'; review: OpenPlanReview }
47  | { kind: 'start' }
48
49/** What an ExitPlanMode call does, given the session's plan review state. */
50export function planCallAction(
51  planHash: string,
52  state: { approval: PendingApproval | null; open: OpenPlanReview | null },
53): PlanCallAction {
54  if (state.approval && state.approval.hash === planHash) return { kind: 'pass-approved', approval: state.approval }
55  if (state.open) return { kind: 'revise', review: state.open }
56  return { kind: 'start' }
57}
58
59/**
60 * The approved call's record for the plugin's own PermissionRequest command
61 * hook (#2007). On Team/Enterprise accounts Claude Code seats its built-in
62 * guard (`cc-plugin-sec-default`) above the person's plugins, and it sends
63 * `classic.PermissionRequest` past this mod. The event then reaches the
64 * command hook (`plannotator`), which reads this record and allows the call
65 * instead of opening a second review. Written while the approved call is in
66 * flight, removed when it settles.
67 *
68 * A copy of the CLI's contract (`apps/hook/server/mod-plan-approval.ts`; a
69 * hooks module imports only its own files); `mod-plan-approval.test.ts` keeps
70 * them equal.
71 */
72export const PLAN_APPROVALS_DIR = 'plan-approvals'
73export const PLAN_APPROVAL_RECORD_VERSION = 1
74
75export interface PlanApprovalRecord {
76  v: typeof PLAN_APPROVAL_RECORD_VERSION
77  hash: string
78  plan: string
79  permissionMode?: string
80  at: number
81}
82
83export function planApprovalRecord(approval: PendingApproval, at: number): PlanApprovalRecord {
84  return {
85    v: PLAN_APPROVAL_RECORD_VERSION,
86    hash: approval.hash,
87    plan: approval.plan,
88    ...(approval.permissionMode ? { permissionMode: approval.permissionMode } : {}),
89    at,
90  }
91}
92
93/** The `classic.PermissionRequest` decision that lets the approved plan through. */
94export function approvedPermissionDecision(toolInput: unknown, approval: PendingApproval) {
95  const input = toolInput && typeof toolInput === 'object' ? (toolInput as Record<string, unknown>) : {}
96  return {
97    behavior: 'allow' as const,
98    // Claude Code drops an ExitPlanMode allow without updatedInput (>= 2.1.199);
99    // carry the approved text so execution starts from what the reviewer saw.
100    updatedInput: { ...input, plan: approval.plan },
101    ...(approval.permissionMode
102      ? { updatedPermissions: [{ type: 'setMode' as const, mode: approval.permissionMode, destination: 'session' as const }] }
103      : {}),
104  }
105}
106
107// --- Copy (what Claude reads in the denied ExitPlanMode result) -----------
108
109export function waitingDenyText(version: number, url?: string): string {
110  const where = url ? ` (${url})` : ''
111  return `Plan v${version} is open in Plannotator for the user's review${where}. It is NOT approved. Stay in plan mode and do not implement. End your turn. The user's decision will arrive as a message from the plannotator plugin. Until then you may answer questions, and you may revise the plan by calling ExitPlanMode again.`
112}
113
114export function revisedDenyText(version: number): string {
115  return `Plan v${version} replaced v${version - 1} in the open review. Still not approved. End your turn and wait for the decision.`
116}
117
118export function unchangedDenyText(version: number): string {
119  return `Plan v${version} is unchanged and still in review. It is NOT approved. End your turn and wait for the decision.`
120}
121
122export function decidingDenyText(): string {
123  return 'The user is recording a decision on the plan in Plannotator right now, so this revision was not added. It is NOT approved. End your turn and wait for the decision message from the plannotator plugin.'
124}
125
126export function revisionPendingDenyText(version: number): string {
127  return `Plan v${version} was sent to the open Plannotator review. It is NOT approved. End your turn and wait for the decision.`
128}
129
130/**
131 * Whether a `plannotator claude-mod-plan` launch failed because the CLI is
132 * older than the plugin (the two update separately) and has no such
133 * subcommand: 0.27.11+ answers "Unknown command", and older CLIs read any
134 * unknown subcommand as the classic hook, which finds no hook event on stdin.
135 */
136export function cliLacksModPlan(stderr: string): boolean {
137  return /Unknown command: claude-mod-plan\b/.test(stderr) || /No plan content in hook event/.test(stderr)
138}
139
140/** Logged once per session when the CLI has no non-blocking plan review. */
141export const CLASSIC_PLAN_REVIEW_TEXT =
142  'Your plannotator CLI is older than the Plannotator plugin and has no non-blocking plan review, so plans open in the classic review, which holds this session until you decide. Update the CLI (curl -fsSL https://plannotator.ai/install.sh | bash) and start or resume a session to get non-blocking plan review.'
143
144/**
145 * Sent to Claude when the old CLI refused only after the ExitPlanMode call had
146 * already been told a review was open: nothing is open, so ask for the call again.
147 */
148export const CLASSIC_PLAN_RETRY_TEXT =
149  "The plan review did not open: the user's plannotator CLI is older than the Plannotator plugin and has no non-blocking plan review. The plan is NOT approved. Call ExitPlanMode again with the same plan; it will open in the classic review."
150
151/** Shown in the status line and toasts. */
152export function planWaitingStatus(version: number): string {
153  return `Plan v${version} · waiting for your review`
154}
155
hooks/mod/take-over.ts 45 lines
1/**
2 * Claude running the `plannotator` CLI through Bash, answered by the mod.
3 *
4 * The skill and the tool steer Claude to the `plannotator` tool, but a model
5 * that reaches for `plannotator annotate x.md --gate --json` in Bash would
6 * otherwise block the session on the CLI and give Ask AI a separate AI. When
7 * the command is one the tool can represent (`plannotatorCommandToToolInput`
8 * in tool.ts decides, host-neutral), the `tool.call` hook answers the Bash call
9 * with the tool's own launch and result text; the command never runs. Anything
10 * else (strict gates, pipelines, unknown flags, a dev build run by path) runs
11 * as written.
12 *
13 * Main loop only: a subagent may run in its own cwd or worktree, while the
14 * mod launches in the session's cwd, so its `review` or `annotate notes.md`
15 * would open the wrong diff or file. A subagent's command runs for real.
16 */
17
18import { plannotatorCommandToToolInput, type PlannotatorToolInput } from './tool'
19
20/** Claude Code's shell tool. */
21export const SHELL_TOOL = 'Bash'
22
23/** The tool input a main-loop Bash call's command stands for; null runs it as written. */
24export function shellTakeOver(command: unknown, fromSubagent: boolean): PlannotatorToolInput | null {
25  if (fromSubagent || typeof command !== 'string') return null
26  // The mod publishes over the tailnet: `--tailscale` is taken over too (#2166).
27  return plannotatorCommandToToolInput(command, { tailscale: true })
28}
29
30/** The Bash tool's result record, carrying the tool's text as the command's output. */
31export interface ShellResult {
32  stdout: string
33  stderr: string
34  interrupted: boolean
35}
36
37/** Open through the tool's launch; the tool's text becomes the Bash result, its error a deny. */
38export async function answerShellCall(
39  mod: { runTool(input: unknown): Promise<{ text: string } | { deny: string }> },
40  input: PlannotatorToolInput,
41): Promise<{ result: ShellResult } | { deny: string }> {
42  const answer = await mod.runTool(input)
43  return 'deny' in answer ? { deny: answer.deny } : { result: { stdout: answer.text, stderr: '', interrupted: false } }
44}
45
hooks/mod/tool.ts 868 lines
1/**
2 * The `plannotator` tool's contract, as the Claude Code mod registers it
3 * (`$.tool.register` in register.ts).
4 *
5 * A COPY of packages/shared/plannotator-tool.ts: a hooks module may import
6 * only its own folder. Everything below the CONTRACT marker must stay byte
7 * for byte the same as there; `tool.test.ts` fails when they differ. Edit the
8 * shared file, then paste its contract section here.
9 */
10
11// --- CONTRACT (copied verbatim into apps/hook/hooks/mod/tool.ts) ---
12
13export const PLANNOTATOR_TOOL_NAME = 'plannotator'
14
15export type PlannotatorToolAction = 'annotate' | 'review' | 'last' | 'list' | 'close'
16
17/** The actions that open a review page. */
18export type PlannotatorToolOpenAction = 'annotate' | 'review' | 'last'
19
20export interface PlannotatorToolInput {
21  action: PlannotatorToolAction
22  /**
23   * annotate: one file, folder or URL, or (contract v2) several files as a
24   * list, in the order they should be read. A one-item list is returned as a
25   * plain string and exact duplicates are dropped, so a list here always has
26   * two or more entries. review: a directory or PR URL (string only).
27   */
28  target?: string | string[]
29  gate?: boolean
30  options?: { base?: string; markdown?: boolean }
31  /**
32   * annotate, review, last: serve the page over the user's tailnet (the CLI's
33   * `--tailscale`). Only from a host that parses with `{ tailscale: true }`.
34   */
35  tailscale?: boolean
36  /** close: a session id (`pn-` + 6 hex, as the results name it) or "all". */
37  session?: string
38}
39
40export const PLANNOTATOR_TOOL_DESCRIPTION = [
41  'Open Plannotator, the browser review UI, for the user, and return at once. Also lists and closes the reviews opened in this conversation (by this tool or the user\'s /plannotator-* commands).',
42  '- action "annotate": annotate a file (markdown, text, config, HTML), a folder, or a URL; `target` is required. Pass a list as `target` to review several files together, in the order you want them read. `gate: true` adds an Approve button for an explicit sign-off. `options.markdown: true` converts HTML or a URL to markdown first.',
43  '- action "review": review code changes; `target` is an optional repository directory or a GitHub/GitLab/Bitbucket pull request URL (default: the current repository). `options.base` sets the compare branch or ref (git only). `gate: true` when you wait for the sign-off: a bare Approve reaches you too.',
44  '- action "last": annotate your own last assistant message; no target.',
45  '- action "list": the reviews opened in this conversation that are still open, one line each: session id, what it shows, url, age, state, and how many comments the reviewer has not sent yet.',
46  '- action "close": close a review opened in this conversation that is no longer needed; `session` is its id (pn-...) or "all". Nothing is sent to you, and the reviewer\'s unsent comments stay saved as a draft. Plan reviews are not closed this way: they end with the reviewer\'s decision.',
47  'Opening only opens the page and names its session id (pn-...). The reviewer\'s feedback arrives later as a message in this conversation that names the same id, so end your turn after opening and wait for it. Use this tool instead of running the `plannotator` CLI. Plan review is not done with this tool: it opens by itself when you exit plan mode.',
48].join('\n')
49
50export const PLANNOTATOR_TOOL_INPUT_SCHEMA = {
51  type: 'object',
52  properties: {
53    action: {
54      type: 'string',
55      enum: ['annotate', 'review', 'last', 'list', 'close'],
56      description: 'What to do: open a file/folder/URL to annotate, code changes or a PR to review, or your last message; list your open reviews; close one.',
57    },
58    target: {
59      anyOf: [
60        { type: 'string' },
61        { type: 'array', items: { type: 'string' }, minItems: 1 },
62      ],
63      description: 'annotate: the file, folder or URL (required), or a list of file paths to review together in that order. review: a repository directory or PR URL (optional). Other actions: not used.',
64    },
65    gate: {
66      type: 'boolean',
67      description: 'annotate: add an Approve button for an explicit sign-off. review: deliver a bare Approve too.',
68    },
69    options: {
70      type: 'object',
71      properties: {
72        base: { type: 'string', description: 'review only: the branch or ref to compare against (git).' },
73        markdown: { type: 'boolean', description: 'annotate only: convert an HTML file or URL to markdown before annotating.' },
74      },
75      additionalProperties: false,
76    },
77    session: {
78      type: 'string',
79      description: 'close: the session id (pn-...) of a review opened in this conversation, or "all".',
80    },
81  },
82  required: ['action'],
83  additionalProperties: false,
84} as const
85
86/** The description line a host that publishes over the tailnet adds (see `PLANNOTATOR_TOOL_TAILSCALE_DESCRIPTION`). */
87export const PLANNOTATOR_TOOL_TAILSCALE_LINE =
88  '- `tailscale: true` (annotate, review, last): serve the page over the user\'s tailnet (HTTPS, never public) for their phone or another device; "Ask this session" works there for this computer\'s owner. Only when the user asks for that.'
89
90/**
91 * The description for a host that accepts `tailscale` (the Claude Code mod):
92 * the plain description with the tailscale line after the action lines.
93 */
94export const PLANNOTATOR_TOOL_TAILSCALE_DESCRIPTION = (() => {
95  const lines = PLANNOTATOR_TOOL_DESCRIPTION.split('\n')
96  const lastAction = lines.findIndex((line) => line.startsWith('- action "close"'))
97  return [...lines.slice(0, lastAction + 1), PLANNOTATOR_TOOL_TAILSCALE_LINE, ...lines.slice(lastAction + 1)].join('\n')
98})()
99
100/** The input schema for a host that accepts `tailscale`: the plain schema plus that one property. */
101export const PLANNOTATOR_TOOL_TAILSCALE_INPUT_SCHEMA = {
102  ...PLANNOTATOR_TOOL_INPUT_SCHEMA,
103  properties: {
104    ...PLANNOTATOR_TOOL_INPUT_SCHEMA.properties,
105    tailscale: {
106      type: 'boolean',
107      description: 'annotate, review, last: serve the page over the user\'s tailnet (HTTPS, never public), to open on another device. "Ask this session" works there for the computer owner\'s Tailscale login.',
108    },
109  },
110} as const
111
112/** What a host's parser accepts beyond the plain contract. */
113export interface PlannotatorToolParseOptions {
114  /** Accept `tailscale` (the host can publish over the tailnet). Default false: the field is unknown. */
115  tailscale?: boolean
116}
117
118/**
119 * What a host answers a `tailscale` call with when its Plannotator CLI cannot
120 * serve it: a CLI without `--tailscale`, or one from before "Ask this session"
121 * was kept over the tailnet (its ready line carries no `tailnet` field). The
122 * review is not left open.
123 */
124export const PLANNOTATOR_TOOL_TAILSCALE_UNAVAILABLE_TEXT =
125  'Plannotator did not open: the installed Plannotator is too old to open a review over the tailnet from this tool. Ask the user to update Plannotator (`plannotator update`), or open it without `tailscale` for now.'
126
127/**
128 * Whether a CLI's startup error for a `tailscale` call is an OLDER CLI's
129 * refusal of the flag itself (it read `--tailscale` as a file, an unknown
130 * option, or a flag for another subcommand), never a current CLI's publish
131 * failure: those all start with `--tailscale:` (Tailscale not running, signed
132 * out, the port already routed) and are the reason to show as it is.
133 */
134export function isOlderCliTailscaleRefusal(errorText: string): boolean {
135  if (errorText.includes('--tailscale:')) return false
136  return (
137    /File not found: [^\n]*--tailscale/.test(errorText) ||
138    errorText.includes('--tailscale is only supported with') ||
139    /(?:unknown|unrecognized|unexpected) (?:option|flag|argument)[^\n]*--tailscale/i.test(errorText)
140  )
141}
142
143/** Longest target or base accepted; a real path or URL is far shorter. */
144export const PLANNOTATOR_TOOL_MAX_TEXT = 4096
145
146/**
147 * A session id as every host names it: `pn-` and six lowercase hex digits, a
148 * short alias of the host's own launch id. Hosts resolve an id only among the
149 * reviews their own agent session opened.
150 */
151export const PLANNOTATOR_SESSION_ID_PREFIX = 'pn-'
152
153const SESSION_ID = /^(?:pn-)?([0-9a-f]{6})$/i
154
155/** `pn-3f2a9c` from an id the agent typed (`pn-3F2A9C`, `3f2a9c`), or null when it is not one. */
156export function normalizePlannotatorSessionId(value: string): string | null {
157  const match = SESSION_ID.exec(value.trim())
158  return match ? `${PLANNOTATOR_SESSION_ID_PREFIX}${(match[1] as string).toLowerCase()}` : null
159}
160
161/** The session id for six hex digits a host drew for its launch. */
162export function plannotatorSessionId(hex6: string): string {
163  return `${PLANNOTATOR_SESSION_ID_PREFIX}${hex6.toLowerCase()}`
164}
165
166const TOOL_KEYS = ['action', 'target', 'gate', 'options', 'session']
167const OPTION_KEYS = ['base', 'markdown']
168const ACTIONS: readonly PlannotatorToolAction[] = ['annotate', 'review', 'last', 'list', 'close']
169
170export type PlannotatorToolParse = { ok: true; input: PlannotatorToolInput } | { ok: false; error: string }
171
172function isRecord(value: unknown): value is Record<string, unknown> {
173  return typeof value === 'object' && value !== null && !Array.isArray(value)
174}
175
176/** A string the CLI can take as one argument: no control characters, never read as a flag. */
177function checkWord(name: string, value: unknown): string | null {
178  if (typeof value !== 'string') return `${name} must be a string`
179  if (value.trim() === '') return `${name} must not be empty`
180  if (value.length > PLANNOTATOR_TOOL_MAX_TEXT) return `${name} is longer than ${PLANNOTATOR_TOOL_MAX_TEXT} characters`
181  if (/[\u0000-\u001f\u007f]/.test(value)) return `${name} must not contain control characters or line breaks`
182  if (value.trim().startsWith('-')) return `${name} must not start with "-"`
183  return null
184}
185
186/** Whether the action opens a page (and so takes target, gate, options). */
187export function isPlannotatorToolOpenAction(action: PlannotatorToolAction): action is PlannotatorToolOpenAction {
188  return action === 'annotate' || action === 'review' || action === 'last'
189}
190
191/**
192 * Validates a tool call strictly: unknown keys, wrong types, and a field the
193 * action does not take are errors (a `false` the action ignores is allowed,
194 * since models often fill defaults). The error text is for the model.
195 */
196export function parsePlannotatorToolInput(value: unknown, parseOptions: PlannotatorToolParseOptions = {}): PlannotatorToolParse {
197  const fail = (error: string): PlannotatorToolParse => ({ ok: false, error: `Invalid plannotator call: ${error}.` })
198  if (!isRecord(value)) return fail('the input must be an object')
199  for (const key of Object.keys(value)) {
200    if (!TOOL_KEYS.includes(key) && !(key === 'tailscale' && parseOptions.tailscale === true)) return fail(`unknown field "${key}"`)
201  }
202  const action = value.action
203  if (typeof action !== 'string' || !ACTIONS.includes(action as PlannotatorToolAction)) {
204    return fail('action must be "annotate", "review", "last", "list" or "close"')
205  }
206  const input: PlannotatorToolInput = { action: action as PlannotatorToolAction }
207  const opens = isPlannotatorToolOpenAction(input.action)
208
209  if (value.target !== undefined) {
210    if (!opens || action === 'last') return fail(`action "${action}" takes no target`)
211    if (Array.isArray(value.target)) {
212      if (action !== 'annotate') return fail('a list of targets is for action "annotate" only')
213      if (value.target.length === 0) return fail('target must not be an empty list')
214      const targets: string[] = []
215      for (const [index, item] of value.target.entries()) {
216        const problem = checkWord(`target[${index}]`, item)
217        if (problem) return fail(problem)
218        const trimmed = (item as string).trim()
219        if (!targets.includes(trimmed)) targets.push(trimmed)
220      }
221      input.target = targets.length === 1 ? targets[0] : targets
222    } else {
223      const problem = checkWord('target', value.target)
224      if (problem) return fail(problem)
225      input.target = (value.target as string).trim()
226    }
227  } else if (action === 'annotate') {
228    return fail('action "annotate" needs a target (a file, folder or URL)')
229  }
230
231  if (value.gate !== undefined) {
232    if (typeof value.gate !== 'boolean') return fail('gate must be true or false')
233    if (value.gate && action !== 'annotate' && action !== 'review') return fail('gate is for actions "annotate" and "review" only')
234    if (value.gate) input.gate = true
235  }
236
237  if (value.tailscale !== undefined) {
238    if (typeof value.tailscale !== 'boolean') return fail('tailscale must be true or false')
239    if (value.tailscale && !opens) return fail('tailscale is for actions "annotate", "review" and "last" only')
240    if (value.tailscale) input.tailscale = true
241  }
242
243  if (value.options !== undefined) {
244    const options = value.options
245    if (!isRecord(options)) return fail('options must be an object')
246    for (const key of Object.keys(options)) {
247      if (!OPTION_KEYS.includes(key)) return fail(`unknown option "${key}"`)
248    }
249    const parsed: NonNullable<PlannotatorToolInput['options']> = {}
250    if (options.base !== undefined) {
251      if (action !== 'review') return fail('options.base is for action "review" only')
252      const problem = checkWord('options.base', options.base)
253      if (problem) return fail(problem)
254      if (/\s/.test((options.base as string).trim())) return fail('options.base must not contain spaces')
255      parsed.base = (options.base as string).trim()
256    }
257    if (options.markdown !== undefined) {
258      if (typeof options.markdown !== 'boolean') return fail('options.markdown must be true or false')
259      if (options.markdown && action !== 'annotate') return fail('options.markdown is for action "annotate" only')
260      if (options.markdown) parsed.markdown = true
261    }
262    if (Object.keys(parsed).length > 0) input.options = parsed
263  }
264
265  if (value.session !== undefined) {
266    if (action !== 'close') return fail('session is for action "close" only')
267    if (typeof value.session !== 'string') return fail('session must be a string')
268    if (action === 'close' && value.session.trim().toLowerCase() === 'all') {
269      input.session = 'all'
270    } else {
271      const id = normalizePlannotatorSessionId(value.session)
272      if (!id) return fail('session must be a session id such as "pn-3f2a9c" or "all"')
273      input.session = id
274    }
275  } else if (action === 'close') {
276    return fail('action "close" needs a session (the pn-... id a result named, or "all")')
277  }
278
279  return { ok: true, input }
280}
281
282/** The files of an annotate call, in order (one or several). */
283export function plannotatorToolTargets(input: PlannotatorToolInput): string[] {
284  if (input.target === undefined) return []
285  return Array.isArray(input.target) ? [...input.target] : [input.target]
286}
287
288/**
289 * The arguments the matching slash command would carry (`/plannotator-annotate
290 * <these>`), one argument per element, never re-split. A list of annotate
291 * targets passes a bare word as `./word`, so the CLI reads every entry as a
292 * path. `last` has none but `--tailscale`, and the actions that open nothing
293 * (list, close) have none. `tailscale` becomes `--tailscale`.
294 */
295export function plannotatorToolArgs(input: PlannotatorToolInput): string[] {
296  switch (input.action) {
297    case 'annotate':
298      return [
299        // A list is files named by their paths, so every entry is passed as
300        // one: a bare word becomes `./word`. The CLI then refuses a list with a
301        // missing file instead of reading the bare word as prose.
302        ...(Array.isArray(input.target)
303          ? input.target.map((target) => (looksLikeFilePath(target) || /^https?:\/\//i.test(target) ? target : `./${target}`))
304          : plannotatorToolTargets(input)),
305        ...(input.gate ? ['--gate'] : []),
306        ...(input.options?.markdown ? ['--markdown'] : []),
307        ...(input.tailscale ? ['--tailscale'] : []),
308      ]
309    case 'review':
310      // A review's `gate` is the host's alone (deliver a bare approval as a
311      // message), never passed on: the review page always has Approve, and a
312      // CLI older than `review --gate` refuses the flag.
313      return [
314        ...(input.options?.base ? ['--base', input.options.base] : []),
315        ...(input.tailscale ? ['--tailscale'] : []),
316        ...plannotatorToolTargets(input),
317      ]
318    case 'last':
319      return input.tailscale ? ['--tailscale'] : []
320    case 'list':
321    case 'close':
322      return []
323  }
324}
325
326/**
327 * What a review is OF, in full: the absolute file or folder path, the URL, the
328 * files of a bundle (in review order), the reviewed directory or the PR URL.
329 * Taken from the server that shows (and later submits) the review, never
330 * guessed from the words the agent typed: two files can share a name.
331 */
332export type PlannotatorTarget = string | readonly string[]
333
334/**
335 * The line(s) naming a review's full target: `Target: /abs/path/notes.md`, or
336 * for several files `Targets:` and one `- path` line each. Empty for no target
337 * (the last-message surface has none). Every decision message and the tool's
338 * opened text carry it, so an agent never has to guess which of two
339 * same-named files a decision is about.
340 */
341export function plannotatorTargetLines(target: PlannotatorTarget | undefined): string {
342  if (target === undefined) return ''
343  if (typeof target === 'string') return target.trim() ? `Target: ${target}` : ''
344  const paths = target.filter((path) => path.trim() !== '')
345  if (paths.length === 0) return ''
346  if (paths.length === 1) return `Target: ${paths[0]}`
347  return ['Targets:', ...paths.map((path) => `- ${path}`)].join('\n')
348}
349
350/**
351 * How a session served over the tailnet answers Ask AI: `ask` true when
352 * "Ask this session" answers there for the machine owner's Tailscale login.
353 */
354export interface PlannotatorTailnetOpen {
355  ask: boolean
356}
357
358/** The line the opened text adds for a session served over the tailnet. */
359export function plannotatorTailnetOpenedLine(tailnet: PlannotatorTailnetOpen): string {
360  return tailnet.ask
361    ? 'It is served over the user\'s tailnet (HTTPS, never public): they open the URL on their phone or another device. "Ask this session" answers there only for the Tailscale login that owns this computer.'
362    : 'It is served over the user\'s tailnet (HTTPS, never public): they open the URL on their phone or another device. "Ask this session" is not available on the other device for this review.'
363}
364
365/**
366 * The tool's result once the session is open (`url`) or still starting (no
367 * url). `sessionId` leads it when given; `target` (the full path or URL the
368 * server opened, when known) follows it. `tailnet` adds the line for a page
369 * served over the user's tailnet.
370 */
371export function plannotatorToolOpenedText(
372  subject: string,
373  url: string | undefined,
374  gate: boolean,
375  sessionId?: string,
376  target?: PlannotatorTarget,
377  tailnet?: PlannotatorTailnetOpen,
378): string {
379  const where = url ? `Opened ${subject} in Plannotator: ${url}` : `Plannotator is starting for ${subject}; it opens in the browser when ready.`
380  const outcome = gate
381    ? 'If they approve, an approval message arrives; if they send annotations, the feedback arrives. Closing it sends nothing.'
382    : 'When they send annotations, the feedback arrives. Closing it with nothing to send sends nothing.'
383  const targetLines = plannotatorTargetLines(target)
384  return [
385    ...(sessionId ? [`Session: ${sessionId}`] : []),
386    ...(targetLines ? [targetLines] : []),
387    where,
388    ...(tailnet ? [plannotatorTailnetOpenedLine(tailnet)] : []),
389    'The reviewer is looking at it now. End your turn now and wait: their decision arrives later as a message in this conversation that starts with "Plannotator:".',
390    outcome,
391    'Do not poll, reopen it, or run the plannotator CLI for this session.',
392  ].join('\n')
393}
394
395/**
396 * The outcome a decision heading names for a code review the reviewer posted
397 * straight to the PR platform (GitHub, GitLab, Bitbucket): the same words on
398 * every host that delivers it as a message.
399 */
400export const PLANNOTATOR_OUTCOME_REVIEW_POSTED = 'Review posted'
401
402/**
403 * The first line of every decision message a host delivers: what was
404 * reviewed, its session id, and the outcome (`Feedback · 3 comments`). With a
405 * `target` (the full path, URL or files the SUBMITTING server reviewed) the
406 * heading is followed by its `Target:` line(s), so even a bare approval names
407 * exactly which file it approves.
408 */
409export function plannotatorDecisionHeading(
410  subject: string,
411  sessionId: string | undefined,
412  outcome: string,
413  target?: PlannotatorTarget,
414): string {
415  const heading = `Plannotator: ${subject}${sessionId ? ` (${sessionId})` : ''} — ${outcome}.`
416  const targetLines = plannotatorTargetLines(target)
417  return targetLines ? `${heading}\n${targetLines}` : heading
418}
419
420const PR_URL_PATTERN = /^https?:\/\/[^\s/]+\/.+\/(?:pull|pull-requests|merge_requests)\/(\d+)\b/i
421
422/** How a pull request URL is named (`PR #12`, `MR !12`), or null when the target is not one. */
423export function plannotatorPrSubject(target: PlannotatorTarget | undefined): string | null {
424  if (typeof target !== 'string') return null
425  const match = PR_URL_PATTERN.exec(target)
426  if (!match) return null
427  return /merge_requests/i.test(target) ? `MR !${match[1]}` : `PR #${match[1]}`
428}
429
430/**
431 * The subject a decision is headed with: the launch's own, unless the
432 * decision is about a DIFFERENT pull request than the launch opened (the
433 * reviewer switched PRs in place), which is then named itself.
434 */
435export function plannotatorDecisionSubject(
436  subject: string,
437  launchTarget: PlannotatorTarget | undefined,
438  decisionTarget: PlannotatorTarget | undefined,
439): string {
440  if (decisionTarget === undefined || plannotatorSameTarget(launchTarget, decisionTarget)) return subject
441  return plannotatorPrSubject(decisionTarget) ?? subject
442}
443
444/** A target as a list of trimmed entries, trailing separators dropped. */
445function targetEntries(target: PlannotatorTarget): string[] {
446  return (typeof target === 'string' ? [target] : [...target]).map((value) => value.trim().replace(/[\\/]+$/, ''))
447}
448
449/** Whether two targets name the same thing (a list compares entry by entry, in order). */
450export function plannotatorSameTarget(a: PlannotatorTarget | undefined, b: PlannotatorTarget | undefined): boolean {
451  if (a === undefined || b === undefined) return a === b
452  const left = targetEntries(a)
453  const right = targetEntries(b)
454  return left.length === right.length && left.every((value, index) => value === right[index])
455}
456
457function pathSegments(path: string): string[] {
458  return path.split(/[\\/]+/).filter((segment) => segment !== '')
459}
460
461/**
462 * Subjects that tell open reviews apart. Reviews whose subjects are equal and
463 * whose targets are different paths (two `QUESTIONS.md` in different folders)
464 * are each named by the shortest trailing part of their path, two segments at
465 * least, that none of the others shares (`releases-2026-10-04/QUESTIONS.md`).
466 * A subject that ends in the path's last segment keeps its other words
467 * (`changes in app/web`). Every other subject is returned as is, in order.
468 */
469export function plannotatorDistinctSubjects(
470  reviews: readonly { subject: string; target?: PlannotatorTarget }[],
471): string[] {
472  const subjects = reviews.map((review) => review.subject)
473  const groups = new Map<string, number[]>()
474  reviews.forEach((review, index) => {
475    if (typeof review.target !== 'string' || /^https?:\/\//i.test(review.target)) return
476    const group = groups.get(review.subject) ?? []
477    group.push(index)
478    groups.set(review.subject, group)
479  })
480  for (const [subject, members] of groups) {
481    const paths = members.map((index) => pathSegments(targetEntries(reviews[index]?.target as string)[0] as string))
482    const joined = paths.map((segments) => segments.join('/'))
483    if (new Set(joined).size < 2) continue
484    const tail = (segments: readonly string[], depth: number) => segments.slice(-depth).join('/')
485    members.forEach((index, position) => {
486      const segments = paths[position] as string[]
487      const last = segments[segments.length - 1]
488      if (!last || !subject.endsWith(last)) return
489      let depth = 2
490      while (
491        depth < segments.length &&
492        paths.some((other, at) => joined[at] !== joined[position] && tail(other, depth) === tail(segments, depth))
493      ) {
494        depth += 1
495      }
496      subjects[index] = `${subject.slice(0, subject.length - last.length)}${tail(segments, depth)}`
497    })
498  }
499  return subjects
500}
501
502/** What a host answers a list of several files with when its Plannotator CLI is too old to open them as one review. */
503export const PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT =
504  'Plannotator did not open: the installed Plannotator is too old to open several files at once. Ask the user to update Plannotator to open several files at once, or open them one at a time for now.'
505
506/**
507 * The line a CLI that opens bundles adds to its "Ambiguous annotate
508 * arguments" error (`ANNOTATE_BUNDLE_HINT` in annotate-target.ts; copied here
509 * because this section must stay dependency-free).
510 */
511export const PLANNOTATOR_BUNDLE_HINT_LINE =
512  'To review several files together, pass only their paths: plannotator annotate a.md b.html'
513
514/**
515 * Whether a CLI's startup error for several file paths is an OLDER CLI's
516 * refusal: its ambiguity error without the bundle hint a current CLI adds. A
517 * host that sent a list of paths answers `PLANNOTATOR_TOOL_BUNDLE_UNAVAILABLE_TEXT`
518 * then, instead of showing an error that tells the agent to pick one file.
519 */
520export function isOlderCliBundleRefusal(errorText: string): boolean {
521  return errorText.includes('Ambiguous annotate arguments:') && !errorText.includes(PLANNOTATOR_BUNDLE_HINT_LINE)
522}
523
524/** The file name of a path, for subjects (either separator). */
525function fileNameOf(path: string): string {
526  const trimmed = path.replace(/[\\/]+$/, '')
527  return trimmed.slice(Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\')) + 1) || trimmed
528}
529
530/**
531 * What a review of several files is called wherever one line names it: the
532 * tool's result, the decision heading, the session list. Up to three file
533 * names, then a count of the rest: "3 files: spec.md, mock.html, notes.md",
534 * "5 files: a.md, b.md, c.md +2 more".
535 */
536export function plannotatorBundleSubject(paths: readonly string[]): string {
537  const names = paths.map(fileNameOf)
538  const rest = names.length - 3
539  return `${names.length} files: ${names.slice(0, 3).join(', ')}${rest > 0 ? ` +${rest} more` : ''}`
540}
541
542/**
543 * A subject from the target the CLI reports it opened (the ready line, the
544 * result record), for the kinds whose subject names what was opened:
545 * annotate (the file name, a URL's host, or a bundle's file names) and
546 * review (`PR #12` / `MR !12`, or `changes in <directory>`). Null when the
547 * target names nothing usable; the host then keeps the subject it built from
548 * the typed words, as it must for an older CLI that reports no target. Typed
549 * words are not trusted for this when a target is known: the CLI ignores a
550 * stray `.` or prose words beside a file, so `annotate . a.md` opens a.md.
551 */
552export function plannotatorTargetSubject(kind: 'annotate' | 'review', target: PlannotatorTarget | undefined): string | null {
553  if (target === undefined) return null
554  const entries = (typeof target === 'string' ? [target] : [...target]).filter((entry) => entry.trim() !== '')
555  if (entries.length === 0) return null
556  if (kind === 'annotate' && entries.length > 1) return plannotatorBundleSubject(entries)
557  if (entries.length !== 1) return null
558  const only = entries[0] as string
559  if (kind === 'review') {
560    const pr = plannotatorPrSubject(only)
561    if (pr) return pr
562    if (/^https?:\/\//i.test(only)) return null
563    const name = fileNameOf(only)
564    return name ? `changes in ${name}` : null
565  }
566  if (/^https?:\/\//i.test(only)) {
567    try {
568      return new URL(only).host || only
569    } catch {
570      return only
571    }
572  }
573  return fileNameOf(only) || null
574}
575
576/**
577 * Whether a shell word reads as a file path rather than prose: it has a path
578 * separator, starts with `~`, `.` or `@`, or ends in a file extension. A URL
579 * is not a path. Pure: nothing is looked up on disk.
580 */
581export function looksLikeFilePath(word: string): boolean {
582  if (/^https?:\/\//i.test(word)) return false
583  if (/[\\/]/.test(word) || /^[~.@]/.test(word)) return true
584  return /\.[A-Za-z0-9]{1,12}$/.test(word)
585}
586
587/** One open review, as `list` reports it. */
588export interface PlannotatorSessionSummary {
589  id: string
590  kind: 'plan' | 'annotate' | 'review' | 'last'
591  /** What it shows: the file(s), folder, URL, PR, or "local changes". */
592  subject: string
593  url?: string
594  ageMs: number
595  /** starting: the server is not up yet. open: waiting for the reviewer. decided: the reviewer decided and it is closing. */
596  state: 'starting' | 'open' | 'decided'
597  /** Comments the reviewer wrote and has not sent; null when the server cannot say (an older Plannotator). */
598  unsent: number | null
599}
600
601function ageText(ms: number): string {
602  const minutes = Math.floor(Math.max(0, ms) / 60_000)
603  if (minutes < 1) return 'under a minute'
604  if (minutes < 60) return `${minutes} min`
605  const hours = Math.floor(minutes / 60)
606  if (hours < 48) return `${hours} h`
607  return `${Math.floor(hours / 24)} days`
608}
609
610/** `list`'s result: one line per open review, or a sentence when there is none. */
611export function plannotatorToolListText(sessions: readonly PlannotatorSessionSummary[]): string {
612  if (sessions.length === 0) return 'No open Plannotator reviews from this conversation.'
613  const lines = sessions.map((session) =>
614    [
615      session.id,
616      session.kind,
617      session.subject,
618      session.url ?? 'no url yet',
619      ageText(session.ageMs),
620      session.state,
621      `unsent: ${session.unsent === null ? 'unknown' : session.unsent}`,
622    ].join(' · '),
623  )
624  const plans = sessions.some((session) => session.kind === 'plan')
625  return [
626    `${sessions.length} open Plannotator ${sessions.length === 1 ? 'review' : 'reviews'} from this conversation:`,
627    ...lines,
628    plans
629      ? 'Close one you no longer need with action "close" and its session id. Plan reviews close only with the reviewer\'s decision.'
630      : 'Close one you no longer need with action "close" and its session id.',
631  ].join('\n')
632}
633
634/** How one `close` went, for `plannotatorToolCloseText`. */
635export type PlannotatorCloseOutcome =
636  | { id: string; subject: string; closed: true; unsent: number | null }
637  | { id: string; subject: string; closed: false; reason: 'plan' | 'decided' | 'failed'; detail?: string }
638
639function savedText(unsent: number | null): string {
640  if (unsent === null) return 'any unsent comments stay saved as a draft'
641  if (unsent === 0) return 'no unsent comments'
642  return `${unsent} unsent ${unsent === 1 ? 'comment' : 'comments'} saved as a draft`
643}
644
645/** `close`'s result. Nothing is sent to the agent later for a review it closed. */
646export function plannotatorToolCloseText(outcomes: readonly PlannotatorCloseOutcome[]): string {
647  if (outcomes.length === 0) return 'No open Plannotator reviews from this conversation to close.'
648  const lines = outcomes.map((outcome) => {
649    if (outcome.closed) return `Closed ${outcome.subject} (${outcome.id}): ${savedText(outcome.unsent)}.`
650    switch (outcome.reason) {
651      case 'plan':
652        return `Not closed: ${outcome.subject} (${outcome.id}) is a plan review; it ends with the reviewer's decision.`
653      case 'decided':
654        return `Not closed: ${outcome.subject} (${outcome.id}) was already decided; its decision arrives as a message.`
655      case 'failed':
656        return `Could not close ${outcome.subject} (${outcome.id})${outcome.detail ? `: ${outcome.detail}` : ''}.`
657    }
658  })
659  const closedAny = outcomes.some((outcome) => outcome.closed)
660  return closedAny ? [...lines, 'Nothing more arrives for a review you closed.'].join('\n') : lines.join('\n')
661}
662
663/** `close` naming a session this conversation did not open (or that already ended). */
664export function plannotatorUnknownSessionText(id: string): string {
665  return `No open Plannotator review ${id} from this conversation. Call the plannotator tool with action "list" to see yours.`
666}
667
668/**
669 * The words of `command` when it is ONE simple command a shell would run
670 * without interpreting anything; null otherwise.
671 *
672 * Quoting follows the slash commands' splitter (`splitShellWords`): whitespace
673 * separates, single quotes are literal, double quotes group (a backslash
674 * escapes `"`, `\`, `$` and a backtick inside them), a backslash outside quotes
675 * escapes the next character. Where that splitter tolerates, this refuses:
676 * anything the shell would expand or treat as syntax makes the result null, so
677 * a word here is exactly the argument the program would have received. That
678 * is: an unquoted operator or redirect (`; & | < > ( )`), a line break, `$`
679 * or a backtick outside single quotes, an unquoted glob or brace (`* ? [ { }`),
680 * a `#` that starts a word (a comment), a `~` that starts a word other than
681 * `~` or `~/...` (the CLIs expand those two themselves), and an unterminated
682 * quote.
683 */
684export function simpleShellCommandWords(command: string): string[] | null {
685  const input = command.trim()
686  const words: string[] = []
687  let word = ''
688  let inWord = false
689  let quote: '"' | "'" | null = null
690
691  for (let index = 0; index < input.length; index += 1) {
692    const char = input[index] as string
693
694    if (quote === "'") {
695      if (char === "'") quote = null
696      else word += char
697      continue
698    }
699
700    if (quote === '"') {
701      if (char === '"') {
702        quote = null
703      } else if (char === '\\' && index + 1 < input.length && '"\\$`'.includes(input[index + 1] as string)) {
704        word += input[index + 1]
705        index += 1
706      } else if (char === '$' || char === '`') {
707        return null
708      } else {
709        word += char
710      }
711      continue
712    }
713
714    if (char === "'" || char === '"') {
715      quote = char
716      inWord = true
717      continue
718    }
719
720    if (char === '\\' && index + 1 < input.length) {
721      // A backslash before a line break joins lines: not one simple word.
722      if (input[index + 1] === '\n' || input[index + 1] === '\r') return null
723      word += input[index + 1]
724      inWord = true
725      index += 1
726      continue
727    }
728
729    if (char === '\n' || char === '\r') return null
730
731    if (/\s/.test(char)) {
732      if (inWord) {
733        words.push(word)
734        word = ''
735        inWord = false
736      }
737      continue
738    }
739
740    if (';&|<>()$`*?[{}'.includes(char)) return null
741    if (!inWord && char === '#') return null
742    if (!inWord && char === '~') {
743      const after = input[index + 1]
744      if (after !== undefined && after !== '/' && !/\s/.test(after)) return null
745    }
746
747    word += char
748    inWord = true
749  }
750
751  if (quote) return null
752  if (inWord) words.push(word)
753  return words
754}
755
756/**
757 * Annotate flags for a script that reads the CLI's own channels: the exit
758 * code and stdout record of a strict gate (`--require-approval`,
759 * `--result-file`) or the hook-shaped stdout (`--hook`). A host that starts
760 * the CLI detached and delivers the decision later as a message has no caller
761 * reading any of them, so the reviewer's decision would be lost. Such a host
762 * refuses annotate words carrying one (`scriptOnlyAnnotateFlag`), and the
763 * shell take-over below leaves a command carrying one to run as written.
764 */
765export const SCRIPT_ONLY_ANNOTATE_FLAGS: readonly string[] = ['--require-approval', '--result-file', '--hook']
766
767/** The first script-only annotate flag among the words, or null. */
768export function scriptOnlyAnnotateFlag(words: readonly string[]): string | null {
769  return words.find((word) => SCRIPT_ONLY_ANNOTATE_FLAGS.includes(word)) ?? null
770}
771
772/** What a detached host answers when the user's annotate words carry a script-only flag. */
773export function scriptOnlyAnnotateFlagText(flag: string): string {
774  return (
775    `Plannotator did not open: ${flag} is for scripts that read the CLI's exit code or result file, ` +
776    'and here your decision comes back as a message instead, so nothing would read it. ' +
777    `Run \`plannotator annotate <file> --gate --json ${flag === '--result-file' ? '--result-file <path>' : flag}\` in a terminal, ` +
778    `or drop ${SCRIPT_ONLY_ANNOTATE_FLAGS.join(' / ')} to annotate here.`
779  )
780}
781
782const COMMAND_ACTIONS: Record<string, PlannotatorToolAction> = {
783  annotate: 'annotate',
784  review: 'review',
785  'annotate-last': 'last',
786  last: 'last',
787}
788
789/**
790 * An agent's shell command (a Bash tool call) as the `plannotator` tool call
791 * that opens the same thing, or null when the command is not one to take over.
792 *
793 * A host that can deliver decisions later answers such a command itself,
794 * through the same launch as the tool, instead of running the blocking CLI:
795 * the agent gets the tool's experience (the page opens, the turn ends, the
796 * decision arrives as a message, Ask AI asks this session) even when it reached
797 * for the CLI.
798 *
799 * Taken over: one simple command (see `simpleShellCommandWords`) whose first
800 * word is exactly `plannotator` (the installed binary on PATH; a path such as
801 * `./plannotator` is a dev build and runs for real), with subcommand
802 * `annotate`, `review`, `annotate-last` or `last`, carrying only what the tool
803 * represents: annotate `<target>` (or several targets that all read as file
804 * paths, `looksLikeFilePath`, which become `target: [...]`, a review of
805 * several files) plus `--gate` and `--markdown`; review `[target]` plus
806 * `--base <ref>` and `--gate`; last with no arguments. `--json` is accepted
807 * and dropped (the decision arrives as a message, not on stdout). With
808 * `{ tailscale: true }` (a host that publishes over the tailnet) `--tailscale`
809 * on annotate, review and last becomes `tailscale: true`. The result passes
810 * `parsePlannotatorToolInput` with the same options.
811 *
812 * Everything else is null and runs as written: other subcommands, any other
813 * flag (`--require-approval`, `--result-file`, `--hook`, `--tailscale` for a
814 * host without that option, `--static`, `--app`, `--no-jina`, `--help`, ...),
815 * a repeated flag, several
816 * targets that are not all file paths (or for review), an environment prefix,
817 * and any shell syntax (`cd x && ...`,
818 * pipes, redirects, substitutions), so scripted strict gates keep the CLI.
819 */
820export function plannotatorCommandToToolInput(
821  command: string,
822  parseOptions: PlannotatorToolParseOptions = {},
823): PlannotatorToolInput | null {
824  const words = simpleShellCommandWords(command)
825  if (!words || words.length < 2) return null
826  const program = words[0] as string
827  if (program !== 'plannotator') return null
828  const action = COMMAND_ACTIONS[words[1] as string]
829  if (!action) return null
830
831  const seen = new Set<string>()
832  const targets: string[] = []
833  const call: Record<string, unknown> = { action }
834  const options: Record<string, unknown> = {}
835  const rest = words.slice(2)
836  if (scriptOnlyAnnotateFlag(rest)) return null
837  for (let index = 0; index < rest.length; index += 1) {
838    const word = rest[index] as string
839    if (!word.startsWith('-')) {
840      targets.push(word)
841      continue
842    }
843    if (seen.has(word)) return null
844    seen.add(word)
845    if (word === '--json') continue
846    if (word === '--gate' && (action === 'annotate' || action === 'review')) call.gate = true
847    else if (word === '--markdown' && action === 'annotate') options.markdown = true
848    else if (word === '--tailscale' && parseOptions.tailscale === true) call.tailscale = true
849    else if (word === '--base' && action === 'review') {
850      const value = rest[index + 1]
851      if (value === undefined || value.startsWith('-')) return null
852      options.base = value
853      index += 1
854    } else return null
855  }
856
857  if (targets.length > 1) {
858    // Several targets are taken over only as a review of several files:
859    // annotate, and every word a file path. Anything else (prose around a
860    // path, which the CLI's tolerant resolution reads) runs as written.
861    if (action !== 'annotate' || !targets.every(looksLikeFilePath)) return null
862    call.target = targets
863  } else if (targets.length === 1) call.target = targets[0]
864  if (Object.keys(options).length > 0) call.options = options
865  const parsed = parsePlannotatorToolInput(call, parseOptions)
866  return parsed.ok ? parsed.input : null
867}
868
hooks/mod/bridge.ts 343 lines
1/**
2 * "Ask this session" for Claude Code: the host half of the pull bridge
3 * (protocol: packages/ai/session-bridge-pull.ts; the OpenCode plugin's client
4 * is packages/ai/session-bridge-pull-client.ts, which this mirrors over
5 * `$.http.fetch` because a mod has no Node `fetch`, timers or AbortSignal).
6 *
7 * The mod generates a token per launched server and hands it to the detached
8 * CLI in `PLANNOTATOR_SESSION_BRIDGE_TOKEN` (the CLI takes it out of its env at
9 * startup). Once the server is listening, this loop long-polls
10 * `POST /api/ai/bridge/poll` and posts progress to `/api/ai/bridge/event`, both
11 * to the loopback port with the bearer token and no Origin header.
12 *
13 * A question runs as a real turn: `$.prompt.submit` puts it in the session
14 * (it waits for idle), the turn's streamed text goes back as deltas, and
15 * `turn.complete`'s answer as `done`. Busy = Claude is mid-turn: reported as
16 * `busy`, so the reviewer chooses wait or interrupt; an interrupt aborts the
17 * running turn with `$.turn.abort`, except a question's turn the person typed
18 * into (turns.ts, take-over), which is theirs, and a turn another plugin's
19 * prompt started, which that plugin may be waiting on. Plan review does not block the session
20 * under the mod, so the status is never `blocked`.
21 */
22
23import type { Host } from './host'
24import type { AskSink, TurnTracker } from './turns'
25
26export const BRIDGE_POLL_PATH = '/api/ai/bridge/poll'
27export const BRIDGE_EVENT_PATH = '/api/ai/bridge/event'
28export const BRIDGE_HOST = 'claude-code'
29export const BRIDGE_MODES = 'turn'
30/** Long-poll wait we ask for; below the server's 25 s cap and any fetch timeout. */
31export const BRIDGE_POLL_WAIT_MS = 15_000
32/**
33 * How long to stay away after the server answered `superseded` (another
34 * client, e.g. a second Claude Code process on the same session, polled
35 * after us): 10 s plus up to 5 s of jitter. Polling again at once made the
36 * two clients supersede each other in a busy loop.
37 */
38export const BRIDGE_SUPERSEDED_WAIT_MS = { min: 10_000, jitter: 5_000 } as const
39/** Statuses that mean the server will never take this client: stop for good. */
40export const BRIDGE_REFUSED_STATUSES: readonly number[] = [401, 403, 404, 405, 503]
41/**
42 * Why "Interrupt and ask now" refuses a turn another message took over. Same
43 * text as `SESSION_ASK_TAKEN_OVER_INTERRUPT_TEXT` (packages/ai/session-bridge.ts).
44 */
45export const TAKEN_OVER_INTERRUPT_TEXT =
46  'The session is now answering another message, so Plannotator will not stop it. Ask when it finishes instead.'
47/** Why "Interrupt and ask now" refuses a turn another plugin's prompt started. */
48export const OTHER_PLUGIN_INTERRUPT_TEXT =
49  'The session is answering a message from another plugin, so Plannotator will not stop it. Ask when it finishes instead.'
50
51/** Used when a `taken_over` comes without a message. */
52const TAKEN_OVER_FALLBACK_NOTE =
53  'Another message entered this session while it was answering, so the rest of the reply went to that message.'
54
55/**
56 * A server that does not advertise `taken_over` (poll `features`) reads it as
57 * `failed`, and its UI then replaces the partial answer with the error. Settle
58 * as an answer instead: what streamed, plus the note as its last paragraph.
59 * Mirrors `takenOverFallback` in packages/ai/session-bridge-pull-client.ts.
60 */
61export function takenOverFallback(streamed: string, message: string | undefined): { delta: string; answer: string } {
62  const note = `_${(message || TAKEN_OVER_FALLBACK_NOTE).trim()}_`
63  const delta = streamed ? `\n\n${note}` : note
64  return { delta, answer: `${streamed}${delta}` }
65}
66
67type BridgeCommand =
68  | { type: 'ask'; askId: string; text: string; mode: string }
69  | { type: 'cancel'; askId: string }
70  | { type: 'interrupt'; interruptId: string }
71
72type BridgeEvent =
73  | { type: 'status'; status: 'ready' | 'busy' | 'blocked' | 'gone' }
74  | { type: 'started'; askId: string }
75  | { type: 'delta'; askId: string; text: string }
76  | { type: 'tool'; askId: string; name: string }
77  | { type: 'done'; askId: string; answer: string }
78  | { type: 'error'; askId: string; code: string; message?: string }
79  | { type: 'interrupted'; interruptId: string; ok: boolean; message?: string }
80
81export interface BridgeOptions {
82  host: Host
83  /** e.g. `http://127.0.0.1:4321`; always the loopback literal. */
84  baseUrl: string
85  token: string
86  turns: TurnTracker
87  /** False once the review settled or the session ended: the loop stops. */
88  isLive: () => boolean
89  maxFailures?: number
90}
91
92export function bridgeBaseUrl(port: number): string {
93  return `http://127.0.0.1:${port}`
94}
95
96export function parseBridgeCommands(text: string): { commands: BridgeCommand[]; closing: boolean; superseded: boolean; features: string[] } {
97  try {
98    const body = JSON.parse(text) as { commands?: unknown; closing?: unknown; superseded?: unknown; features?: unknown }
99    const commands = Array.isArray(body.commands)
100      ? body.commands.filter((command): command is BridgeCommand =>
101          !!command && typeof command === 'object' && typeof (command as { type?: unknown }).type === 'string')
102      : []
103    const features = Array.isArray(body.features) ? body.features.filter((feature): feature is string => typeof feature === 'string') : []
104    return { commands, closing: body.closing === true, superseded: body.superseded === true, features }
105  } catch {
106    return { commands: [], closing: false, superseded: false, features: [] }
107  }
108}
109
110/**
111 * Why a bridge loop ended, so the controller knows whether to start another:
112 * - `failures`: the server stopped answering (`maxFailures` in a row; each
113 *   `$.http.fetch` gives up after 30 s, so a sleeping laptop or a paused
114 *   server gets here in about three minutes). Worth a new loop later.
115 * - `refused`: 401/403 (token, not loopback), 404/405 (a CLI without the
116 *   bridge), 503 (AI off). Never retried.
117 * - `closing`: the server is shutting down. Not retried.
118 * - `ended`: the launch is no longer live for this client (settled, closed,
119 *   the session ended, or another Claude Code process watches it now).
120 */
121export interface BridgeEnd {
122  reason: 'failures' | 'refused' | 'closing' | 'ended'
123  status?: number
124  /** At least one poll was answered with 200 during this loop. */
125  connected: boolean
126}
127
128export interface BridgeHandle {
129  /** Runs until the server closes, refuses, stops answering, or the review is no longer live. Never throws. */
130  run(): Promise<BridgeEnd>
131  /** Push a busy/ready change now (from `turn.start` / `turn.complete`), not at the next poll. */
132  pushStatus(): void
133}
134
135export function createBridge(options: BridgeOptions): BridgeHandle {
136  const { host, turns, token } = options
137  const base = options.baseUrl.replace(/\/+$/, '')
138  const headers = { 'content-type': 'application/json', authorization: `Bearer ${token}` }
139  const maxFailures = options.maxFailures ?? 6
140  const seenAsks = new Set<string>()
141  const seenInterrupts = new Set<string>()
142  let outbox: BridgeEvent[] = []
143  let sending: Promise<void> = Promise.resolve()
144  let lastStatus: 'ready' | 'busy' = turns.busy ? 'busy' : 'ready'
145  /** The server knows the `taken_over` code (poll `features`). */
146  let serverTakesTakenOver = false
147
148  const post = async (events: BridgeEvent[]): Promise<void> => {
149    if (events.length === 0) return
150    try {
151      const response = await host.fetch(`${base}${BRIDGE_EVENT_PATH}`, {
152        method: 'POST',
153        headers,
154        body: JSON.stringify(events.length === 1 ? events[0] : { events }),
155      })
156      if (response.status === 409) {
157        // The server no longer runs a question we are answering: stop ours.
158        for (const event of events) {
159          if ('askId' in event) void stopAsk(event.askId)
160        }
161      }
162    } catch {
163      // Best effort; the server re-sends what it needs.
164    }
165  }
166
167  const flush = (): Promise<void> => {
168    const batch = outbox
169    outbox = []
170    sending = sending.then(() => post(batch))
171    return sending
172  }
173
174  const emit = (event: BridgeEvent, immediate = true) => {
175    const last = outbox[outbox.length - 1]
176    if (event.type === 'delta' && last?.type === 'delta' && last.askId === event.askId) {
177      last.text += event.text
178    } else {
179      outbox.push(event.type === 'delta' ? { ...event } : event)
180    }
181    if (immediate) void flush()
182  }
183
184  const stopAsk = async (askId: string) => {
185    const turnId = turns.cancelAsk(askId)
186    if (turnId) await host.abortTurn(turnId).catch(() => undefined)
187  }
188
189  const runAsk = (command: Extract<BridgeCommand, { type: 'ask' }>) => {
190    if (seenAsks.has(command.askId)) return
191    seenAsks.add(command.askId)
192    const askId = command.askId
193    let streamed = ''
194    const sink: AskSink = {
195      delta: (text) => {
196        streamed += text
197        emit({ type: 'delta', askId, text }, false)
198      },
199      tool: (name) => emit({ type: 'tool', askId, name }),
200      done: (answer) => emit({ type: 'done', askId, answer }),
201      error: (code, message) => {
202        if (code === 'taken_over' && !serverTakesTakenOver) {
203          const fallback = takenOverFallback(streamed, message)
204          emit({ type: 'delta', askId, text: fallback.delta }, false)
205          emit({ type: 'done', askId, answer: fallback.answer })
206          return
207        }
208        emit({ type: 'error', askId, code, ...(message ? { message } : {}) })
209      },
210    }
211    if (!turns.beginAsk(askId, command.text, sink)) {
212      emit({ type: 'error', askId, code: 'busy', message: 'Another question is already running in this session.' })
213      return
214    }
215    emit({ type: 'started', askId })
216    host.submit(command.text).catch((error: unknown) => {
217      turns.failAsk(askId, error instanceof Error ? error.message : String(error))
218    })
219  }
220
221  const runInterrupt = async (interruptId: string) => {
222    if (seenInterrupts.has(interruptId)) return
223    seenInterrupts.add(interruptId)
224    const running = turns.runningTurnId
225    if (!running) {
226      emit({ type: 'interrupted', interruptId, ok: true })
227      return
228    }
229    // A question's turn that the person typed into is theirs now: never stopped from Plannotator.
230    if (turns.isTakenOver(running)) {
231      emit({ type: 'interrupted', interruptId, ok: false, message: TAKEN_OVER_INTERRUPT_TEXT })
232      return
233    }
234    // Another plugin's prompt started it: that plugin may be waiting on its answer, so it is never stopped from here.
235    if (turns.isOtherPluginTurn(running)) {
236      emit({ type: 'interrupted', interruptId, ok: false, message: OTHER_PLUGIN_INTERRUPT_TEXT })
237      return
238    }
239    try {
240      await host.abortTurn(running)
241      emit({ type: 'interrupted', interruptId, ok: true })
242    } catch (error) {
243      emit({ type: 'interrupted', interruptId, ok: false, message: error instanceof Error ? error.message : String(error) })
244    }
245  }
246
247  const handle = (command: BridgeCommand) => {
248    switch (command.type) {
249      case 'ask':
250        runAsk(command)
251        break
252      case 'cancel':
253        if (turns.isActiveAsk(command.askId)) void stopAsk(command.askId)
254        else emit({ type: 'error', askId: command.askId, code: 'aborted' })
255        break
256      case 'interrupt':
257        void runInterrupt(command.interruptId)
258        break
259    }
260  }
261
262  const pushStatus = () => {
263    const status: 'ready' | 'busy' = turns.busy ? 'busy' : 'ready'
264    if (status === lastStatus) return
265    lastStatus = status
266    emit({ type: 'status', status })
267  }
268
269  const supersededWait = () => {
270    const jitter = Number.parseInt(host.randomHex(1), 16) / 255
271    return BRIDGE_SUPERSEDED_WAIT_MS.min + Math.round(jitter * BRIDGE_SUPERSEDED_WAIT_MS.jitter)
272  }
273
274  const loop = async (): Promise<BridgeEnd> => {
275    let failures = 0
276    let connected = false
277    while (options.isLive()) {
278      // Deltas are batched per poll round.
279      if (outbox.length > 0) await flush()
280      const status: 'ready' | 'busy' = turns.busy ? 'busy' : 'ready'
281      lastStatus = status
282      let response
283      try {
284        response = await host.fetch(`${base}${BRIDGE_POLL_PATH}`, {
285          method: 'POST',
286          headers,
287          body: JSON.stringify({ status, modes: { turn: true, transient: false }, waitMs: pollWaitFor(turns) }),
288        })
289      } catch {
290        failures += 1
291        if (failures >= maxFailures) return { reason: 'failures', connected }
292        await host.sleep(Math.min(4_000, 500 * 2 ** (failures - 1)))
293        continue
294      }
295      if (BRIDGE_REFUSED_STATUSES.includes(response.status)) return { reason: 'refused', status: response.status, connected }
296      if (!response.ok) {
297        failures += 1
298        if (failures >= maxFailures) return { reason: 'failures', status: response.status, connected }
299        await host.sleep(Math.min(4_000, 500 * 2 ** (failures - 1)))
300        continue
301      }
302      failures = 0
303      connected = true
304      const { commands, closing, superseded, features } = parseBridgeCommands(response.text)
305      serverTakesTakenOver = features.includes('taken_over')
306      for (const command of commands) {
307        host.debug(`bridge ${base}: ${command.type}`)
308        handle(command)
309      }
310      if (closing) return { reason: 'closing', connected }
311      if (superseded) {
312        // Someone else polls this server now. Stay away a while instead of
313        // taking it back at once, which only starts a ping-pong.
314        const wait = supersededWait()
315        host.debug(`bridge ${base}: superseded, polling again in ${wait} ms`)
316        await host.sleep(wait)
317      }
318    }
319    return { reason: 'ended', connected }
320  }
321
322  const run = async (): Promise<BridgeEnd> => {
323    try {
324      return await loop()
325    } catch {
326      return { reason: 'failures', connected: false }
327    } finally {
328      await flush()
329    }
330  }
331
332  return { run, pushStatus }
333}
334
335/**
336 * While our question streams, poll briefly so deltas and status go out
337 * promptly (a mod has no timer that can interrupt a pending fetch); otherwise
338 * wait long.
339 */
340function pollWaitFor(turns: TurnTracker): number {
341  return turns.askInFlight ? 750 : BRIDGE_POLL_WAIT_MS
342}
343