From b660eef77699c4e21854d77410bc81198c17e1e6 Mon Sep 17 00:00:00 2001 From: omartelo Date: Mon, 23 Nov 2026 06:36:42 -0300 Subject: [PATCH 1/2] feat(hooks): turn a subagent call into a lich session through lich's /subagent veto Every harness but opencode 2 asks lich before its own subagent tool runs and turns lich's deny into the harness's own veto, with lich's reason untouched; every failure to get an answer within 10 seconds lets the native subagent run. hooks/veto-subagent.sh serves Claude Code (and Cursor CLI), Codex, Antigravity, Kiro CLI and Crush, and the opencode and omp modules do the same in process. The Claude Code mod's agent-cards and worker answer are retired with it, along with their prompt texts, docs and the footer's worker count. The subagent-cards fixture is read at lich d33b02a8, in no release yet. --- CHANGELOG.md | 38 +- CLAUDE.md | 30 +- README.md | 31 +- docs/agent-cards.md | 195 -------- docs/edit-guard.md | 2 +- docs/mod-answer.md | 93 ---- docs/mod-control.md | 4 +- docs/mod-status.md | 5 +- docs/providers.md | 18 +- docs/subagent-cards.md | 94 ++++ hooks.json | 4 +- hooks/agent-cards.js | 526 ---------------------- hooks/codex-hooks.json | 11 + hooks/crush-hooks.json | 6 + hooks/hooks.json | 10 + hooks/lich.js | 4 - hooks/mod-status.js | 3 +- hooks/prompt-text.js | 145 +----- hooks/status-line.js | 9 +- hooks/veto-subagent.sh | 119 +++++ hooks/win-veto.cmd | 10 + hooks/worker-answer.js | 222 --------- omp/lich.js | 85 +++- opencode/lich.js | 87 +++- tests/agent-cards.engine.test.ts | 143 ------ tests/agent-cards.test.mjs | 676 ---------------------------- tests/contract.mjs | 45 +- tests/fixtures/mod-answer.jsonl | 13 - tests/fixtures/subagent-cards.jsonl | 33 ++ tests/hooks.test.mjs | 26 +- tests/prompt-text.test.mjs | 118 +---- tests/refresh-fixtures.sh | 10 +- tests/status-line.test.mjs | 26 +- tests/subagent.test.mjs | 543 ++++++++++++++++++++++ tests/worker-answer.engine.test.ts | 103 ----- tests/worker-answer.test.mjs | 353 --------------- 36 files changed, 1127 insertions(+), 2713 deletions(-) delete mode 100644 docs/agent-cards.md delete mode 100644 docs/mod-answer.md create mode 100644 docs/subagent-cards.md delete mode 100644 hooks/agent-cards.js create mode 100755 hooks/veto-subagent.sh create mode 100644 hooks/win-veto.cmd delete mode 100644 hooks/worker-answer.js delete mode 100644 tests/agent-cards.engine.test.ts delete mode 100644 tests/agent-cards.test.mjs delete mode 100644 tests/fixtures/mod-answer.jsonl create mode 100644 tests/fixtures/subagent-cards.jsonl create mode 100644 tests/subagent.test.mjs delete mode 100644 tests/worker-answer.engine.test.ts delete mode 100644 tests/worker-answer.test.mjs diff --git a/CHANGELOG.md b/CHANGELOG.md index a598bc9..6f1b9f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,16 +7,36 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -### Changed +Needs the lich release after v0.92.0, the first that answers `/subagent` and +sends the notification envelope. This release is a minor so that an older lich +never installs it. + +### Added -- **A subagent card's report is described as lich's envelope.** The note the - Agent call answers with, in every prompt language, says the worker's report - arrives at the prompt by itself as a ``, - the envelope lich hands every note in, so there is nothing to poll or collect. - It no longer speaks of a `[lich]` note, which lich no longer sends. Needs the - lich release after v0.92.0, the first that sends the notification envelope; - this release is a minor so that an older lich, still sending `[lich]` notes, - never installs it. +- **A subagent call becomes a lich session on every harness but opencode 2.** + Before the agent's own subagent tool runs (Claude Code's `Agent`, Cursor CLI's + `Task`, Codex's `spawn_agent`, `collaborationspawn_agent` and + `collaborationwait_agent`, Antigravity's `invoke_subagent`, Crush's `agent`, + opencode's and oh-my-pi's `task`, and Kiro CLI's `subagent` and + `use_subagent` through lich's own registration), the new + `hooks/veto-subagent.sh`, or the opencode and oh-my-pi module, asks lich. lich + opens the task as a card you can watch and take over, and the call is refused + in the harness's own way with lich's reason, which the model reads. The card's + report arrives at the prompt by itself as a + ``. Which subagent types stay + native is lich's call. When lich does not answer within 10 seconds, or cannot + be reached, the native subagent runs. Codex on Windows runs the hook through + `hooks/win-veto.cmd`, which keeps the veto `win-run.cmd` would drop. + +### Removed + +- **The Claude Code mod no longer opens subagent cards itself.** Its + agent-cards, which answered the `Agent` call as a background agent, and its + worker answer, which posted a worker's last message to `/mod/answer`, are + gone: lich's veto above replaces the first, and lich reads a worker's answer + off its final message itself. Their texts in every prompt language go with + them, and so does the worker count in the prompt footer, which the errands + already counted. ## [0.21.1] - 2026-11-13 diff --git a/CLAUDE.md b/CLAUDE.md index df6e1de..15dd3a4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,14 +16,14 @@ hooks/codex-hooks.json # hook registration, Codex hooks/crush-hooks.json # hook registration, Crush (hand-merged into crush.json) hooks/ # hook scripts (all four run them; only how they are addressed differs) hooks/detail.jq # what a tool call acts on, shared by two of those scripts -hooks/conversation-id.sh # the conversation a payload comes from, sourced by three of them +hooks/conversation-id.sh # the conversation a payload comes from, sourced by four of them +hooks/veto-subagent.sh # the subagent veto: the one hook that blocks, waiting on lich's answer hooks/win-run.cmd # runs one of those scripts on Windows (Codex) +hooks/win-veto.cmd # runs veto-subagent.sh on Windows (Codex), keeping the stdout its veto rides hooks/lich.js # the one module hooks/hooks.json names under `modules`: registers the mods below hooks/mod-control.js # Claude Code mod: lich drives the session -hooks/agent-cards.js # Claude Code mod: a general-purpose subagent runs as a lich session hooks/mod-usage.js # Claude Code mod: the session reports its own context, rate limits and cost hooks/edit-guard.js # Claude Code mod: an edit says which other lich session edited the file -hooks/worker-answer.js # Claude Code mod: a lich subagent worker's last message answers its task hooks/mod-status.js # Claude Code mod: the session's relay errands in the prompt footer hooks/mod-compacting.js # Claude Code mod: the card says when the conversation is being compacted hooks/self-command.js # Claude Code mod: the session runs a built-in slash command the user asked for @@ -64,11 +64,10 @@ Contracts are **canonical in the lich repository** (`docs/hooks/` there); this p - [docs/session-title.md](docs/session-title.md) — the provider's own session title, via `PostToolUse`/`PreInvocation` and `Stop` - [docs/session-touched.md](docs/session-touched.md) — git-status refresh signal via `PostToolUse` (file-mutating tools only) - [docs/mod-control.md](docs/mod-control.md): lich drives a Claude Code session (prompt, abort, model, effort, command) and asks it side questions (ask) through a mod that long-polls for commands and acks each one; Claude Code only, the other harnesses have no mod system -- [docs/agent-cards.md](docs/agent-cards.md): a general-purpose subagent Claude Code starts runs as a lich session, through the `lich open` CLI rather than an HTTP contract; Claude Code only - [docs/mod-usage.md](docs/mod-usage.md): a Claude Code session reports the context window, rate limits and cost it measured itself, through a mod hooking `session.measure`; Claude Code only -- [docs/mod-answer.md](docs/mod-answer.md): a lich subagent worker answers the task it was handed with its turn's final message, through a mod reading the main loop's `classic.Stop` and `turn.complete`; Claude Code only - [docs/mod-status.md](docs/mod-status.md): a Claude Code session shows the relay errands it is part of (owed, out, ready) in its prompt footer, through a mod reading `/mod/status`, which never collects; Claude Code only - [docs/self-command.md](docs/self-command.md): a Claude Code session runs a built-in slash command the user asked it for (`/compact`), queued after the turn, through a mod answering the Skill tool's refusal of a built-in, and lich's `control_session` refusal of the session's own, by queueing the command itself; Claude Code only +- [docs/subagent-cards.md](docs/subagent-cards.md): the agent's own subagent call becomes a lich session, through a pre-tool hook that asks `/subagent` and turns lich's deny into the harness's veto; every harness but opencode 2, Kiro CLI through lich's own registration - [docs/edit-guard.md](docs/edit-guard.md): an edit to a file another lich session edited in the last minutes carries a note naming it, through markers in the checkout's git dir rather than an HTTP contract; Claude Code only - [docs/providers.md](docs/providers.md) — the per-harness map, including what installing on omp takes and what it cannot report @@ -107,8 +106,6 @@ Claude Code mod, handing it a fake `$` and asserting its acks against the mod-control fixtures and its polls against the commands lich sends; [tests/mod-usage.test.mjs](tests/mod-usage.test.mjs) does the same for its usage reports against the mod-usage fixtures, -[tests/worker-answer.test.mjs](tests/worker-answer.test.mjs) for a worker's -answer against the mod-answer fixtures, [tests/mod-status.test.mjs](tests/mod-status.test.mjs) for the footer line it draws from the mod-status response, and [tests/mod-compacting.test.mjs](tests/mod-compacting.test.mjs) for the @@ -118,27 +115,26 @@ fake `$` with an in-memory git dir and asserts the markers it leaves and the note another session's marker adds, and [tests/status-line.test.mjs](tests/status-line.test.mjs) that the mods share one lich line in the prompt footer. -[tests/agent-cards.test.mjs](tests/agent-cards.test.mjs) hands the agent-cards -mod the same kind of fake `$` and asserts the `lich open` argv -it runs, the Agent result it answers each outcome with, and that a call it does -not take, or one lich cannot take, reaches the native agent untouched. [tests/self-command.test.mjs](tests/self-command.test.mjs) does the same for the self-command mod: which Skill calls it takes, that the command runs only after the call is answered, and that `/model` and `/effort` never run. +[tests/subagent.test.mjs](tests/subagent.test.mjs) runs every harness's +subagent veto, the script as each registration spells it and the two modules +in process, against a stub answering with the subagent-cards fixture's +answers: the body each sends for its own call, the veto each turns a deny into +with the reason untouched, and the allow every failure is. [tests/contract.mjs](tests/contract.mjs) is the fixtures, the assertions and the stub, shared so every client answers to the same lines. Node only, no dependencies. [tests/mod-control.engine.test.ts](tests/mod-control.engine.test.ts) and -[tests/agent-cards.engine.test.ts](tests/agent-cards.engine.test.ts) and [tests/mod-usage.engine.test.ts](tests/mod-usage.engine.test.ts) and [tests/mod-status.engine.test.ts](tests/mod-status.engine.test.ts) and -[tests/worker-answer.engine.test.ts](tests/worker-answer.engine.test.ts) and [tests/edit-guard.engine.test.ts](tests/edit-guard.engine.test.ts) and [tests/self-command.engine.test.ts](tests/self-command.engine.test.ts) run the mods under Claude Code's own engine (`claude plugin test .`); they need a `claude` binary, so CI does not run them. The kit does not check a `tool.call` result against the tool's output schema (measured on 2.1.289), so whether -Claude Code accepts the Agent result is a live run's to answer. +Claude Code accepts a mod's tool result is a live run's to answer. The fixtures are vendored in `tests/fixtures/` from lich (`docs/hooks/fixtures/*.jsonl` there) by @@ -157,11 +153,11 @@ commit it pins until a release ships it. endpoint), `tests/lich-ref` pins that merge commit, the plugin release that speaks it is tagged here next, and the lich release that installs it is cut last. -- A hook must never block or fail the user's turn: short timeout, errors swallowed, always exit 0. On Codex the exit code is louder still — `2` on `PermissionRequest` denies the request, so silence and exit 0 are what keep a report an observation. +- A hook must never block or fail the user's turn: short timeout, errors swallowed, always exit 0. The subagent veto is the one hook that blocks, because lich's answer is the decision: it waits 10 seconds at most, and every failure lets the call run. On Codex the exit code is louder still — `2` on `PermissionRequest` denies the request, so silence and exit 0 are what keep a report an observation. - Outside lich (env vars absent) every hook is a no-op with exit 0 — the plugin must be safe to install globally. - A skill must be useful from any working directory: the user runs the agent CLI on their own project, not on the lich checkout. - One script per contract, shared by every provider that runs commands. Registration differs per harness, the report does not — extend a script to read a second transcript format before adding a second script. A harness that runs no commands at all is the one case for a client of its own, which is what `opencode/lich.js` and `omp/lich.js` are; they still send the same payloads to the same endpoints. -- opencode and omp both await their plugin handlers, so neither `lich.js` ever awaits a report or throws — that is their version of "always exit 0". The omp one also subscribes to nothing outside lich: omp loads it on every run on the machine, so the gate has to be in the module. +- opencode and omp both await their plugin handlers, so neither `lich.js` ever awaits a report or throws — that is their version of "always exit 0". The subagent veto is the exception in both, as in the scripts: it awaits lich's answer, and a deny is how each refuses the call (opencode by throwing, omp by returning `{block: true}`). The omp one also subscribes to nothing outside lich: omp loads it on every run on the machine, so the gate has to be in the module. - **A module client names only events it was measured emitting.** A name read off a type declaration is a report that silently never fires, which is worse than an absent feature — the omp `waiting` state is left unreported for exactly this reason. - **The same goes for every other name a registration carries** — an event, a tool a matcher names, a payload field, a plugin-root variable. All of them fail the same way: quietly, on every event, with a green test suite, because a harness that never runs the hook reports nothing to disagree with. - **A name is measured off a real payload, or it is a guess.** Not from a harness you already support, and not from a symbol table or an enum either — those are the *implementation's* names, and something may map them before they reach a hook. Antigravity is the worked example in both directions: its guide says a tool name is the step type lowercased with `CORTEX_STEP_TYPE_` dropped, and the enum's `MCP_TOOL` still arrives as `call_mcp_tool`. Its write tools really are `write_to_file` and `replace_file_content`, which the enum does not contain. Run the turn, print the payload, read the name off it — a matcher built any other way matches nothing, and losing a report costs no error, only the report. @@ -188,6 +184,6 @@ Same standard as the `lich` repository (Keep a Changelog + SemVer). Releases are 1. Move the `[Unreleased]` entries in `CHANGELOG.md` under the new version heading (with date) and refresh the compare links at the bottom. 2. Pick the number by what changed: a release that sends anything lich's contract did not already accept (a new endpoint, header, field or value) bumps the **minor** (the major, from 1.0); anything else bumps the **patch**. lich accepts every release below the next minor of the contract it implements, so a contract change released as a patch reaches a lich that refuses it. A contract change is tagged here once lich has merged it and before the lich release that installs it, since that lich may fetch files only this release ships; an older lich never picks it up, because its ceiling stops below this minor. `docs/hooks/README.md` in lich, Versioning, is the rule. -3. Align `version` in `.claude-plugin/plugin.json` **and** `.codex-plugin/plugin.json` with the tag, and `plugin_version` in each `hooks/report-*.sh` and `PLUGIN_VERSION` in `opencode/lich.js`, `omp/lich.js`, `hooks/mod-control.js`, `hooks/mod-usage.js`, `hooks/mod-status.js`, `hooks/mod-compacting.js` and `hooks/worker-answer.js`, the header every report sends. The suite fails while any of them disagrees with the Claude Code manifest. The root `plugin.json` is not a third one to bump: Antigravity's manifest takes only a `name`, and lich writes its own carrying the tag when it installs a release. +3. Align `version` in `.claude-plugin/plugin.json` **and** `.codex-plugin/plugin.json` with the tag, and `plugin_version` in each `hooks/report-*.sh` and in `hooks/veto-subagent.sh`, and `PLUGIN_VERSION` in `opencode/lich.js`, `omp/lich.js`, `hooks/mod-control.js`, `hooks/mod-usage.js`, `hooks/mod-status.js`, and `hooks/mod-compacting.js`, the header every report sends. The suite fails while any of them disagrees with the Claude Code manifest. The root `plugin.json` is not a third one to bump: Antigravity's manifest takes only a `name`, and lich writes its own carrying the tag when it installs a release. 4. Annotated tag `vX.Y.Z` + push with the tag. 5. `gh release create vX.Y.Z` with the notes taken from the matching `CHANGELOG.md` section. diff --git a/README.md b/README.md index 80afb88..6ea94bc 100644 --- a/README.md +++ b/README.md @@ -6,8 +6,9 @@ The agent side of the [lich](https://github.com/lichdotdev/lich) integration. li - **session start** — persists the agent's session id on the lich session (`SessionStart`/`PreInvocation`) - **session title** — names the card after the session's own title (`Stop`) - **session touched** — refreshes the card's git status right after file-mutating tools (`PostToolUse`) +- **subagent cards** — turns the agent's own subagent call into a lich session, asking lich before the tool runs (`PreToolUse`, or the module's pre-tool event) -The four are what Claude Code, Codex, Antigravity, opencode and omp report. **Crush reports two of them** — its session id and the git-status refresh — because `PreToolUse` is the only event it has, and a state nothing can end is worse on a card than no state. **omp reports all four minus the bell**: no event of its own for "your turn" has been measured yet, so its card shows a spinner while the agent waits on you. [docs/providers.md](docs/providers.md) has the event mapping per harness. +The four reports are what Claude Code, Codex, Antigravity, opencode and omp send. **Crush reports two of them** — its session id and the git-status refresh — because `PreToolUse` is the only event it has, and a state nothing can end is worse on a card than no state. **omp reports all four minus the bell**: no event of its own for "your turn" has been measured yet, so its card shows a spinner while the agent waits on you. [docs/providers.md](docs/providers.md) has the event mapping per harness. On **opencode** under a lich from before it registered its MCP server there, it also carries the other direction: the operations lich offers a session for @@ -28,15 +29,16 @@ refuses its session, naming what to fix. [docs/mod-control.md](docs/mod-control.md) has what it does and which releases run it. No other harness has a mod system, so none of them gets the controls. -The same mod system turns a **general-purpose subagent** Claude Code starts into -a lich session: a card you can watch and steer, working in the asking session's -checkout as a native subagent does, or in a worktree of its own when the -subagent asks for isolation. The Agent call returns at once as a background -subagent, and the session's full report arrives at the asking session's prompt -on its own as a ``: the worker's last message is its report, as a native subagent's is -([docs/mod-answer.md](docs/mod-answer.md)). Explore, Plan and other agent types stay inside Claude Code. [docs/agent-cards.md](docs/agent-cards.md) has the -rules and what happens when lich cannot be reached. Since that subagent shares -the checkout, an edit to a file another lich session edited in the last ten +On every harness here but opencode 2, and on Kiro CLI through lich's own +registration, the agent's **subagent call** becomes a lich session: before the +tool runs, the plugin asks lich, which opens the task as a card you can watch +and steer and refuses the native call with a reason the model reads. The card's +report arrives at the asking session's prompt on its own as a +``. Which subagent types stay native, +such as the read-only explorers, is lich's call, and when lich cannot be reached +the native subagent runs. [docs/subagent-cards.md](docs/subagent-cards.md) has +the veto per harness. Since a card shares the checkout unless the call asked +for a worktree, an edit to a file another lich session edited in the last ten minutes tells the model which session it was and how to reach it ([docs/edit-guard.md](docs/edit-guard.md)). Asked to run a built-in slash command such as `/compact`, the session runs it on itself once its turn ends @@ -64,16 +66,15 @@ hooks/report-tool.sh # session-state hook: the tool a turn is runni hooks/report-session-start.sh # session-start hook hooks/report-title.sh # session-title hook hooks/report-touched.sh # session-touched hook -hooks/lich.js # the Claude Code mods' entry, which registers the seven below +hooks/veto-subagent.sh # subagent-cards hook: lich's veto on a subagent call +hooks/lich.js # the Claude Code mods' entry, which registers the five below hooks/mod-control.js # mod-control client, a Claude Code mod -hooks/agent-cards.js # a general-purpose subagent as a lich session, a Claude Code mod hooks/mod-usage.js # mod-usage client, a Claude Code mod hooks/edit-guard.js # names the other lich session that edited a file, a Claude Code mod -hooks/worker-answer.js # mod-answer client: a lich worker's last message answers its task, a Claude Code mod hooks/mod-status.js # mod-status client: the session's errands in the prompt footer, a Claude Code mod hooks/self-command.js # runs a built-in slash command the user asked the session for, a Claude Code mod -opencode/lich.js # opencode client: all four reports plus the seven tools, one module -omp/lich.js # omp client: the reports, one module +opencode/lich.js # opencode client: all four reports, the subagent veto and the seven tools, one module +omp/lich.js # omp client: the reports and the subagent veto, one module docs/ # client-side docs, one per contract skills/theme/ # theme skill: SKILL.md, template.json, validate.mjs skills/extension/ # extension skill, manual only: SKILL.md, agents/openai.yaml diff --git a/docs/agent-cards.md b/docs/agent-cards.md deleted file mode 100644 index 789fc73..0000000 --- a/docs/agent-cards.md +++ /dev/null @@ -1,195 +0,0 @@ -# Mod: agent cards - -Runs a subagent Claude Code starts as a lich session: a card the user can watch -and steer, where Claude Code would otherwise run the agent hidden inside the -asking session. It follows the native agent's semantics: it works in the asking -session's checkout, or in a worktree of its own when the call asks for -`isolation: "worktree"`. - -The text this mod adds for the agent follows `LICH_PROMPT_LANG`, the prompt language lich exports into every session (English when unset or unknown; catalog in `hooks/prompt-text.js`). - -There is no HTTP contract behind it. It drives the lich CLI the asking session -already has, `$LICH_BIN open`, so what it reads is what that command prints -(`docs/cli.md` in the lich repository: `open --json`, Exit status). - -| client | Claude Code | Codex | Antigravity | opencode | omp | Crush | -|------------------------|-------------------------------------------------------|---------------------|---------------------|---------------------|---------------------|---------------------| -| `hooks/agent-cards.js` | mod, registered by `hooks/lich.js` (`hooks/hooks.json` `modules`) | none: no mod system | none: no mod system | none: no mod system | none: no mod system | none: no mod system | - -It hooks Claude Code's `Agent` tool (`tool.call`). A call is taken only when all -of these hold, and every other one goes on to Claude Code untouched: - -- the model made it on the main loop: `next.origin` is the engine and the call - carries no `agentId`, so another plugin's `$.agent.spawn` and a subagent's own - subagents stay native; -- its `subagent_type` is `general-purpose` or absent, so Explore, Plan, project - and plugin agent types keep their own behaviour, and an unknown type keeps - Claude Code's own error; -- it names no `team_name` and no `isolation: remote`, so a teammate and a - remote agent keep Claude Code's own route; -- under a lich older than `LICH_SUBAGENT_DEPTH` (below), the session is not - itself a worker, so a worker's own subagents stay native instead of opening - cards from cards. That lich starts every `--subagent` session with - `LICH_SUBAGENT_CARDS=off`, which covers a worker in the asking session's - checkout; an isolated call also stays native when the session is on a branch - under `subagent/`, which only this mod opens. A lich that sets the depth - decides how deep cards open from cards through `LICH_SUBAGENT_CARDS` alone, - so a worker below its limit opens cards of its own, from a `subagent/` branch - too; -- the session is interactive (`session.start` saw `isInteractive`), since a - `claude -p` started from a tool inside a lich session inherits its variables; -- `LICH_BIN` and `LICH_SESSION_ID` are set, which is to say the session runs - inside lich; -- `LICH_SUBAGENT_CARDS` is not `off`. lich sets it to `off` in a Claude Code - session it starts while "Subagents as lich sessions" is off in Settings › - Providers › Claude Code, and in a worker at lich's own depth limit for cards - opened from cards, and leaves it out otherwise, so the default is on. A lich - older than `LICH_SUBAGENT_DEPTH` sets it in every session opened with - `--subagent` instead. - A session's environment is fixed when it starts, so turning the setting over - reaches the sessions started after that. When it is `off` in a worker, which - `LICH_SUBAGENT_DEPTH` above `0` marks, the native agent runs with a toast - saying lich keeps that session's subagents native; in any other session it - runs silently. - -`LICH_SUBAGENT_DEPTH` is set by lich on every Claude Code session it starts: -`0` for one nobody opened with `--subagent`, `n` for a worker opened `n` -`--subagent` levels down. The depth limit is lich's; this mod reads the -variable only to tell a worker from a top-level session and an older lich from -a current one. - -A taken call runs: - -1. With `isolation: "worktree"` only, `git branch --show-current` in the - session's directory, for the base. -2. `$LICH_BIN open --kind claude --subagent [--worktree [--base ]] [--model ] --prompt --json`, - given two minutes, the sum of the waits lich's own client allows an open - with a task. `--worktree` and `--base` go only with `isolation: "worktree"`; - without them lich opens the worker in the asking session's directory. - -Nothing runs after that: the delivery `lich open` printed decides the answer. - -| delivery | the Agent call answers | -|-------------------------------|---------------------------------------------------------------------| -| `pending` | `async_launched` at once, plus a note on how the report comes back; the worker is counted in the footer | -| `answered` | `completed`: the report, then the checkout (and branch) it is on | -| `unanswered` | `async_launched`, as for `pending`: a turn that ended unanswered usually left a background command running, and the report still arrives as a `` | -| `unread`, `undelivered` | denied: the task never reached the card | -| a status it does not know | denied, naming the card and its branch | -| the open failed | the native agent runs, with a toast saying why | - -`pending` is the usual case: a worker rarely reports within the open's own -wait. Both results are the Agent tool's own arms, and `agentId` is the worker's -roster name in each. `async_launched` carries the call's description and prompt -and an empty `outputFile`, which is the value Claude Code gives its own agents -that have no output file: there is nothing to read, and without -`canReadOutputFile` Claude Code never shows the model the field. `completed` -carries the worker's checkout in `worktreePath` and `worktreeBranch`, and token -and tool counts of zero because they are the worker's session's, not this one's. -Like a native agent's, its `worktreePath` and `worktreeBranch` are there only -for an isolated call. - -## How it behaves - -- **The call is put to Claude Code's own permission check first.** The mod - passes a call it takes on beneath it (`next` in `tool.call`), where Claude - Code applies its rules, the mode, the dialog and PreToolUse hooks, and opens - the worker only at `agent.spawn`, which Claude Code raises once the call was - allowed and before the native agent or its worktree exist. The mod denies - that spawn and answers the Agent call with lich's outcome. A call refused - there, the user's "no" at the dialog included, never reaches `agent.spawn`: - its refusal stands and lich opens nothing. Both orders measured on Claude - Code 2.1.296. -- **The call runs in the background**, as a background subagent does: once lich - has the task it answers `async_launched` and the asking turn goes on. Parallel - Agent calls run their hooks concurrently, so each opens its own card at once. -- **The report comes back through lich, not Claude Code.** `--subagent` makes - lich hand the worker's whole report to the asking session's prompt as a - `` (through mod-control's `prompt` when the session runs the mod), - so the model has nothing to collect; `wait_for_answer` and `lich wait` still - work. Claude Code's own text for a background agent promises a task - notification and names `SendMessage`, so the result carries a `context` line - the model reads after it: where the worker is (and, without isolation, that - it edits this same checkout), that its report arrives on its own, and that - `send_to_session` or `lich send` reaches it where `SendMessage` cannot. -- **The worker answers by itself.** Its own copy of this plugin posts the final - message of a turn that ends with nothing left running in the background as - its answer ([mod-answer](mod-answer.md)), so lich hands it the task with no - ticket and no reply instructions, as a native subagent gets its prompt.- **Without isolation the worker shares the checkout**, as a native subagent - does: both edit the same files, and nothing keeps their changes apart. With - `isolation: "worktree"` it gets a branch and worktree of its own. -- **It falls back to the native agent only before lich has the task.** Claude - Code runs the native agent in place of any hook that throws, overruns its - budget or lets a `$.process.run` reject, so the module catches every failure - and decides. A task over lich's 8192-byte limit, or an open that failed, runs - natively with a toast saying why, naming the card when one was opened. Esc - while the open is still running denies the call instead, because lich may - already have handed the task over and a native agent beside the worker would - do the work twice; a report that worker sends still arrives as a ``. -- **An isolated worker's branch is named from the call.** The description is slugged the way - lich's own worktree dialog slugs a typed name (2 to 5 words, 10 to 40 - characters, letters and digits in any script), `agent` when nothing is left, - under `subagent/`, plus `-` and the last four letters or digits of the call's id. lich checks out - a branch that already exists as it stands, and the suffix keeps a call from - landing on one. -- **An isolated worker's base is the asking session's branch, as last - committed.** Uncommitted - changes are not in the worker's checkout. On a detached HEAD, or when git - cannot answer, the base is left to lich, which uses the project's current branch. -- **The prompt footer counts the workers still running**, as Claude Code's own - "N agents" hint counts background agents: `lich: N workers` in the lich line - of the footer (`hooks/status-line.js`, see [mod-status.md](mod-status.md)), - cleared at none, and left out while that line shows lich's errands, which - count every worker. Every 5 seconds while any runs, the mod reads - `$LICH_BIN sessions --json`. A worker in this checkout is finished once lich - no longer lists it: lich closes it after it reported and its turn ended - (`lich open --subagent` in lich's docs/cli.md), while a turn it ended with a - command left in the background is done without being finished. An isolated - worker keeps its card after it reported, so a turn lich lists `done` ends it. - A list lich could not give leaves the count as it was until the next read. -- **Esc does not stop a worker, and TaskStop does**, as with a native background - agent. Measured on Claude Code 2.1.289: Esc in the asking session interrupts - its own turn and leaves its background agents running (a second Esc at the - idle prompt too; Claude Code stops them all with its own `ctrl+x ctrl+k`, - pressed twice), and the model stops one with `TaskStop({ task_id })`, the - `agentId` the Agent call answered, which answers - `{ message, task_id, task_type: "local_agent", command }`. The mod takes a - TaskStop whose `task_id` (or the deprecated `shell_id`) is a worker it opened - and is still counting: a worker in this checkout is closed with - `$LICH_BIN close `, having nothing of its own to keep, and an isolated - one has its turn stopped with `$LICH_BIN control abort`, its card and - worktree left for the user. A closed worker's task just ends: lich sends - the asking session no note about it. Either answers TaskStop's own result shape; a - command lich refused denies the call with lich's reason. Any other task id - goes to Claude Code. -- **The worker runs with the permissions lich opens any Claude Code session - with**, not the asking session's mode, so a permission prompt waits on its - card, and lich tells the asking session when the worker is waiting on one. -- **lich files the worker in a folder named after the asking session**, and its - errand never expires. -- **A model the call names is the worker's model**, passed as `--model`. With - none, the worker starts on the model lich opens Claude Code with, not the - asking session's, which a native agent would inherit. - -## Known ceilings - -- **Claude Code only.** No other harness has a mod system, so their subagents - stay inside their CLI. -- **Workflow steps never reach the Agent tool's hook** (measured on 2.1.289), - so they stay native. -- **The result reports no tokens and no tool uses.** Both are counted in the - worker's own session. -- **Claude Code does not track the worker as a task.** It is not in the - background-task list and Claude Code sends no completion notification for it; - the status line and TaskStop above are the mod's, not Claude Code's. So - `ctrl+x ctrl+k` does not stop a worker, and a worker is counted only while - this module remembers it: a reload forgets the count, and TaskStop then goes - to Claude Code, which does not know the id. -- **The status line lags a worker's end by up to 5 seconds**, the period of the - `lich sessions --json` read, and matches a worker by the roster name `lich - open` printed, so a worker renamed in Claude Code is read as finished. -- **Needs a lich that takes `lich open --subagent`.** An older one refuses the - flag, and every subagent runs inside Claude Code with a toast saying why. -- **A reload of the module mid-session forgets that the session is - interactive** until its next `session.start`, and Agent calls run natively - until then. diff --git a/docs/edit-guard.md b/docs/edit-guard.md index 204849f..93c4ac5 100644 --- a/docs/edit-guard.md +++ b/docs/edit-guard.md @@ -11,7 +11,7 @@ dir, and nothing is sent to lich. ## Why -A general-purpose subagent lich opens ([agent-cards.md](agent-cards.md)) works +A subagent lich opens as a card ([subagent-cards.md](subagent-cards.md)) works in the asking session's checkout by default, so two Claude Code sessions can edit the same file at once. Each one only sees the other's change when it reads the file again, and neither knows who made it or that the other may still be at diff --git a/docs/mod-answer.md b/docs/mod-answer.md deleted file mode 100644 index 6bb665e..0000000 --- a/docs/mod-answer.md +++ /dev/null @@ -1,93 +0,0 @@ -# Mod: worker answer - -Client side of the [mod-answer contract](https://github.com/lichdotdev/lich/blob/main/docs/hooks/mod-answer.md) -(the endpoint and the payload are defined in the lich repository; this plugin -only implements them). - -Makes a lich subagent worker (a session opened with `lich open --subagent`, -which is what [agent-cards](agent-cards.md) opens for an Agent call) answer the -task it was handed the way a native subagent does: the final message of its -turn is its result. lich hands such a worker its task with no ticket and no -reply instructions, and answers the errand with what this mod posts. - -| client | Claude Code | Codex | Antigravity | opencode | omp | Crush | -|--------------------------|----------------------------------------------------------|---------------------|---------------------|---------------------|---------------------|---------------------| -| `hooks/worker-answer.js` | mod, registered by `hooks/lich.js`, the `modules` entry | none: no mod system | none: no mod system | none: no mod system | none: no mod system | none: no mod system | - -| event | sent | -|-------------------------------------------|-------------------------------------------------------------| -| `classic.Stop`, then `turn.complete{reason=answer}` | `POST /mod/answer` with `{"session_id", "text"}` | -| `classic.Stop` with a blank message, then `turn.complete{reason=answer}` | `POST /mod/answer` with `{"session_id", "unanswered": "blank"}` | -| `turn.complete{reason=answer}` in a session that never saw a `classic.Stop` | the same two bodies, from the completion's `answer` | - -## How it behaves - -- **Only a worker answers.** It reads `LICH_SUBAGENT_DEPTH` in `session.start`, - which lich sets on every Claude Code session it starts, and reports only when - it is an integer above `0`: a session opened `n` `--subagent` levels down - carries `n`, any other `0`. Under a lich older than that variable it reads - `LICH_SUBAGENT_CARDS` instead and reports only when it is `off`, which that - lich sets on every `--subagent` session. A session the user turned subagent - cards off for carries it too; lich ignores a report from a session with no - subagent errand open. -- **A turn that handed work to the background does not answer.** Its main-loop - `classic.Stop` lists what is still running in `background_tasks` (a shell, a - subagent, a monitor, a workflow); Claude Code resumes in a new turn when that - work finishes, and that turn's `Stop`, with nothing listed, is the one that - answers. -- **A blank turn says so.** One whose final message is blank posts - `unanswered: "blank"`, so the caller hears the errand ended instead of - waiting on it, and only when the turn's own `classic.Stop` lists nothing - running. The plugin reports blank turns only. -- **An aborted turn does not report**: its user took the worker over, and the - turn they start next is the one that answers. -- **A refused or failed turn does not report either**, though the contract has - `unanswered: "refusal"` and `"error"` for them. Measured on Claude Code - 2.1.296, both end through `StopFailure` (a refusal with error - `invalid_request`) and then `turn.complete`, with no `Stop`, and neither - carries `background_tasks`, nor does any mod engine call list them: the mod - cannot tell a failed turn with nothing running from one whose background - work resumes it later and answers then, so a report would answer the errand - twice. Both are pending until Claude Code exposes that list on the failure. -- `turn.complete` is matched once per `reason` (`answer`, `refusal`, - `error`, `aborted`), which keeps the hooks beside mod-control's own - `turn.complete` hook: Claude Code refuses one plugin's second hook on an event - with no matcher. Every one of them drops the `Stop` it read. -- **A worker whose `classic.Stop` is bypassed answers from `turn.complete`.** - Measured on Claude Code 2.1.306: on a machine with managed settings (Team - and Enterprise organizations) the builtin `cc-plugin-sec-default` seats - itself outermost and sends `classic.Stop` on past the plugins a person - installs; the engine marks the mod's hook `skipped` ("bypassed by") and tells - the model, but no mod call says so. The mod infers it from a session that has - not seen a single `classic.Stop`: one main-loop `turn.complete` with reason - `answer` then posts its `answer`, or `unanswered: "blank"` for a blank one. - The bypass follows the settings the session started with, so once a `Stop` - has been seen the Stop rule above holds for the rest of the session. -- **Without a `Stop`, only a subagent can hold the answer back.** There is no - `background_tasks` to read. `$.agent.list()` names the session's subagents - (not its shells, monitors or workflows), and one listed `running` or - `waiting`, or a list that cannot be read, holds the turn's report. A turn - that handed a background shell, monitor or workflow off answers with what it - said when it did, and lich takes the first answer, so the resumed turn's - answer is lost. Pending until the engine exposes the background tasks, or - the bypass, to a mod. -- **A subagent's turn inside the worker does not answer.** `classic.Stop` fires - on the main loop only, and a `turn.complete` that carries an `agentId` is - skipped. -- **A Stop answers only for its own turn.** The text is posted when the - completion's `answer` equals the Stop's `last_assistant_message`, a blank - Stop only beside a blank `answer`, and the Stop is dropped once a completion - read it: an aborted turn fires no Stop, and must not inherit the last one. -- **The text is cut at 16,000 UTF-16 units** and marked `[truncated]`, as an - `ask`'s answer is. -- **The turn is never held up.** The answer is posted beside the chain; one - that fails is dropped, never retried. -- **Outside lich, and in a non-interactive run, it never reports.** - -Measured on Claude Code 2.1.289: `classic.Stop` fires on the main loop before -`turn.complete`, its `last_assistant_message` equals the completion's `answer`, -and its `background_tasks` is `[]` when nothing runs. `classic.SubagentStop` -fires for engine forks too, and a background subagent lists itself as still -running there, which is why only the main loop's `Stop` is read. A worker that -asks with `AskUserQuestion` blocks with no `Stop` until someone answers in its -card. diff --git a/docs/mod-control.md b/docs/mod-control.md index 8337826..343dd96 100644 --- a/docs/mod-control.md +++ b/docs/mod-control.md @@ -20,8 +20,8 @@ applies the commands that come back, and acks each one. A Claude Code mod is a module Claude Code runs inside its own process, listed under `modules` in the same `hooks/hooks.json` that registers the scripts. Both kinds live in one file and both fire. Claude Code takes one entry there, so the -entry is `hooks/lich.js`, which registers this module and -[agent-cards](agent-cards.md). lich refuses to queue a command for a +entry is `hooks/lich.js`, which registers this module and the other mods. +lich refuses to queue a command for a session whose mod is not polling, so on every other harness `lich control` and `control_session` fail at once, naming what to fix, instead of waiting on nothing. diff --git a/docs/mod-status.md b/docs/mod-status.md index ed1cc7d..e39af21 100644 --- a/docs/mod-status.md +++ b/docs/mod-status.md @@ -31,10 +31,7 @@ The line reads `lich: 1 task out, 1 answer to collect`. With all three lists empty the piece is gone. The mods share one lich line, built by `hooks/status-line.js`: the errands, -then the worker count of [agent-cards.md](agent-cards.md), then the note of -[edit-guard.md](edit-guard.md), joined by ` · `. While the errands show, the -worker count is left out: every worker that mod opens is an errand of this -session, so `open` already counts it. The line is drawn dim among the mode +then the note of [edit-guard.md](edit-guard.md), joined by ` · `. The line is drawn dim among the mode labels at the right of the prompt footer, by a `ui.render` hook on `SessionMode` that adds it after Claude Code's own labels. `$.ui.status` is not used: Claude Code draws it as a yellow warning under the prompt, and keeps diff --git a/docs/providers.md b/docs/providers.md index c5c534f..a341e96 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -5,12 +5,8 @@ lich drives an agent CLI inside a PTY and injects the same three variables [hook contracts](https://github.com/lichdotdev/lich/blob/main/docs/hooks/README.md) are therefore provider-agnostic: what changes per provider is only *how the harness registers hooks* and *what its lifecycle events are called*. A Claude -Code session also carries `LICH_BIN`; `LICH_SUBAGENT_DEPTH`, how many -`--subagent` levels down the session was opened (`0` for one nobody opened as a -worker); and `LICH_SUBAGENT_CARDS=off` when "Subagents as lich sessions" is off -in lich's Settings › Providers › Claude Code, or in a worker at lich's depth -limit. The agent-cards mod ([agent-cards.md](agent-cards.md)) reads all three, -and the worker-answer mod ([mod-answer.md](mod-answer.md)) the last two. +Code session also carries `LICH_BIN`, which the mods that drive the lich CLI +read. This repository is one plugin, packaged for each harness it supports: @@ -25,15 +21,15 @@ This repository is one plugin, packaged for each harness it supports: | `hooks/codex-hooks.json` | Codex | hook registration | | `hooks.json` | Antigravity | hook registration, name and place both fixed | | `hooks/crush-hooks.json` | Crush | hook registration, merged by hand | -| `hooks/*.sh` | the four | the reports themselves | +| `hooks/report-*.sh` | the four | the reports themselves | +| `hooks/veto-subagent.sh` | the four, Kiro CLI | the subagent veto ([subagent-cards.md](subagent-cards.md)) | | `hooks/win-run.cmd` | Codex | runs a script on Windows | +| `hooks/win-veto.cmd` | Codex | runs the veto on Windows, keeping its stdout | | `hooks/lich.js` | Claude Code | the one module `hooks/hooks.json` names under `modules`; registers the mods below | | `hooks/mod-control.js` | Claude Code | the mod-control client, a mod | -| `hooks/agent-cards.js` | Claude Code | runs a general-purpose subagent as a lich session, a mod | | `hooks/mod-usage.js` | Claude Code | the mod-usage client, a mod | | `hooks/mod-status.js` | Claude Code | the mod-status client, a mod | | `hooks/edit-guard.js` | Claude Code | names the other lich session that edited a file, a mod | -| `hooks/worker-answer.js` | Claude Code | the mod-answer client: a worker's last message answers its task, a mod | | `hooks/mod-compacting.js` | Claude Code | the session-state `compacting` report, a mod | | `hooks/self-command.js` | Claude Code | runs a built-in slash command the user asked the session for, a mod | | `opencode/lich.js` | opencode | the whole client, as a module | @@ -151,7 +147,9 @@ waits. script and the same argument to that wrapper, which looks for Git Bash — on `PATH`, then at its default install — and always exits 0, bash or no bash. Codex picks `commandWindows` over `command` on Windows and ignores it - everywhere else, so one registration still serves both. + everywhere else, so one registration still serves both. The subagent veto + goes through `hooks/win-veto.cmd` instead, which keeps the script's stdout: + that is where the veto rides, and `win-run.cmd` drops it. ## opencode specifics diff --git a/docs/subagent-cards.md b/docs/subagent-cards.md new file mode 100644 index 0000000..c229731 --- /dev/null +++ b/docs/subagent-cards.md @@ -0,0 +1,94 @@ +# Hook: subagent cards + +Client side of the [subagent-cards contract](https://github.com/lichdotdev/lich/blob/main/docs/hooks/subagent-cards.md) +— the contract (request, answers, timing, the per-provider veto) is defined in +the lich repository; this plugin only implements it. + +When the agent calls its own subagent tool, the pre-tool hook asks lich first. +lich opens the task as a session of its own, a card the user can watch and take +over, and answers with a deny; the hook turns it into the harness's own veto, so +the native subagent never runs and the model reads lich's reason. The worker's +report arrives later at the prompt as a ``. +Which subagent types stay native is lich's call, not the plugin's: every call +to a subagent tool is asked about. + +| Harness | Client | Event | Tool | Veto | +|-------------|--------------------------------|-----------------------------------------|----------------------------------------------------------------------|-------------------------------------------------------------| +| Claude Code | `veto-subagent.sh claude` | `PreToolUse` matcher `Agent\|Task` | `Agent` | `hookSpecificOutput.permissionDecision: "deny"` on stdout | +| Cursor CLI | the Claude Code install's | the same, in the terminal | `Task` | the same | +| Codex | `veto-subagent.sh codex` | `PreToolUse` matcher `spawn_agent\|collaborationspawn_agent\|collaborationwait_agent` | `spawn_agent`, `collaborationspawn_agent` (sealed), `collaborationwait_agent` (a `wait`) | the same JSON as Claude Code | +| Antigravity | `veto-subagent.sh antigravity` | `PreToolUse`, chained after the tool report | `invoke_subagent` | `{"decision":"deny","reason":R}` on stdout, `allow` otherwise | +| Kiro CLI | `veto-subagent.sh kiro` | `preToolUse`, registered by lich | `subagent`, `use_subagent` (`InvokeSubagents`) | exit 2, `R` on stderr | +| Crush | `veto-subagent.sh crush` | `PreToolUse` matcher `^agent$` | `agent` | exit 2, `R` on stderr | +| opencode 1 | `opencode/lich.js` | `tool.execute.before` | `task` | `throw new Error(R)` | +| oh-my-pi | `omp/lich.js` | `tool_call` | `task`, one task per entry of its `tasks` | `return {block: true, reason: R}` | + +`POST /subagent` with the contract's body: `session_id`, `provider_session_id` +(the conversation, as the state reports read it), `nested`, `call`, `tool`, +`tool_use_id`, `tasks[]` of `{title, prompt, type}`, `model`, `sealed`, +`isolation`, `background`, every field present, empty or `false` when the +call does not give it. The token rides an `Authorization: Bearer` header from +the script and `?token=` from the two modules, as in every other report. + +## How it behaves + +- **It blocks, and fails open.** The call waits on lich's answer, 10 seconds at + most, because the answer is the decision. No lich, no `jq` (the script), a + refused connection, a timeout, a status other than 200, a body that is not a + decision or a deny with no reason: the call runs natively. lich closes what it + opened for an answer nobody read. Every registration gives the hook 15 + seconds, so a harness never kills it while lich may still be opening a card. +- **The reason is lich's.** It is written in the session's prompt language and + reaches the model byte for byte; the hook writes no text of its own. +- **A call lich would refuse is not sent.** A spawn with no task, or a task with + a blank prompt, is left native without a request: lich answers it 400, which is + an allow anyway. A Codex v2 spawn is sent sealed with an empty prompt, since + its message is ciphertext; lich answers with a redirect to `open_session`. +- **Nested calls are sent as nested.** Claude Code marks a call from inside a + native subagent with `agent_id`, and opencode a sub-session by its parent; + lich allows both. The other harnesses send `nested: false` and lich tells a + child conversation by `provider_session_id`. +- **Antigravity gets one verdict per call.** Its `PreToolUse` command runs the + tool report and then the veto on the same payload, kept in a shell variable, + and the veto prints the verdict for every tool (`allow` for any that is not + `invoke_subagent`), with an `allow` fallback if the script is missing. How + Antigravity merges two entries' verdicts is not measured, so it is not asked + to. +- **Codex on Windows** runs it through `hooks/win-veto.cmd`, which keeps the + script's stdout: `win-run.cmd` drops it, and a deny lost there would leave a + card and a native subagent on the same task. + +## Registration lich writes + +Kiro CLI and Crush keep their hooks in config lich writes, and lich installs +the files for Antigravity, Kiro CLI and Crush from the release by a list. + +| Harness | Event | Matcher | Command | Timeout | +|-------------|--------------|-----------------------------|-------------------------------------------------|------------------------| +| Kiro CLI | `preToolUse` | `subagent` | `"/hooks/veto-subagent.sh" kiro` | `timeout_ms` 15000 | +| Kiro CLI | `preToolUse` | `use_subagent` | `"/hooks/veto-subagent.sh" kiro` | `timeout_ms` 15000 | +| Crush | `PreToolUse` | `^agent$` | `"/hooks/veto-subagent.sh" crush` | 15 | +| Antigravity | `PreToolUse` | `""` (the plugin's `hooks.json`) | as shipped in `hooks.json` | 15 | + +The files each needs: `hooks/veto-subagent.sh` and `hooks/conversation-id.sh` +for all three; Antigravity's `hooks.json` also runs `hooks/report-tool.sh` and +`hooks/detail.jq` as before. + +## Not measured + +The tool names and the input fields are the contract's table, measured by lich +on 2026-11-22. These were not measured, and each fails to an allow or an empty +field when it is wrong: + +- `tool_use_id` as a payload field outside Claude Code (Codex, Kiro, Crush, the + Claude Code-compatible hook Cursor runs); Antigravity sends none here. +- Kiro's payload envelope (`tool_name`, `tool_input`, `session_id`), where + `use_subagent` keeps its `subagents` (`content.subagents` or top level) and + how it spells the `InvokeSubagents` command. +- How oh-my-pi's `context` joins each task's prompt (here: first, a blank line + after it). +- Cursor CLI's payload, taken to be Claude Code's. +- `win-veto.cmd`, on a Windows machine. + +opencode 2 is left out: its subagent tool is `subagent` and the contract has no +row for it. diff --git a/hooks.json b/hooks.json index 8ed6597..6ed319f 100644 --- a/hooks.json +++ b/hooks.json @@ -23,8 +23,8 @@ "hooks": [ { "type": "command", - "command": "hooks/report-tool.sh; printf '{\"decision\":\"allow\"}'", - "timeout": 5 + "command": "payload=$(cat); printf '%s' \"$payload\" | hooks/report-tool.sh; printf '%s' \"$payload\" | hooks/veto-subagent.sh antigravity || printf '{\"decision\":\"allow\"}'", + "timeout": 15 } ] } diff --git a/hooks/agent-cards.js b/hooks/agent-cards.js deleted file mode 100644 index 92306c3..0000000 --- a/hooks/agent-cards.js +++ /dev/null @@ -1,526 +0,0 @@ -// Runs a general-purpose subagent Claude Code starts as a lich session: a card -// the user can watch and steer, instead of an agent hidden inside this session. -// It works in this session's checkout, as a native subagent does, or in a -// worktree of its own when the call asks for `isolation: "worktree"`. -// Docs: ../docs/agent-cards.md. There is no HTTP contract behind it: it drives -// the lich CLI (`$LICH_BIN open`), whose output and exit codes are docs/cli.md -// in the lich repository. -// -// The call goes through Claude Code's own permission check first (its rules, -// mode, dialog and PreToolUse hooks, all beneath `next` in tool.call), and lich -// opens the worker only at `agent.spawn`, which fires once the call was allowed -// and before the native agent or its worktree exist; the spawn is then denied -// and the Agent call answered with lich's outcome. A call refused there never -// reaches `agent.spawn`, so it opens nothing (measured on 2.1.296). -// -// Once lich has the task the Agent call answers at once, as a background -// subagent does, and nothing here waits on the worker: `--subagent` makes lich -// hand the worker's whole report to this session's prompt as a -// envelope. -// While workers run, the status line counts them from `$LICH_BIN sessions -// --json`, and Claude Code's TaskStop on one is taken here and done by lich. -// -// Claude Code fails a tool.call hook open: one that throws, overruns its budget -// or lets a `$.process.run` reject is skipped and the native agent runs in its -// place (measured on 2.1.289). Every failure is therefore caught here and -// decided: before lich has the task, the native agent runs with a toast saying -// why; once lich may have it, the call is denied, because a native agent beside -// the worker would do the work twice. -// -// Every function that takes `$` is declared at the top level: the loader -// refuses a module that hands `$` to a nested function or keeps it in a variable. - -import { promptLang, say } from "./prompt-text.js" -import { setStatusPart } from "./status-line.js" - -// lich's `promptLimit` (internal/relay). lich checks it only after the session -// was opened, so a task over it would leave an empty card behind. -const PROMPT_LIMIT_BYTES = 8192 - -// `lich open --prompt` waits up to `openCall` (60s) for the session and then -// delivers like a send: `deliverWait` (20s) plus `callSlack` (30s), all in -// internal/cli/cli.go. This bound only has to outlast lich's own. -const OPEN_TIMEOUT_MS = 120000 - -// The value lich writes into a session's environment to keep its subagents -// native: when "Subagents as lich sessions" is off in Settings › Providers › -// Claude Code, and in a worker at lich's own depth limit for cards opened from -// cards. A lich older than LICH_SUBAGENT_DEPTH writes it into every worker. -const CARDS_OFF = "off" - -// The bounds lich's own worktree dialog slugs a typed name with -// (`toBranchName`, frontend/src/lib/git/branch-name.ts there), so a branch -// opened here reads like one a person named. -const MIN_WORDS = 2 -const MAX_WORDS = 5 -const MIN_CHARS = 10 -const MAX_CHARS = 40 -const FALLBACK_SLUG = "agent" -// Marks a worker's branch. Under a lich older than LICH_SUBAGENT_DEPTH, the mod -// inside an isolated worker reads it to leave its own subagents native instead -// of opening cards from cards; a lich that sets the depth decides that alone, -// through LICH_SUBAGENT_CARDS. -const WORKER_BRANCH_PREFIX = "subagent/" - -// How often the status line asks lich which workers still run. Claude Code's -// own "N agents" hint moves as each agent ends; a worker's end reaches lich, not -// this session, so it is read from `lich sessions --json`, one short run of the -// CLI per period while any worker runs. -const WORKER_POLL_MS = 5000 - -// The end of the Agent call's id makes each branch new: lich checks out an -// existing branch as it stands, so a bare slug could land on someone's work. -const SUFFIX_CHARS = 4 - -/** - * @typedef {import('claude-code').EngineInterface} Engine - * @typedef {{ ticket: string, target: string, status: string, answer: string }} Report - * @typedef {{ label: string, name: string, path: string, delivery?: Report }} Opened - * @typedef {{ label: string, name: string, description: string, shared: boolean }} Worker - * @typedef {{ call: AgentCall, lich: string, base: string, lang: string, answer?: object }} Claim - * @typedef {{ interactive: boolean, workers: Map, watching: boolean, lich: string, - * claims: Map }} State - * @typedef {{ label: string, name: string, state: string }} Peer - * @typedef {{ tool: "Agent", tool_use_id: string, agentId?: string, description: string, prompt: string, - * subagent_type?: string, model?: string, team_name?: string, isolation?: string }} AgentCall - */ - -/** @param {unknown} error */ -function messageOf(error) { - return error instanceof Error ? error.message : String(error) -} - -/** - * A call the model made on the main loop for a general-purpose agent, in an - * interactive session. Another plugin's `$.agent.spawn`, a subagent's own - * call, a typed agent and a teammate keep their native behaviour. - * - * @param {AgentCall} e - * @param {{ origin: { plugin: string } }} next - * @param {State} state - */ -function isDelegable(e, next, state) { - const isModelOnMainLoop = next.origin.plugin === "engine" && e.agentId === undefined - const isGeneralPurpose = e.subagent_type === undefined || e.subagent_type === "general-purpose" - const isLocal = e.team_name === undefined && e.isolation !== "remote" - return state.interactive && isModelOnMainLoop && isGeneralPurpose && isLocal -} - -/** @param {string} text */ -function slugOf(text) { - const words = text - .toLowerCase() - .replace(/[^\p{L}\p{N}]+/gu, " ") - .trim() - .split(/\s+/) - .filter(Boolean) - /** @type {string[]} */ - const picked = [] - let length = 0 - for (const word of words) { - const grown = length === 0 ? word.length : length + 1 + word.length - const hasMinimum = picked.length >= MIN_WORDS && length >= MIN_CHARS - if (picked.length >= MAX_WORDS || (grown > MAX_CHARS && hasMinimum)) break - picked.push(word) - length = grown - } - return picked.join("-").slice(0, MAX_CHARS).replace(/-+$/, "") -} - -/** @param {AgentCall} e */ -function branchFor(e) { - const suffix = e.tool_use_id.replace(/[^A-Za-z0-9]/g, "").slice(-SUFFIX_CHARS).toLowerCase() - return `${WORKER_BRANCH_PREFIX}${slugOf(e.description ?? "") || FALLBACK_SLUG}-${suffix}` -} - -/** - * The branch the asking session is on, so the worker starts from its work and - * not from the main checkout's branch; "" on a detached HEAD or when git - * cannot answer, which leaves the base to lich. - * - * @param {Engine} $ - */ -async function currentBranch($) { - try { - const { exitCode, stdout } = await $.process.run(["git", "branch", "--show-current"]) - return exitCode === 0 ? stdout.trim() : "" - } catch { - // A rejection here would fail the whole hook open; lich's default base is the answer instead. - return "" - } -} - -/** @param {string} stdout */ -function parsedOrUndefined(stdout) { - try { - return JSON.parse(stdout) - } catch { - return undefined - } -} - -/** - * Opens the worker and hands it the task. Throws when the task did not reach - * it, with lich's own reason. - * - * @param {Engine} $ - * @param {string} lich - * @param {AgentCall} e - * @param {string} branch "" opens the worker in this session's checkout - * @param {string} base - * @returns {Promise} - */ -async function openWorker($, lich, e, branch, base) { - const argv = [ - lich, "open", "--kind", "claude", "--subagent", - ...(branch ? ["--worktree", branch] : []), - ...(base ? ["--base", base] : []), - ...(e.model ? ["--model", e.model] : []), - "--prompt", e.prompt, "--json", - ] - const { exitCode, stdout, stderr } = await $.process.run(argv, { timeoutMs: OPEN_TIMEOUT_MS }) - /** @type {Opened | undefined} */ - const opened = parsedOrUndefined(stdout) - const reason = stderr.trim() || `lich open exited ${exitCode}` - if (opened === undefined) throw new Error(reason) - if (opened.delivery === undefined) throw new Error(`the task did not reach "${opened.label}": ${reason}`) - return /** @type {Opened & { delivery: Report }} */ (opened) -} - -/** - * The Agent tool's `async_launched` arm, plus what the model reads after it. - * Claude Code's own text for this arm promises a task notification and points - * at SendMessage, and neither reaches a lich session, so `context` says how the - * report really comes back. `outputFile` is "", Claude Code's own value for an - * agent with no output file: without `canReadOutputFile` the model is never - * shown it. - * - * @param {AgentCall} e - * @param {Opened} opened - * @param {string} branch - * @param {string} lang - */ -function backgrounded(e, opened, branch, lang) { - const where = branch - ? say(lang, "whereBranch", { branch, path: opened.path }) - : say(lang, "whereShared", { path: opened.path }) - return { - result: { - status: /** @type {const} */ ("async_launched"), - agentId: opened.name, - description: e.description, - prompt: e.prompt, - outputFile: "", - }, - context: [say(lang, "backgrounded", { label: opened.label, where })], - } -} - -/** - * The Agent tool's `completed` arm, which Claude Code checks a hook's result - * against. The worker's tokens and tools are its own session's, so none are - * counted here; a worker in this checkout names no worktree, as a native agent - * without isolation does. - * - * @param {AgentCall} e - * @param {Opened} opened - * @param {string} branch - * @param {string} text - * @param {number} durationMs - */ -function completed(e, opened, branch, text, durationMs) { - return { - status: /** @type {const} */ ("completed"), - agentId: opened.name, - content: [{ type: /** @type {const} */ ("text"), text }], - totalToolUseCount: 0, - totalDurationMs: durationMs, - totalTokens: 0, - usage: { - input_tokens: 0, - output_tokens: 0, - cache_creation_input_tokens: null, - cache_read_input_tokens: null, - server_tool_use: null, - service_tier: null, - cache_creation: null, - }, - prompt: e.prompt, - ...(branch ? { worktreePath: opened.path, worktreeBranch: branch } : {}), - } -} - -/** - * @param {AgentCall} e - * @param {Opened} opened - * @param {string} branch - * @param {Report} report - * @param {number} durationMs - * @param {string} lang - */ -function answerFor(e, opened, branch, report, durationMs, lang) { - switch (report.status) { - // A worker whose turn ended unanswered is usually still at it: it left a - // command running in the background and resumes when it finishes, and its - // report still arrives as a . - case "pending": - case "unanswered": - return backgrounded(e, opened, branch, lang) - case "answered": { - const where = say(lang, branch ? "completedBranch" : "completedShared", { - branch, - path: opened.path, - label: opened.label, - }) - return { result: completed(e, opened, branch, `${report.answer}\n\n${where}`, durationMs) } - } - case "unread": - case "undelivered": - return { deny: say(lang, "denyNeverReached", { label: opened.label, status: report.status }) } - default: - return { - deny: say(lang, "denyAnswered", { - status: report.status, - label: opened.label, - branchPart: branch ? `, ${say(lang, "onBranch", { branch })}` : "", - }), - } - } -} - -/** - * A worker lich opened with `--subagent`, `depth` levels below a session nobody - * opened as one. - * - * @param {string | undefined} depth LICH_SUBAGENT_DEPTH - */ -function isWorkerDepth(depth) { - const levels = Number(depth) - return Number.isInteger(levels) && levels > 0 -} - -/** - * @param {Engine} $ - * @param {AgentCall} e - * @param {(e: AgentCall) => Promise} next - * @param {string} reason - */ -function runNatively($, e, next, reason) { - $.ui.toast(`lich: ran "${e.description}" as a Claude Code subagent: ${reason}`) - return next(e) -} - -/** - * @param {Engine} $ - * @param {State} state - * @param {AgentCall} e - * @param {any} next - */ -async function runAsSession($, state, e, next) { - if (!isDelegable(e, next, state)) return next(e) - const [lich, session, cards, depth, langTag] = await Promise.all([ - $.env.get("LICH_BIN"), - $.env.get("LICH_SESSION_ID"), - $.env.get("LICH_SUBAGENT_CARDS"), - $.env.get("LICH_SUBAGENT_DEPTH"), - $.env.get("LICH_PROMPT_LANG"), - ]) - const lang = promptLang(langTag) - if (!lich || !session) return next(e) - if (cards === CARDS_OFF) { - if (!isWorkerDepth(depth)) return next(e) - return runNatively($, e, next, "this session is itself a lich subagent card, and lich keeps its subagents inside it") - } - const bytes = new TextEncoder().encode(e.prompt).length - if (bytes > PROMPT_LIMIT_BYTES) { - return runNatively($, e, next, `the task is ${bytes} bytes, over lich's ${PROMPT_LIMIT_BYTES}`) - } - - const isolated = e.isolation === "worktree" - const base = isolated ? await currentBranch($) : "" - if (depth === undefined && base.startsWith(WORKER_BRANCH_PREFIX)) return next(e) - /** @type {Claim} */ - const claim = { call: e, lich, base, lang } - state.claims.set(e.tool_use_id, claim) - try { - const native = await next(e) - return claim.answer ?? native - } finally { - state.claims.delete(e.tool_use_id) - } -} - -/** - * The spawn of an Agent call `runAsSession` claimed, reached only once Claude - * Code allowed the call: opens the worker in its place and keeps the answer for - * the call. Before lich has the task the native agent starts instead. - * - * @param {Engine} $ - * @param {State} state - * @param {{ tool_use_id: string }} e - * @param {any} next - */ -async function openInPlaceOfSpawn($, state, e, next) { - const claim = state.claims.get(e.tool_use_id) - if (claim === undefined) return next(e) - const { call, lich, base, lang } = claim - const startedMs = await $.clock.now() - const branch = call.isolation === "worktree" ? branchFor(call) : "" - /** @type {Opened & { delivery: Report }} */ - let opened - try { - opened = await openWorker($, lich, call, branch, base) - } catch (error) { - if (!next.signal.aborted) return runNatively($, call, () => next(e), messageOf(error)) - claim.answer = { - deny: say(lang, "denyInterrupted", { - branchPart: branch ? ` ${say(lang, "onBranch", { branch })}` : "", - }), - } - return claim.answer - } - claim.answer = answerFor(call, opened, branch, opened.delivery, (await $.clock.now()) - startedMs, lang) - if (opened.delivery.status === "pending") trackWorker($, state, lich, opened, call, branch) - return { deny: `lich runs this agent as the session "${opened.label}"` } -} - -/** - * Shows how many workers this session waits on in the footer's lich line, as - * Claude Code's own hint does for its background agents, and clears it at none. - * - * @param {Engine} $ - * @param {State} state - */ -function showWorkers($, state) { - const count = state.workers.size - setStatusPart("workers", count === 0 ? undefined : `${count} worker${count === 1 ? "" : "s"}`) - $.ui.invalidate("ui.render") -} - -/** - * Keeps one watch running while any worker does. - * - * @param {Engine} $ - * @param {State} state - */ -function watchWorkers($, state) { - if (state.watching || state.workers.size === 0) return - state.watching = true - $.clock.after(WORKER_POLL_MS, () => refreshWorkers($, state)) -} - -/** - * A worker in this checkout still runs while lich lists it: lich closes one - * once it reported, and a turn it ended with a command left in the background - * is done without being finished. An isolated worker keeps its card after it - * reported, so for it a done turn is the end. - * - * @param {Worker} worker - * @param {Peer[]} peers - */ -function stillRuns(worker, peers) { - const listed = peers.find((p) => p.name === worker.name) - return listed !== undefined && (worker.shared || listed.state !== "done") -} - -/** - * Drops the workers lich lists as finished. A list lich could not give leaves - * the count as it is until the next period. - * - * @param {Engine} $ - * @param {State} state - */ -async function refreshWorkers($, state) { - state.watching = false - try { - const { exitCode, stdout } = await $.process.run([state.lich, "sessions", "--json"]) - /** @type {Peer[] | undefined} */ - const peers = exitCode === 0 ? parsedOrUndefined(stdout) : undefined - const before = state.workers.size - if (Array.isArray(peers)) { - for (const [id, worker] of state.workers) { - if (!stillRuns(worker, peers)) state.workers.delete(id) - } - } - if (state.workers.size !== before) showWorkers($, state) - } catch { - // A rejection here reaches no hook; the next period asks again. - } - watchWorkers($, state) -} - -/** - * @param {Engine} $ - * @param {State} state - * @param {string} lich - * @param {Opened} opened - * @param {AgentCall} e - * @param {string} branch - */ -function trackWorker($, state, lich, opened, e, branch) { - state.lich = lich - state.workers.set(opened.name, { label: opened.label, name: opened.name, description: e.description, shared: !branch }) - showWorkers($, state) - watchWorkers($, state) -} - -/** - * Claude Code's TaskStop for a worker this mod opened: Esc in this session - * leaves a background agent running, and TaskStop is how the model stops one - * (both measured on 2.1.289). A worker in this checkout is closed, having - * nothing of its own to keep; an isolated one has its turn stopped, and its - * card and worktree stay for the user. Any other task goes to Claude Code. - * - * @param {Engine} $ - * @param {State} state - * @param {{ tool: "TaskStop", task_id?: string, shell_id?: string }} e - * @param {any} next - */ -async function stopWorker($, state, e, next) { - const id = e.task_id ?? e.shell_id ?? "" - const worker = state.workers.get(id) - if (worker === undefined) return next(e) - const lang = promptLang(await $.env.get("LICH_PROMPT_LANG")) - const argv = worker.shared - ? [state.lich, "close", worker.name] - : [state.lich, "control", worker.name, "abort"] - let outcome - try { - outcome = await $.process.run(argv) - } catch (error) { - return { deny: say(lang, "denyStopFailed", { label: worker.label, reason: messageOf(error) }) } - } - if (outcome.exitCode !== 0) { - const reason = outcome.stderr.trim() || say(lang, "lichExited", { code: outcome.exitCode }) - return { deny: say(lang, "denyStopFailed", { label: worker.label, reason }) } - } - state.workers.delete(id) - showWorkers($, state) - return { - result: { - message: `Successfully stopped task: ${id} (${worker.description})`, - task_id: id, - task_type: "local_agent", - command: worker.description, - }, - } -} - -/** @param {import('claude-code').On} on */ -export function register(on) { - /** @type {State} */ - const state = { interactive: false, workers: new Map(), watching: false, lich: "", claims: new Map() } - - // A `claude -p` started from a tool inside a lich session inherits its - // variables; its subagents are its own and stay inside it. The matcher is - // also what lets this module hook `session.start` beside mod-control.js: - // Claude Code refuses one plugin's second hook on an event with no matcher. - on("session.start", { isInteractive: true }, ($, e, next) => { - state.interactive = true - return next(e) - }) - - on("tool.call", { tool: "Agent" }, ($, e, next) => runAsSession($, state, e, next)) - on("agent.spawn", ($, e, next) => openInPlaceOfSpawn($, state, e, next)) - on("tool.call", { tool: "TaskStop" }, ($, e, next) => stopWorker($, state, e, next)) -} diff --git a/hooks/codex-hooks.json b/hooks/codex-hooks.json index 744ded4..92213cd 100644 --- a/hooks/codex-hooks.json +++ b/hooks/codex-hooks.json @@ -34,6 +34,17 @@ "timeout": 5 } ] + }, + { + "matcher": "spawn_agent|collaborationspawn_agent|collaborationwait_agent", + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/veto-subagent.sh\" codex", + "commandWindows": "\"${CLAUDE_PLUGIN_ROOT}/hooks/win-veto.cmd\" \"${CLAUDE_PLUGIN_ROOT}/hooks/veto-subagent.sh\" codex", + "timeout": 15 + } + ] } ], "PostToolUse": [ diff --git a/hooks/crush-hooks.json b/hooks/crush-hooks.json index 66560d9..0a0214c 100644 --- a/hooks/crush-hooks.json +++ b/hooks/crush-hooks.json @@ -11,6 +11,12 @@ "matcher": "^(edit|write|multiedit|bash)$", "command": "\"/hooks/report-touched.sh\"", "timeout": 5 + }, + { + "name": "lich subagent cards", + "matcher": "^agent$", + "command": "\"/hooks/veto-subagent.sh\" crush", + "timeout": 15 } ] } diff --git a/hooks/hooks.json b/hooks/hooks.json index 6df6b89..0d31a79 100644 --- a/hooks/hooks.json +++ b/hooks/hooks.json @@ -29,6 +29,16 @@ "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/report-tool.sh\"" } ] + }, + { + "matcher": "Agent|Task", + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/veto-subagent.sh\" claude", + "timeout": 15 + } + ] } ], "PostToolUse": [ diff --git a/hooks/lich.js b/hooks/lich.js index 8a4773b..d7668bf 100644 --- a/hooks/lich.js +++ b/hooks/lich.js @@ -2,7 +2,6 @@ // single entry there, so each mod lives in a file of its own and is registered // from here. -import { register as registerAgentCards } from "./agent-cards.js" import { register as registerCompacting } from "./mod-compacting.js" import { register as registerEditGuard } from "./edit-guard.js" import { register as registerModControl } from "./mod-control.js" @@ -10,15 +9,12 @@ import { register as registerModStatus } from "./mod-status.js" import { register as registerModUsage } from "./mod-usage.js" import { register as registerSelfCommand } from "./self-command.js" import { register as registerStatusLine } from "./status-line.js" -import { register as registerWorkerAnswer } from "./worker-answer.js" /** @param {import('claude-code').On} on */ export function register(on) { registerModControl(on) - registerAgentCards(on) registerModUsage(on) registerEditGuard(on) - registerWorkerAnswer(on) registerModStatus(on) registerCompacting(on) registerSelfCommand(on) diff --git a/hooks/mod-status.js b/hooks/mod-status.js index e800ced..80312af 100644 --- a/hooks/mod-status.js +++ b/hooks/mod-status.js @@ -14,8 +14,7 @@ import { setStatusPart } from "./status-line.js" // Sent as X-Lich-Plugin on every request; bumped at release (CLAUDE.md, Release). const PLUGIN_VERSION = "0.22.0" -// The contract asks for a read at most every few seconds; the worker count in -// agent-cards.js polls lich on the same period. +// The contract asks for a read at most every few seconds. const READ_EVERY_MS = 5000 /** diff --git a/hooks/prompt-text.js b/hooks/prompt-text.js index 3e2afa9..8371c80 100644 --- a/hooks/prompt-text.js +++ b/hooks/prompt-text.js @@ -3,9 +3,8 @@ // session as LICH_PROMPT_LANG (`internal/prompt` there); an empty or unknown // value is English, as it is for lich itself. // -// A text is a template with `{name}` slots. Tool and command names, the -// `} */ export const en = { @@ -14,26 +13,6 @@ export const en = { "interrupt your turn and your answer is not added to the conversation. Tools are " + "unavailable: do not call any tool. Answer from what the conversation already holds, " + "in plain text, briefly. Question: ", - onBranch: "on branch {branch}", - whereBranch: "on branch {branch} in {path}, not in this checkout", - whereShared: "in this same checkout, {path}, and edits its files as you do", - backgrounded: - 'The agent runs as the lich session "{label}", {where}. ' + - 'Its full report arrives at this prompt by itself as a , so there is no need to poll ' + - "or to call wait_for_answer (it still works). SendMessage cannot reach that session; " + - "send_to_session or lich send can.", - completedBranch: - 'The work is on branch {branch} in {path} (lich session "{label}"), not in this checkout. ' + - "Reach that session with send_to_session or lich send, not SendMessage.", - completedShared: - 'The work is in this same checkout, {path} (lich session "{label}"). ' + - "Reach that session with send_to_session or lich send, not SendMessage.", - denyNeverReached: 'the task never reached "{label}" ({status}): open its card.', - denyAnswered: 'lich answered "{status}" about "{label}"{branchPart}: open its card.', - denyInterrupted: - 'interrupted; a lich session{branchPart} may already have the task, and a report it sends arrives here as a .', - denyStopFailed: 'lich could not stop "{label}": {reason}', - lichExited: "lich exited {code}", editNoteJustNow: "under a minute ago", editNoteAgo: "{minutes} min ago", editNote: @@ -60,26 +39,6 @@ export const ptBR = { "interrompe o seu turno e a sua resposta não entra na conversa. As ferramentas estão " + "indisponíveis: não chame nenhuma. Responda com o que a conversa já contém, " + "em texto simples e de forma breve. Pergunta: ", - onBranch: "na branch {branch}", - whereBranch: "na branch {branch} em {path}, não neste checkout", - whereShared: "neste mesmo checkout, {path}, e edita os arquivos dele como você", - backgrounded: - 'O agente roda como a sessão lich "{label}", {where}. ' + - 'O relatório completo chega neste prompt por conta própria como um , então não é preciso ' + - "fazer polling nem chamar wait_for_answer (ele ainda funciona). SendMessage não alcança essa sessão; " + - "send_to_session ou lich send alcançam.", - completedBranch: - 'O trabalho está na branch {branch} em {path} (sessão lich "{label}"), não neste checkout. ' + - "Fale com essa sessão por send_to_session ou lich send, não por SendMessage.", - completedShared: - 'O trabalho está neste mesmo checkout, {path} (sessão lich "{label}"). ' + - "Fale com essa sessão por send_to_session ou lich send, não por SendMessage.", - denyNeverReached: 'a tarefa nunca chegou a "{label}" ({status}): abra o card dela.', - denyAnswered: 'o lich respondeu "{status}" sobre "{label}"{branchPart}: abra o card dela.', - denyInterrupted: - 'interrompido; uma sessão lich{branchPart} pode já ter a tarefa, e o relatório que ela enviar chega aqui como um .', - denyStopFailed: 'o lich não conseguiu parar "{label}": {reason}', - lichExited: "o lich saiu com {code}", editNoteJustNow: "há menos de um minuto", editNoteAgo: "há {minutes} min", editNote: @@ -104,25 +63,6 @@ export const zhCN = { askPreamble: "这是在你的回合之外、你工作期间提出的旁路问题。它不会打断你的回合,你的回答也不会加入对话。" + "工具不可用:不要调用任何工具。请仅根据对话中已有的内容,用纯文本简要回答。问题:", - onBranch: "在分支 {branch} 上", - whereBranch: "在分支 {branch} 上的 {path} 中,不在当前 checkout 里", - whereShared: "在同一个 checkout {path} 中,并且和你一样编辑其中的文件", - backgrounded: - 'agent 作为 lich 会话 "{label}" 运行,{where}。' + - '它的完整报告会以 的形式自动出现在此提示中,因此无需轮询,也无需调用 ' + - "wait_for_answer(调用仍然有效)。SendMessage 无法联系该会话;send_to_session 或 lich send 可以。", - completedBranch: - '工作位于分支 {branch} 上的 {path}(lich 会话 "{label}"),不在当前 checkout 里。' + - "请通过 send_to_session 或 lich send 联系该会话,不要用 SendMessage。", - completedShared: - '工作位于同一个 checkout {path}(lich 会话 "{label}")中。' + - "请通过 send_to_session 或 lich send 联系该会话,不要用 SendMessage。", - denyNeverReached: '任务从未送达 "{label}"({status}):请打开它的卡片。', - denyAnswered: 'lich 针对 "{label}"{branchPart} 返回了 "{status}":请打开它的卡片。', - denyInterrupted: - '已中断;某个 lich 会话{branchPart}可能已经拿到任务,它发送的报告会以 的形式出现在这里。', - denyStopFailed: 'lich 无法停止 "{label}":{reason}', - lichExited: "lich 退出,退出码 {code}", editNoteJustNow: "不到一分钟前", editNoteAgo: "{minutes} 分钟前", editNote: @@ -148,26 +88,6 @@ export const es = { "interrumpe tu turno y tu respuesta no se añade a la conversación. Las herramientas no están " + "disponibles: no llames a ninguna. Responde con lo que la conversación ya contiene, " + "en texto plano y de forma breve. Pregunta: ", - onBranch: "en la rama {branch}", - whereBranch: "en la rama {branch} en {path}, no en este checkout", - whereShared: "en este mismo checkout, {path}, y edita sus archivos igual que tú", - backgrounded: - 'El agente se ejecuta como la sesión lich "{label}", {where}. ' + - 'Su informe completo llega a este prompt por sí solo como un , así que no hace falta ' + - "hacer polling ni llamar a wait_for_answer (sigue funcionando). SendMessage no puede llegar a esa sesión; " + - "send_to_session o lich send sí.", - completedBranch: - 'El trabajo está en la rama {branch} en {path} (sesión lich "{label}"), no en este checkout. ' + - "Comunícate con esa sesión con send_to_session o lich send, no con SendMessage.", - completedShared: - 'El trabajo está en este mismo checkout, {path} (sesión lich "{label}"). ' + - "Comunícate con esa sesión con send_to_session o lich send, no con SendMessage.", - denyNeverReached: 'la tarea nunca llegó a "{label}" ({status}): abre su tarjeta.', - denyAnswered: 'lich respondió "{status}" sobre "{label}"{branchPart}: abre su tarjeta.', - denyInterrupted: - 'interrumpido; puede que una sesión lich{branchPart} ya tenga la tarea, y el informe que envíe llega aquí como un .', - denyStopFailed: 'lich no pudo detener "{label}": {reason}', - lichExited: "lich terminó con {code}", editNoteJustNow: "hace menos de un minuto", editNoteAgo: "hace {minutes} min", editNote: @@ -193,27 +113,6 @@ export const ja = { "これは、あなたが作業している間にターンの外から尋ねられた横からの質問です。あなたのターンを中断することはなく、" + "あなたの回答が会話に追加されることもありません。ツールは使えません。どのツールも呼び出さないでください。" + "会話にすでにある内容から、プレーンテキストで簡潔に答えてください。質問:", - onBranch: "ブランチ {branch}", - whereBranch: "ブランチ {branch} の {path} で、このチェックアウトではありません", - whereShared: "同じこのチェックアウト {path} で、あなたと同じようにそのファイルを編集します", - backgrounded: - 'エージェントは lich セッション "{label}" として動いています({where})。' + - 'そのレポート全体は として、このプロンプトに自動で届きます。' + - "そのためポーリングも wait_for_answer の呼び出しも必要ありません(呼んでも動作します)。SendMessage ではそのセッションに届きません。" + - "send_to_session または lich send なら届きます。", - completedBranch: - '作業はブランチ {branch} の {path} にあり(lich セッション "{label}")、このチェックアウトにはありません。' + - "そのセッションには SendMessage ではなく、send_to_session または lich send で連絡してください。", - completedShared: - '作業は同じこのチェックアウト {path} にあります(lich セッション "{label}")。' + - "そのセッションには SendMessage ではなく、send_to_session または lich send で連絡してください。", - denyNeverReached: 'タスクは "{label}" に届きませんでした({status}):そのカードを開いてください。', - denyAnswered: 'lich は "{label}"{branchPart} について "{status}" と答えました:そのカードを開いてください。', - denyInterrupted: - "中断されました。lich セッション{branchPart}がすでにタスクを受け取っている可能性があり、" + - 'そのセッションが送るレポートは としてここに届きます。', - denyStopFailed: 'lich は "{label}" を停止できませんでした:{reason}', - lichExited: "lich が終了コード {code} で終了しました", editNoteJustNow: "1 分以内", editNoteAgo: "{minutes} 分前", editNote: @@ -239,26 +138,6 @@ export const ko = { "이것은 당신이 작업하는 동안 턴 밖에서 들어온 곁가지 질문입니다. 당신의 턴을 중단하지 않으며, 당신의 답은 " + "대화에 추가되지 않습니다. 도구는 사용할 수 없습니다. 어떤 도구도 호출하지 마세요. 대화에 이미 있는 내용으로, " + "일반 텍스트로 짧게 답하세요. 질문: ", - onBranch: "브랜치 {branch}", - whereBranch: "브랜치 {branch}의 {path}, 이 체크아웃이 아님", - whereShared: "같은 체크아웃 {path}, 당신처럼 그 파일을 수정함", - backgrounded: - '에이전트는 lich 세션 "{label}"에서 실행됩니다({where}). ' + - '전체 보고서는 로 이 프롬프트에 알아서 도착하므로, ' + - "폴링하거나 wait_for_answer를 호출할 필요가 없습니다(호출해도 동작합니다). SendMessage로는 그 세션에 닿을 수 없고, " + - "send_to_session이나 lich send로는 닿을 수 있습니다.", - completedBranch: - '작업은 브랜치 {branch}의 {path}에 있으며(lich 세션 "{label}"), 이 체크아웃에는 없습니다. ' + - "그 세션에는 SendMessage가 아니라 send_to_session이나 lich send로 연락하세요.", - completedShared: - '작업은 같은 체크아웃 {path}에 있습니다(lich 세션 "{label}"). ' + - "그 세션에는 SendMessage가 아니라 send_to_session이나 lich send로 연락하세요.", - denyNeverReached: '작업이 "{label}"에 한 번도 전달되지 않았습니다({status}): 그 카드를 열어 보세요.', - denyAnswered: 'lich의 답은 "{status}"였습니다("{label}"{branchPart}): 그 카드를 열어 보세요.', - denyInterrupted: - '중단되었습니다. 작업이 이미 lich 세션{branchPart}에 있을 수 있으며, 그 세션이 보내는 보고서는 로 여기에 도착합니다.', - denyStopFailed: 'lich가 "{label}"을(를) 멈추지 못했습니다: {reason}', - lichExited: "lich 종료 코드 {code}", editNoteJustNow: "1분 이내", editNoteAgo: "{minutes}분 전", editNote: @@ -284,26 +163,6 @@ export const ru = { "Это побочный вопрос, заданный вне вашего хода, пока вы работаете. Он не прерывает ваш ход, и ваш ответ " + "не добавляется в разговор. Инструменты недоступны: не вызывайте никаких инструментов. Отвечайте, исходя " + "из того, что уже есть в разговоре, простым текстом и кратко. Вопрос: ", - onBranch: "в ветке {branch}", - whereBranch: "в ветке {branch} в {path}, а не в этой рабочей копии", - whereShared: "в этой же рабочей копии, {path}, и редактирует её файлы так же, как вы", - backgrounded: - 'Агент работает как сессия lich "{label}", {where}. ' + - 'Его полный отчёт сам придёт в этот промпт как , поэтому не нужно ни опрашивать, ' + - "ни вызывать wait_for_answer (он по-прежнему работает). SendMessage не может связаться с этой сессией; " + - "send_to_session или lich send могут.", - completedBranch: - 'Работа находится в ветке {branch} в {path} (сессия lich "{label}"), а не в этой рабочей копии. ' + - "Связывайтесь с этой сессией через send_to_session или lich send, а не через SendMessage.", - completedShared: - 'Работа находится в этой же рабочей копии, {path} (сессия lich "{label}"). ' + - "Связывайтесь с этой сессией через send_to_session или lich send, а не через SendMessage.", - denyNeverReached: 'задача так и не дошла до "{label}" ({status}): откройте её карточку.', - denyAnswered: 'lich ответил "{status}" для "{label}"{branchPart}: откройте её карточку.', - denyInterrupted: - 'прервано; задача, возможно, уже у сессии lich{branchPart}, и отчёт, который она отправит, придёт сюда как .', - denyStopFailed: 'lich не смог остановить "{label}": {reason}', - lichExited: "lich завершился с кодом {code}", editNoteJustNow: "меньше минуты назад", editNoteAgo: "{minutes} мин назад", editNote: diff --git a/hooks/status-line.js b/hooks/status-line.js index fb5aad5..d0dda06 100644 --- a/hooks/status-line.js +++ b/hooks/status-line.js @@ -3,17 +3,14 @@ // `$.ui.status`, which Claude Code draws as a yellow warning. Each mod owns one // part of the line, and the line is the parts joined in a fixed order. // -// The errands lich lists (mod-status.js) include every worker agent-cards.js -// opened, so while that part shows, the worker count is left out of the line. -// // The parts live in this module, not in `$.state`: every part is redrawn by // its own mod within seconds, except an edit note, which a hot reload of the // plugin drops early. -/** @typedef {"errands" | "workers" | "edits"} Part */ +/** @typedef {"errands" | "edits"} Part */ /** @type {Part[]} */ -const ORDER = ["errands", "workers", "edits"] +const ORDER = ["errands", "edits"] const SEPARATOR = " · " /** @type {Map} */ @@ -33,7 +30,7 @@ export function setStatusPart(part, text) { } function statusLine() { - const shown = ORDER.filter((p) => parts.has(p) && !(p === "workers" && parts.has("errands"))) + const shown = ORDER.filter((p) => parts.has(p)) return shown.length === 0 ? undefined : `lich: ${shown.map((p) => parts.get(p)).join(SEPARATOR)}` } diff --git a/hooks/veto-subagent.sh b/hooks/veto-subagent.sh new file mode 100755 index 0000000..ac3e91e --- /dev/null +++ b/hooks/veto-subagent.sh @@ -0,0 +1,119 @@ +#!/bin/sh +# Asks lich whether a subagent call runs natively or as a lich session, and +# turns lich's deny into the harness's own veto, so the native subagent never +# runs. Contract: docs/subagent-cards.md +# $1: the harness, which decides how the payload maps to tasks and how the veto +# is spelled: claude (Cursor CLI runs this one too), codex, antigravity, +# kiro or crush. +# stdin: the harness's pre-tool payload. +# +# The one hook that blocks: the call waits on lich's answer, because the answer +# is the decision. Every way of not getting one (no lich, no jq, an error, a +# timeout, a status other than 200, a body that is not a decision) lets the call +# run, and lich closes whatever it opened for an answer nobody read. A deny is +# the only text this script passes on, and it is lich's, untouched. + +harness=$1 + +# Antigravity needs a verdict on every path; the others read silence as allow. +allow() { + [ "$harness" = antigravity ] && printf '{"decision":"allow"}' + exit 0 +} + +[ -n "$LICH_PORT" ] && [ -n "$LICH_TOKEN" ] && [ -n "$LICH_SESSION_ID" ] || allow + +# Sent as X-Lich-Plugin on every request; bumped at release (CLAUDE.md, Release). +plugin_version=0.22.0 + +# The body is built from arbitrary text and the answer read back as JSON, so +# without jq there is nothing safe to send. +command -v jq >/dev/null 2>&1 || allow + +# A file-shipped install that lacks conversation-id.sh still asks, without +# naming the conversation, as the report scripts do. +if [ -r "${0%/*}/conversation-id.sh" ]; then + . "${0%/*}/conversation-id.sh" +else + conversation_id() { :; } + from_subagent() { return 1; } +fi + +payload=$(cat) +conversation=$(printf '%s' "$payload" | conversation_id) +printf '%s' "$payload" | from_subagent && nested=true || nested=false + +# The body lich takes, or nothing when the call starts no subagent. Tool and +# field names are the contract's table (Event → veto mapping). +body=$(printf '%s' "$payload" | jq -c --arg harness "$harness" --arg sid "$LICH_SESSION_ID" \ + --arg conversation "$conversation" --argjson nested "$nested" ' + def s: if type == "string" then . else "" end; + def spawn($tasks): {call: "spawn", tasks: $tasks}; + . as $root + | (.tool_input // {}) as $in + | (.toolCall.args // {}) as $args + | (.tool_name // .toolCall.name // "" | s) as $tool + | if $harness == "claude" then + if $tool == "Agent" or $tool == "Task" then + spawn([{title: ($in.description | s), prompt: ($in.prompt | s), type: ($in.subagent_type | s)}]) + + {model: ($in.model | s), isolation: ($in.isolation | s), background: ($in.run_in_background == true)} + else empty end + elif $harness == "codex" then + if $tool == "spawn_agent" then + spawn([{title: "", prompt: ($in.message | s), type: ($in.agent_type | s)}]) + elif $tool == "collaborationspawn_agent" then + spawn([{title: ($in.task_name | s), prompt: "", type: ""}]) + {sealed: true} + elif $tool == "collaborationwait_agent" then + {call: "wait", tasks: []} + else empty end + elif $harness == "antigravity" then + if $tool == "invoke_subagent" then + spawn([{title: "", prompt: ($args.Prompt | s), type: ($args.TypeName | s)}]) + else empty end + elif $harness == "kiro" then + if $tool == "subagent" then + spawn([{title: ($in.stages[0].name? | s), prompt: ($in.task | s), type: ""}]) + elif $tool == "use_subagent" and (($in.command // "InvokeSubagents") == "InvokeSubagents") then + spawn([($in.subagents // $in.content.subagents // [])[]? | {title: "", prompt: (.query | s), type: ""}]) + else empty end + elif $harness == "crush" then + if $tool == "agent" then spawn([{title: "", prompt: ($in.prompt | s), type: ""}]) else empty end + else empty end + # A spawn lich would refuse (no task, a task with no prompt) is left native + # here rather than sent: lich answers it 400, which is an allow anyway. + | select(.call == "wait" or .sealed == true + or ((.tasks | length) > 0 and all(.tasks[]; .prompt | test("\\S")))) + | {session_id: $sid, provider_session_id: $conversation, nested: $nested, tool: $tool, + tool_use_id: ($root.tool_use_id | s), model: "", sealed: false, isolation: "", background: false} + + . +' 2>/dev/null) +[ -n "$body" ] || allow + +# The token rides a header fed through stdin, as in every report script: a +# query string or -H would put it in curl's command line. The answer comes back +# with its status on a last line of its own. +url="http://127.0.0.1:${LICH_PORT}/subagent" +answer=$(printf 'header = "Authorization: Bearer %s"\n' "$LICH_TOKEN" | + curl -s --max-time 10 -X POST \ + -H 'Content-Type: application/json' \ + -H "X-Lich-Plugin: ${plugin_version}" \ + -d "$body" -w '\n%{http_code}' -K - "$url" 2>/dev/null) +[ "$(printf '%s' "$answer" | tail -n 1)" = 200 ] || allow +decision=$(printf '%s' "$answer" | sed '$d' | + jq -c 'select(.decision == "deny" and (.reason | type) == "string" and .reason != "")' 2>/dev/null) +[ -n "$decision" ] || allow + +case $harness in + claude | codex) + printf '%s' "$decision" | + jq -c '{hookSpecificOutput: {hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: .reason}}' + ;; + antigravity) + printf '%s' "$decision" | jq -c '{decision: "deny", reason}' + ;; + kiro | crush) + printf '%s' "$decision" | jq -j '.reason' >&2 + exit 2 + ;; +esac +exit 0 diff --git a/hooks/win-veto.cmd b/hooks/win-veto.cmd new file mode 100644 index 0000000..2ed683f --- /dev/null +++ b/hooks/win-veto.cmd @@ -0,0 +1,10 @@ +@echo off +rem Runs veto-subagent.sh through a POSIX shell on Windows, where Codex spawns a +rem hook with `cmd.exe /C` and cmd cannot execute a .sh itself. Unlike +rem win-run.cmd it keeps the script's stdout, which carries the veto: a veto +rem dropped there would let the native subagent run beside the session lich +rem opened for the same task. No bash on the machine prints nothing, which +rem Codex reads as allow, and lich opens nothing because nothing asked. +where bash >nul 2>&1 || set "PATH=%PATH%;%ProgramFiles%\Git\bin" +bash %* 2>nul +exit /b 0 diff --git a/hooks/worker-answer.js b/hooks/worker-answer.js deleted file mode 100644 index d68f4f5..0000000 --- a/hooks/worker-answer.js +++ /dev/null @@ -1,222 +0,0 @@ -// Answers the task a lich subagent worker was handed with the worker's own last -// message, the way a native subagent's final message is its result. Contract: -// ../docs/mod-answer.md, canonical in -// https://github.com/lichdotdev/lich/blob/main/docs/hooks/mod-answer.md -// -// A Claude Code mod, registered by hooks/lich.js beside mod-control.js. Only a -// worker reports: lich sets LICH_SUBAGENT_DEPTH on every Claude Code session it -// starts, 0 at the top and n for a worker n `lich open --subagent` levels down. -// A lich older than that variable spawns every worker with -// LICH_SUBAGENT_CARDS=off instead, which a session the user turned subagent -// cards off for also carries; lich ignores the report from a session with no -// subagent errand open, so that one costs a request per turn and nothing else. -// -// A main-loop turn reports only when its `classic.Stop` lists no background -// task (a shell, subagent, monitor or workflow still running means the turn -// handed work to the background, and the turn Claude Code resumes in once it -// finishes is the one that reports). Its `turn.complete` then says what: an -// answer that is not blank is the worker's answer, a blank one is -// `unanswered: "blank"`. Measured on Claude Code 2.1.289: `classic.Stop` fires -// on the main loop only, before `turn.complete`, and its -// `last_assistant_message` equals the completion's `answer`; an aborted turn -// fires no Stop. -// -// A session that never saw a `classic.Stop` reports from `turn.complete` -// alone. Measured on Claude Code 2.1.306: the builtin cc-plugin-sec-default, -// seated outermost on a machine with managed settings, sends `classic.Stop` on -// past user-installed plugins ("bypassed by", "hook was skipped"), and no mod -// call says so, so the mod infers it from a session with no Stop. That is set -// by the settings the session started with, which is why one Stop is enough to -// keep the Stop rule above for the rest of the session. Without a Stop there -// is no `background_tasks`: the only running work the mod can still see is a -// subagent `$.agent.list()` names running or waiting, which holds the report. -// A background shell, monitor or workflow is not listed there, so a turn that -// handed one off answers early, and lich takes the first answer. -// -// A refused turn and one an API error ended report nothing, though the -// contract has `unanswered: "refusal"` and `"error"` for them. Measured on -// Claude Code 2.1.296, both end through `StopFailure` (a refusal with error -// `invalid_request`) and then `turn.complete`, with no `Stop`, and neither -// carries `background_tasks`: the mod cannot tell a failed turn with nothing -// running from one whose background work resumes it later and answers then, -// so reporting would answer the errand twice. -// -// Every function that takes `$` is declared here at the top level: the loader -// refuses a module that hands `$` to a nested function. - -// Sent as X-Lich-Plugin on every request; bumped at release (CLAUDE.md, Release). -const PLUGIN_VERSION = "0.22.0" - -// The value a lich older than LICH_SUBAGENT_DEPTH spawns every `--subagent` -// session with. -const CARDS_OFF = "off" - -// The contract cuts an answer at this many UTF-16 units, as mod-control.js -// cuts an ask's, which keeps the body under lich's 64 KiB limit. -const ANSWER_LIMIT = 16000 - -/** - * @typedef {import('claude-code').EngineInterface} Engine - * @typedef {{ base: string, token: string, session: string }} Link - * @typedef {{ idle: boolean, text: string }} Stop - * @typedef {{ link?: Link, stop?: Stop, stopSeen?: boolean }} State - * @typedef {{ text: string } | { unanswered: "blank" }} Report - */ - -/** - * @param {string | undefined} depth LICH_SUBAGENT_DEPTH - * @param {string | undefined} cards LICH_SUBAGENT_CARDS - */ -function isWorker(depth, cards) { - if (depth === undefined) return cards === CARDS_OFF - const levels = Number(depth) - return Number.isInteger(levels) && levels > 0 -} - -/** - * The link to lich, for a worker only. - * - * @param {Engine} $ - * @returns {Promise} - */ -async function workerLink($) { - const [port, token, session, depth, cards] = await Promise.all([ - $.env.get("LICH_PORT"), - $.env.get("LICH_TOKEN"), - $.env.get("LICH_SESSION_ID"), - $.env.get("LICH_SUBAGENT_DEPTH"), - $.env.get("LICH_SUBAGENT_CARDS"), - ]) - if (!port || !token || !session || !isWorker(depth, cards)) return undefined - return { base: `http://127.0.0.1:${port}`, token, session } -} - -/** @param {string} text */ -function cut(text) { - if (text.length <= ANSWER_LIMIT) return text - return `${text.slice(0, ANSWER_LIMIT)}\n[truncated]` -} - -/** - * What a finished main-loop turn reports, if anything. The Stop must be the - * turn's own: an answer's text equals the completion's, a blank Stop comes - * with a blank completion. - * - * @param {Stop | undefined} stop the turn's main-loop `classic.Stop` - * @param {import('claude-code').TurnCompleteInput} e - * @returns {Report | undefined} - */ -function reportOf(stop, e) { - if (stop === undefined || !stop.idle) return undefined - if (e.reason !== "answer") return undefined - if (stop.text.trim() === "") return e.answer.trim() === "" ? { unanswered: "blank" } : undefined - return stop.text === e.answer ? { text: cut(stop.text) } : undefined -} - -/** - * What a main-loop turn of a session whose `classic.Stop` never fires reports. - * - * @param {import('claude-code').TurnCompleteInput} e - * @returns {Report | undefined} - */ -function reportWithoutStop(e) { - if (e.reason !== "answer") return undefined - return e.answer.trim() === "" ? { unanswered: "blank" } : { text: cut(e.answer) } -} - -/** - * Whether a subagent is still at work. One the list cannot be read for counts - * as at work: the first answer lich hears wins, so an early one is worse than - * none. - * - * @param {Engine} $ - */ -async function subagentAtWork($) { - try { - const agents = await $.agent.list() - return agents.some((agent) => agent.status === "running" || agent.status === "waiting") - } catch { - return true - } -} - -/** - * @param {Engine} $ - * @param {Link} link - * @param {Report} body - */ -async function reportUnlessSubagentAtWork($, link, body) { - if (await subagentAtWork($)) return - await report($, link, body) -} - -/** - * Posts one report beside the chain. One that cannot be sent is dropped: the - * worker's card still holds it, and a second copy of a report is worse than - * none. - * - * @param {Engine} $ - * @param {Link} link - * @param {Report} body - */ -async function report($, link, body) { - try { - await $.http.fetch(`${link.base}/mod/answer?token=${link.token}`, { - method: "POST", - headers: { "content-type": "application/json", "X-Lich-Plugin": PLUGIN_VERSION }, - body: JSON.stringify({ session_id: link.session, ...body }), - }) - } catch { - // The contract's client rule: a report that cannot be sent is dropped. - } -} - -/** - * @param {Engine} $ - * @param {State} state - * @param {import('claude-code').TurnCompleteInput} e - * @param {(e: import('claude-code').TurnCompleteInput) => unknown} next - */ -function settleTurn($, state, e, next) { - const stop = state.stop - state.stop = undefined - const link = state.link - if (link === undefined || e.agentId !== undefined) return next(e) - if (state.stopSeen) { - const body = reportOf(stop, e) - if (body !== undefined) void report($, link, body) - return next(e) - } - const body = reportWithoutStop(e) - if (body !== undefined) void reportUnlessSubagentAtWork($, link, body) - return next(e) -} - -/** @param {import('claude-code').On} on */ -export function register(on) { - /** @type {State} */ - const state = {} - - // Interactive sessions only: a `claude -p` started from a tool inside a - // worker inherits its variables, and its answers are not the worker's. - on("session.start", { isInteractive: true }, async ($, e, next) => { - state.link = await workerLink($) - return next(e) - }) - - on("classic.Stop", ($, e, next) => { - state.stopSeen = true - state.stop = { idle: (e.background_tasks ?? []).length === 0, text: e.last_assistant_message ?? "" } - return next(e) - }) - - // One hook per reason a turn ends with: the matchers keep them beside - // mod-control.js's own turn.complete hook, which has none, and Claude Code - // refuses one plugin's second hook on an event with no matcher. The refused, - // aborted and failed ones report nothing; they are here so every turn drops - // the Stop it read, and a later turn never inherits it. - on("turn.complete", { reason: "answer" }, ($, e, next) => settleTurn($, state, e, next)) - on("turn.complete", { reason: "refusal" }, ($, e, next) => settleTurn($, state, e, next)) - on("turn.complete", { reason: "error" }, ($, e, next) => settleTurn($, state, e, next)) - on("turn.complete", { reason: "aborted" }, ($, e, next) => settleTurn($, state, e, next)) -} diff --git a/omp/lich.js b/omp/lich.js index 81cf3a1..ef99340 100644 --- a/omp/lich.js +++ b/omp/lich.js @@ -7,7 +7,9 @@ // fed a payload on stdin. So this one file plays the part the four hooks/*.sh // scripts play on the harnesses that do run commands, the way opencode/lich.js // does: same transport, same payloads, same rule — outside lich it is a no-op, -// and it never blocks or fails the user's turn. +// and it never fails the user's turn. It blocks in one place, a `task` call +// waiting on lich's veto (vetoReason, below), because there the answer is the +// decision. // // Every event name and context method used here was measured against omp // v17.3.0 (@oh-my-pi/pi-coding-agent), against a stub listener, not read off @@ -19,7 +21,7 @@ // no package around it to resolve a shared module from — so the duplication is // the packaging, not an oversight. -// Fire and forget. Nothing here is awaited: omp awaits its extension handlers, +// Fire and forget. No report is awaited: omp awaits its extension handlers, // so a slow or dead listener would sit in front of the agent's next step. The // environment is read per report rather than at import, so a module loaded // outside lich stays a no-op instead of a cached decision. @@ -41,6 +43,65 @@ function report(path, body) { } catch {} } +// The one request this module awaits: lich's answer decides whether a `task` +// call runs (docs/subagent-cards.md), so the call waits for it, 10 seconds at +// most. Every way of not getting a deny (an error, a timeout, a status other +// than 200, a body that is not a decision) resolves to undefined, which lets +// the call run. A deny resolves to lich's reason, untouched. +const VETO_WAIT_MS = 10000 + +async function vetoReason(body) { + try { + const res = await fetch( + `http://127.0.0.1:${process.env.LICH_PORT}/subagent?token=${process.env.LICH_TOKEN}`, + { + method: "POST", + headers: { "content-type": "application/json", "x-lich-plugin": PLUGIN_VERSION }, + body: JSON.stringify({ session_id: process.env.LICH_SESSION_ID, ...body }), + signal: AbortSignal.timeout(VETO_WAIT_MS), + }, + ) + if (res.status !== 200) return undefined + const answer = await res.json() + return answer?.decision === "deny" && typeof answer.reason === "string" && answer.reason !== "" + ? answer.reason + : undefined + } catch { + return undefined + } +} + +const text = (value) => (typeof value === "string" ? value : "") + +// The `task` call as lich's /subagent body, one task per entry of its `tasks`, +// or undefined when lich would refuse it for want of a prompt, which leaves it +// native without asking. Field names are the contract's table (Event → veto +// mapping), measured on 18.8.9 there; how `context` joins each prompt is not +// given, so it goes first with a blank line after it. +function subagentBody(event, ctx) { + const input = event?.input + const entries = Array.isArray(input?.tasks) ? input.tasks : [] + const context = text(input?.context).trim() + const tasks = entries.map((entry) => ({ + title: text(entry?.name), + prompt: context && text(entry?.task) ? `${context}\n\n${text(entry.task)}` : text(entry?.task), + type: text(entry?.agent), + })) + if (tasks.length === 0 || tasks.some((task) => task.prompt.trim() === "")) return undefined + return { + provider_session_id: sessionIdOf(ctx) ?? "", + nested: false, + call: "spawn", + tool: event.toolName, + tool_use_id: text(event.toolCallId), + tasks, + model: "", + sealed: false, + isolation: "", + background: false, + } +} + function inLich() { return Boolean(process.env.LICH_PORT && process.env.LICH_TOKEN && process.env.LICH_SESSION_ID) } @@ -163,16 +224,20 @@ export default function lichPlugin(pi) { }), ) - // The tool line on the card. This handler is on the agent's critical path: - // returning `{block: true}` from it would refuse the call, so it returns - // nothing, always. - pi.on( - "tool_call", - safely((event, ctx) => { + // The tool line on the card, and lich's say on a `task` call. This handler + // is on the agent's critical path: returning `{block: true}` from it refuses + // the call, so it returns that for lich's deny and nothing otherwise. One + // handler does both, since `safely` drops what a handler returns. + pi.on("tool_call", async (event, ctx) => { + try { if (typeof event?.toolName !== "string" || event.toolName === "") return report("hook", { state: "busy", tool: event.toolName, detail: detailOf(event.input), ...conversation(ctx) }) - }), - ) + if (event.toolName !== "task") return + const body = subagentBody(event, ctx) + const reason = body && (await vetoReason(body)) + if (reason) return { block: true, reason } + } catch {} + }) // After the write, not before it: `tool_result` is where the tree has already // changed, so the refresh lich runs sees it. diff --git a/opencode/lich.js b/opencode/lich.js index a6b5e70..63f7f2a 100644 --- a/opencode/lich.js +++ b/opencode/lich.js @@ -2,11 +2,12 @@ // https://github.com/lichdotdev/lich/tree/main/docs/hooks // // opencode loads a module rather than running a script, so this one file plays -// the part the four hooks/*.sh scripts play on the other harnesses. Same -// transport, same payloads, same rule: outside lich it is a no-op, and it never -// blocks or fails the user's turn. +// the part the hooks/*.sh scripts play on the other harnesses. Same transport, +// same payloads, same rule: outside lich it is a no-op, and it never fails the +// user's turn. It blocks in one place, a `task` call waiting on lich's veto +// (vetoReason, below), because there the answer is the decision. -// Fire and forget. Nothing here is awaited: opencode awaits its hooks, so a +// Fire and forget. No report is awaited: opencode awaits its hooks, so a // slow or dead listener would sit in front of the agent's next step. The // environment is read per report rather than at import, so a module loaded // outside lich stays a no-op instead of a cached decision. @@ -28,6 +29,57 @@ function report(path, body) { } catch {} } +// The one request this module awaits: lich's answer decides whether a `task` +// call runs (docs/subagent-cards.md), so the call waits for it, 10 seconds at +// most. Every way of not getting a deny (no lich, an error, a timeout, a status +// other than 200, a body that is not a decision) resolves to undefined, which +// lets the call run. A deny resolves to lich's reason, untouched. +const VETO_WAIT_MS = 10000 + +async function vetoReason(body) { + const port = process.env.LICH_PORT + const token = process.env.LICH_TOKEN + const session = process.env.LICH_SESSION_ID + if (!port || !token || !session) return undefined + try { + const res = await fetch(`http://127.0.0.1:${port}/subagent?token=${token}`, { + method: "POST", + headers: { "content-type": "application/json", "x-lich-plugin": PLUGIN_VERSION }, + body: JSON.stringify({ session_id: session, ...body }), + signal: AbortSignal.timeout(VETO_WAIT_MS), + }) + if (res.status !== 200) return undefined + const answer = await res.json() + return answer?.decision === "deny" && typeof answer.reason === "string" && answer.reason !== "" + ? answer.reason + : undefined + } catch { + return undefined + } +} + +const text = (value) => (typeof value === "string" ? value : "") + +// The `task` call as lich's /subagent body, or undefined when lich would refuse +// it for want of a prompt, which leaves it native without asking. Field names +// are the contract's table (Event → veto mapping), measured on 1.19.4 there. +function subagentBody(input, args, nested) { + const prompt = text(args?.prompt) + if (prompt.trim() === "") return undefined + return { + provider_session_id: text(input.sessionID), + nested, + call: "spawn", + tool: input.tool, + tool_use_id: text(input.callID), + tasks: [{ title: text(args?.description), prompt, type: text(args?.subagent_type) }], + model: "", + sealed: false, + isolation: "", + background: false, + } +} + // The conversation a state report comes from, so lich can drop one from an // agent CLI nested in the session (docs/session-state.md, Nested agent CLIs). // An id opencode did not give is left out rather than sent empty. @@ -548,16 +600,25 @@ export const LichPlugin = async ({ $ } = {}, helper) => { } }, - // The tool line on the card. `file.edited` above already covers the touched - // report, so this one only decorates the state. + // The tool line on the card, and lich's say on a `task` call. `file.edited` + // above already covers the touched report. A sub-session's `task` is still + // asked about, as nested, and lich leaves it native. A deny is thrown: that + // is how opencode refuses a call, and the model reads the message. "tool.execute.before": async (input, output) => { - if (!input?.tool || subSessions.has(input.sessionID)) return - report("hook", { - state: "busy", - tool: input.tool, - detail: detailOf(output?.args), - ...conversation(input.sessionID), - }) + if (!input?.tool) return + const nested = subSessions.has(input.sessionID) + if (!nested) { + report("hook", { + state: "busy", + tool: input.tool, + detail: detailOf(output?.args), + ...conversation(input.sessionID), + }) + } + if (input.tool !== "task") return + const body = subagentBody(input, output?.args, nested) + const reason = body && (await vetoReason(body)) + if (reason) throw new Error(reason) }, // Absent outside lich, and absent when the helper cannot be imported: the diff --git a/tests/agent-cards.engine.test.ts b/tests/agent-cards.engine.test.ts deleted file mode 100644 index 9978596..0000000 --- a/tests/agent-cards.engine.test.ts +++ /dev/null @@ -1,143 +0,0 @@ -// The Agent-call mod under Claude Code's own engine: `claude plugin test .` -// loads hooks/lich.js from hooks/hooks.json the way a session does, which -// registers hooks/agent-cards.js, and runs these against it. The test's hooks -// stand for the lich CLI (`process.run`) and for the native agent (the -// `tool.call` beneath the mod). -// -// tests/agent-cards.test.mjs is the suite CI runs; this one needs a claude -// binary, and proves the module loads beside mod-control.js and its hooks -// chain in the engine that runs it: a call the mod takes goes on to Claude -// Code's permission check, and one refused there runs no lich. The open itself -// happens at `agent.spawn`, which Claude Code raises beneath an allowed call; -// the kit refuses `$.agent.spawn` from a test's hook (measured on 2.1.296), so -// the open, the `async_launched` result and the worker count are pinned by -// tests/agent-cards.test.mjs and a live run, not here. - -import { expect, mock, test } from 'claude-code/testing' -import type { On, ProcessRunResult } from 'claude-code' - -const ENV: Record = { LICH_BIN: '/opt/lich/bin/lich', LICH_SESSION_ID: 'lich-1' } -const BRANCH = 'subagent/fix-the-auth-flow-ab12' -const OPENED = { id: '9f8e', label: BRANCH, name: `${BRANCH}-9f8e`, kind: 'claude', path: `/wt/${BRANCH}` } -const CALL = { - tool: 'Agent', - tool_use_id: 'toolu_01QxW7zAB12', - description: 'Fix the auth flow', - prompt: 'Fix the login bug.', - subagent_type: 'general-purpose', -} as const - -const exited = (exitCode: number, stdout: unknown = '', stderr = ''): ProcessRunResult => ({ - exitCode, - stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), - stderr, - isStdoutTruncated: false, - isStderrTruncated: false, -}) - -/** - * Answers `git` with a branch and each `lich` run with the next of `lich`, and - * stands for the native agent and the engine's own session start. - */ -function world(on: On, ...lich: ProcessRunResult[]) { - return worldWith(on, ENV, ...lich) -} - -function worldWith(on: On, env: Record, ...lich: ProcessRunResult[]) { - const native: string[] = [] - const argvs: string[][] = [] - const toasts: string[] = [] - const footer = { modes: [] as readonly string[] } - mock.env(on, env) - const clock = mock.clock(on) - on('ui.render', { component: 'SessionMode' }, async ($, e) => { - footer.modes = e.props.modes - const { Text } = $.ui.resolve(e) - return h(Text, {}, e.props.modes.join(' & ')) - }) - on('session.start', async (_$, e) => ({ cwd: e.cwd })) - on('process.run', async (_$, e) => { - argvs.push([...e.argv]) - if (e.argv[0] === 'git') return { value: exited(0, 'main\n') } - const answer = lich.shift() - if (!answer) throw new Error(`unscripted run: ${e.argv.join(' ')}`) - return { value: answer } - }) - on('ui.toast', async (_$, e) => { - toasts.push(e.text) - return { value: undefined } - }) - on('tool.call', { tool: 'Agent' }, async (_$, e) => { - native.push(e.description) - return { deny: 'the native agent ran' } - }) - on('tool.call', { tool: 'TaskStop' }, async (_$, e) => { - native.push(`TaskStop ${e.task_id}`) - return { deny: 'the native TaskStop ran' } - }) - return { native, argvs, toasts, footer, clock } -} - -/** The lich line the footer draws now, Claude Code's own modes being none. */ -async function footerLine($: { ui: { render: (input: object) => Promise } }, w: { footer: { modes: readonly string[] } }) { - await $.ui.render({ surface: 'terminal', component: 'SessionMode', requestId: 'footer', props: { modes: [] } }) - return w.footer.modes.at(-1) -} - -test('a call the mod takes goes on to the permission check, and a refusal there runs no lich', async ($, on) => { - const w = world(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - const ran = await $.tool.call(CALL) - expect(ran.deny).toBe('the native agent ran') - expect(w.native).toEqual(['Fix the auth flow']) - expect(w.argvs).toEqual([]) -}) - -test('a refused isolated call reads its base branch and opens no worktree', async ($, on) => { - const w = world(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await $.tool.call({ ...CALL, isolation: 'worktree' }) - expect(w.native).toEqual(['Fix the auth flow']) - expect(w.argvs).toEqual([['git', 'branch', '--show-current']]) -}) - -test('a non-interactive run keeps its subagents native', async ($, on) => { - const w = world(on) - await $.session.start({ cwd: '/w', surface: null, isInteractive: false }) - await $.tool.call(CALL) - expect(w.native).toEqual(['Fix the auth flow']) - expect(w.argvs).toEqual([]) -}) - -test('an Explore agent stays native and lich is never run', async ($, on) => { - const w = world(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await $.tool.call({ ...CALL, subagent_type: 'Explore' }) - expect(w.native).toEqual(['Fix the auth flow']) - expect(w.argvs).toEqual([]) -}) - -test('turned off in lich, every subagent stays native and lich is never run', async ($, on) => { - const w = worldWith(on, { ...ENV, LICH_SUBAGENT_CARDS: 'off' }) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await $.tool.call(CALL) - expect(w.native).toEqual(['Fix the auth flow']) - expect(w.argvs).toEqual([]) -}) - -test('a worker at lich\'s depth limit keeps its subagents native, with a toast saying why', async ($, on) => { - const w = worldWith(on, { ...ENV, LICH_SUBAGENT_CARDS: 'off', LICH_SUBAGENT_DEPTH: '2' }) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await $.tool.call(CALL) - expect(w.native).toEqual(['Fix the auth flow']) - expect(w.argvs).toEqual([]) - expect(w.toasts).toEqual([expect.stringContaining('this session is itself a lich subagent')]) -}) - -test('TaskStop on a task this mod did not open goes to Claude Code', async ($, on) => { - const w = world(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await $.tool.call({ tool: 'TaskStop', task_id: 'a712043a56e1aafb1' }) - expect(w.native).toEqual(['TaskStop a712043a56e1aafb1']) - expect(await footerLine($, w)).toBe(undefined) -}) diff --git a/tests/agent-cards.test.mjs b/tests/agent-cards.test.mjs deleted file mode 100644 index a7bec43..0000000 --- a/tests/agent-cards.test.mjs +++ /dev/null @@ -1,676 +0,0 @@ -// Pins the Claude Code mod that runs a subagent as a lich session -// (hooks/agent-cards.js) to the lich CLI it drives: the argv of `lich open`, how -// each outcome it prints is answered, and the rule that a call the mod does not -// take goes to the native agent untouched. -// -// Like tests/mod-control.test.mjs it imports the module and hands it a fake -// engine. The `e` fields, `next.origin`, `next.signal`, the Agent result arms -// and the `$.process.run` behaviour were measured on Claude Code 2.1.289; the -// CLI's output shapes and exit codes are docs/cli.md in lich (`open --json`, -// Exit status). -// -// Run: node --test tests/ - -import { test } from 'node:test' -import assert from 'node:assert/strict' - -import { footerLine } from './contract.mjs' -import { register } from '../hooks/agent-cards.js' - -const LICH_BIN = '/opt/lich/bin/lich' -const ENV = { LICH_BIN, LICH_SESSION_ID: 'lich-1', LICH_PORT: '47999', LICH_TOKEN: 'tok' } -const TICKET = 'a1b2c3d4' -const BRANCH = 'subagent/fix-the-auth-flow-ab12' -const OPENED = { - id: '9f8e', - projectId: 'p1', - project: 'lich', - label: BRANCH, - name: `${BRANCH}-9f8e`, - kind: 'claude', - path: `/wt/${BRANCH}`, - nextSeq: 5, - originSessionId: '3c4d', - originLabel: 'planner', -} -const AGENT = { - tool: 'Agent', - tool_use_id: 'toolu_01QxW7zAB12', - description: 'Fix the auth flow', - prompt: 'Fix the login bug in auth/login.go and run its tests.', - subagent_type: 'general-purpose', -} -const ISOLATED = { ...AGENT, isolation: 'worktree' } -// A worker without isolation opens in the asking session's directory. -const SHARED = { ...OPENED, label: 'claude-2', name: 'claude-2-9f8e', path: '/w' } -const NATIVE = { result: 'the native agent ran' } -const REJECTED = { result: "Error: The user doesn't want to proceed with this tool use.", isError: true } - -const report = (status, answer = '') => ({ ticket: TICKET, target: BRANCH, status, answer }) -const opened = (status, answer) => ({ ...OPENED, delivery: report(status, answer) }) -const openedHere = (status, answer) => ({ ...SHARED, delivery: report(status, answer) }) - -/** One scripted `$.process.run` answer: the child exited with `code`. */ -const exits = (code, stdout = '', stderr = '') => () => ({ - exitCode: code, - stdout: typeof stdout === 'string' ? stdout : JSON.stringify(stdout), - stderr, - isStdoutTruncated: false, - isStderrTruncated: false, -}) -const rejects = (message) => () => Promise.reject(new Error(message)) -const onBranch = (name) => exits(0, `${name}\n`) - -/** - * Registers the module against a fake engine. `runs` answers each - * `$.process.run` in turn; one past the script fails the test. `times` is what - * `$.clock.now` answers, in turn. A hook registered with a matcher runs only - * for an `e` holding the matcher's fields, as the engine runs it. - */ -function load({ env = ENV, runs = [], times = [1000, 4000] } = {}) { - const hooks = new Map() - register((event, ...rest) => { - const hook = rest.at(-1) - const matcher = rest.length > 1 ? rest[0] : {} - const matches = (e) => Object.entries(matcher).every(([field, value]) => e[field] === value) - const below = hooks.get(event) ?? ((_$, e, next) => next(e)) - hooks.set(event, ($, e, next) => (matches(e) ? hook($, e, next) : below($, e, next))) - }) - - const ran = [] - const toasts = [] - const statuses = [] - const timers = [] - const script = [...runs] - const clock = [...times] - const $ = { - env: { get: async (name) => env[name] }, - clock: { - now: async () => clock.shift(), - after: (ms, fn) => { - timers.push({ ms, fn }) - return { cancel: () => {} } - }, - }, - process: { - run: async (argv, init) => { - ran.push({ argv, init }) - const answer = script.shift() - if (!answer) assert.fail(`unscripted run: ${argv.join(' ')}`) - return answer(argv, init) - }, - }, - ui: { toast: (text) => toasts.push(text), invalidate: () => statuses.push(footerLine()) }, - } - - return { - ran, - toasts, - statuses, - timers, - /** Scripts what the next `$.process.run` calls answer. */ - answer: (...more) => script.push(...more), - /** Fires the timers pending now, `runs` scripting what they run, and waits for them. */ - async tick(...more) { - script.push(...more) - const due = timers.splice(0) - await Promise.all(due.map(({ fn }) => fn())) - }, - start: (isInteractive = true) => - hooks.get('session.start')($, { cwd: '/w', surface: isInteractive ? 'terminal' : null, isInteractive }, async (e) => e), - /** - * Raises one tool call; `passed` is what reached the native tool. Beneath - * an Agent call's `next` the engine decides its permission and, only once - * `permission` is allowed, raises `agent.spawn` before the native agent - * starts, as measured on Claude Code 2.1.296. - */ - async call(e = AGENT, { plugin = 'engine', signal = new AbortController().signal, permission = 'allow' } = {}) { - const passed = [] - const spawn = async (forwarded) => { - const input = { tool_use_id: forwarded.tool_use_id, prompt: forwarded.prompt, description: forwarded.description } - const spawnNext = Object.assign( - async () => { - passed.push(forwarded) - return { model: 'claude-opus-5-5' } - }, - { signal }, - ) - const unhooked = (_$, spawning, nextSpawn) => nextSpawn(spawning) - const spawned = await (hooks.get('agent.spawn') ?? unhooked)($, input, spawnNext) - return spawned.deny === undefined ? NATIVE : { result: `Error: ${spawned.deny}`, text: spawned.deny, isError: true } - } - const next = Object.assign( - async (forwarded) => { - if (forwarded.tool !== 'Agent') { - passed.push(forwarded) - return NATIVE - } - return permission === 'allow' ? spawn(forwarded) : REJECTED - }, - { origin: { plugin, tier: plugin === 'engine' ? 'core' : 'user' }, signal }, - ) - const answer = await hooks.get('tool.call')($, e, next) - return { answer, passed } - }, - } -} - -/** Loads the module inside an interactive lich session and raises `e`. */ -async function delegate(runs, e = AGENT, options = {}) { - const mod = load({ runs, ...options }) - await mod.start() - return { mod, ...(await mod.call(e, options)) } -} - -function completed(text, { durationMs = 3000, prompt = AGENT.prompt, worker = OPENED } = {}) { - const worktree = worker === OPENED ? { worktreePath: OPENED.path, worktreeBranch: BRANCH } : {} - return { - result: { - status: 'completed', - agentId: worker.name, - content: [{ type: 'text', text }], - totalToolUseCount: 0, - totalDurationMs: durationMs, - totalTokens: 0, - usage: { - input_tokens: 0, - output_tokens: 0, - cache_creation_input_tokens: null, - cache_read_input_tokens: null, - server_tool_use: null, - service_tier: null, - cache_creation: null, - }, - prompt, - ...worktree, - }, - } -} - -const reportArrives = - 'Its full report arrives at this prompt by itself as a , so there is no need to poll ' + - 'or to call wait_for_answer (it still works). SendMessage cannot reach that session; ' + - 'send_to_session or lich send can.' - -function backgrounded({ worker = OPENED } = {}) { - const where = - worker === OPENED - ? `on branch ${BRANCH} in ${OPENED.path}, not in this checkout` - : `in this same checkout, ${SHARED.path}, and edits its files as you do` - return { - result: { status: 'async_launched', agentId: worker.name, description: AGENT.description, prompt: AGENT.prompt, outputFile: '' }, - context: [`The agent runs as the lich session "${worker.label}", ${where}. ${reportArrives}`], - } -} - -const whereItIs = - `\n\nThe work is on branch ${BRANCH} in ${OPENED.path} (lich session "${BRANCH}"), not in this checkout. ` + - `Reach that session with send_to_session or lich send, not SendMessage.` -const whereItIsHere = - `\n\nThe work is in this same checkout, ${SHARED.path} (lich session "${SHARED.label}"). ` + - `Reach that session with send_to_session or lich send, not SendMessage.` - -function assertNativeUntouched({ answer, passed, mod }, e = AGENT) { - assert.deepEqual(passed, [e]) - assert.equal(answer, NATIVE) - assert.deepEqual(mod.ran, []) -} - -// --------------------------------------------------------- what it leaves -- - -test('a call another plugin raised goes to the native agent', async () => { - const mod = load() - await mod.start() - assertNativeUntouched({ mod, ...(await mod.call(AGENT, { plugin: 'other-plugin' })) }) -}) - -test("a subagent's own Agent call goes to the native agent", async () => { - const mod = load() - await mod.start() - const e = { ...AGENT, agentId: 'a7f3' } - assertNativeUntouched({ mod, ...(await mod.call(e)) }, e) -}) - -test('every type but general-purpose stays native, an unknown one included', async () => { - for (const type of ['Explore', 'Plan', 'claude-code-guide', 'addon-studio:troubleshooter', 'does-not-exist']) { - const mod = load() - await mod.start() - const e = { ...AGENT, subagent_type: type } - assertNativeUntouched({ mod, ...(await mod.call(e)) }, e) - } -}) - -test("a worker on a branch this mod opened keeps its isolated subagents native", async () => { - const mod = load({ runs: [onBranch('subagent/fix-the-auth-flow-ab12')] }) - await mod.start() - const { answer, passed } = await mod.call(ISOLATED) - assert.deepEqual(passed, [ISOLATED]) - assert.equal(answer, NATIVE) - assert.equal(mod.ran.length, 1) -}) - -test('a remote agent stays native', async () => { - const e = { ...AGENT, isolation: 'remote' } - const mod = load() - await mod.start() - assertNativeUntouched({ ...(await mod.call(e)), mod }, e) -}) - -test('a teammate stays native', async () => { - const mod = load() - await mod.start() - const e = { ...AGENT, team_name: 'crew' } - assertNativeUntouched({ mod, ...(await mod.call(e)) }, e) -}) - -// A `claude -p` run from a tool inside a lich session inherits its variables. -test('a non-interactive run stays native', async () => { - const mod = load() - await mod.start(false) - assertNativeUntouched({ mod, ...(await mod.call()) }) -}) - -test('a session that never reported its start stays native', async () => { - const mod = load() - assertNativeUntouched({ mod, ...(await mod.call()) }) -}) - -test('subagents as lich sessions turned off in lich keeps every call native', async () => { - const mod = load({ env: { ...ENV, LICH_SUBAGENT_CARDS: 'off' } }) - await mod.start() - assertNativeUntouched({ mod, ...(await mod.call()) }) -}) - -// lich sets the depth on every Claude Code session it starts; at 0 the session -// is nobody's worker and cards off is only the user's setting. -test('a top-level session with subagent cards turned off stays native without a toast', async () => { - const mod = load({ env: { ...ENV, LICH_SUBAGENT_CARDS: 'off', LICH_SUBAGENT_DEPTH: '0' } }) - await mod.start() - assertNativeUntouched({ mod, ...(await mod.call()) }) - assert.deepEqual(mod.toasts, []) -}) - -test('a worker lich keeps native at its depth limit runs natively, with a toast saying why', async () => { - const mod = load({ env: { ...ENV, LICH_SUBAGENT_CARDS: 'off', LICH_SUBAGENT_DEPTH: '2' } }) - await mod.start() - assertNativeUntouched({ mod, ...(await mod.call()) }) - assert.deepEqual(mod.toasts, [ - 'lich: ran "Fix the auth flow" as a Claude Code subagent: this session is itself a lich subagent card, and lich keeps its subagents inside it', - ]) -}) - -// With the depth set, lich's LICH_SUBAGENT_CARDS is the only gate: the -// subagent/ branch an isolated worker sits on no longer keeps it native. -test('a worker below lich\'s depth limit opens cards of its own, even from a subagent/ branch', async () => { - const base = 'subagent/fix-the-auth-flow-ab12' - const { mod, answer, passed } = await delegate( - [onBranch(base), exits(0, opened('pending'))], - ISOLATED, - { env: { ...ENV, LICH_SUBAGENT_DEPTH: '1' } }, - ) - assert.deepEqual(passed, []) - assert.deepEqual(answer, backgrounded()) - assert.deepEqual(mod.ran[1].argv.slice(5, 9), ['--worktree', BRANCH, '--base', base]) -}) - -test('outside lich every call stays native', async () => { - for (const missing of ['LICH_BIN', 'LICH_SESSION_ID']) { - const env = { ...ENV } - delete env[missing] - const mod = load({ env }) - await mod.start() - assertNativeUntouched({ mod, ...(await mod.call()) }) - } -}) - -// --------------------------------------------------------------- the open -- - -test('a general-purpose call opens a Claude Code subagent session in this checkout, without asking git', async () => { - const { mod } = await delegate([exits(0, openedHere('answered', 'done'))]) - assert.deepEqual(mod.ran, [ - { - argv: [LICH_BIN, 'open', '--kind', 'claude', '--subagent', '--prompt', AGENT.prompt, '--json'], - init: { timeoutMs: 120000 }, - }, - ]) -}) - -test('an isolated call opens the session in a worktree off the current branch', async () => { - const { mod } = await delegate([onBranch('feat/login'), exits(0, opened('answered', 'done'))], ISOLATED) - assert.deepEqual(mod.ran, [ - { argv: ['git', 'branch', '--show-current'], init: undefined }, - { - argv: [ - LICH_BIN, 'open', '--kind', 'claude', '--subagent', '--worktree', BRANCH, '--base', 'feat/login', - '--prompt', AGENT.prompt, '--json', - ], - init: { timeoutMs: 120000 }, - }, - ]) -}) - -test('a call with no type is a general-purpose one', async () => { - const e = { ...AGENT } - delete e.subagent_type - const { mod, passed } = await delegate([exits(0, openedHere('answered', 'done'))], e) - assert.deepEqual(passed, []) - assert.equal(mod.ran[0].argv[1], 'open') -}) - -test('the model the call names is the model the session starts on', async () => { - const { mod } = await delegate([exits(0, openedHere('answered', 'done'))], { ...AGENT, model: 'haiku' }) - assert.deepEqual(mod.ran[0].argv.slice(4, 7), ['--subagent', '--model', 'haiku']) - const isolated = await delegate([onBranch('main'), exits(0, opened('answered', 'done'))], { ...ISOLATED, model: 'haiku' }) - assert.deepEqual(isolated.mod.ran[1].argv.slice(7, 11), ['--base', 'main', '--model', 'haiku']) -}) - -test('with no current branch an isolated session opens off lich\'s default base', async () => { - for (const git of [exits(0, '\n'), exits(128, '', 'fatal: not a git repository'), rejects('git: not found')]) { - const { mod } = await delegate([git, exits(0, opened('answered', 'done'))], ISOLATED) - assert.deepEqual(mod.ran[1].argv, [ - LICH_BIN, 'open', '--kind', 'claude', '--subagent', '--worktree', BRANCH, '--prompt', AGENT.prompt, '--json', - ]) - } -}) - -// ------------------------------------------------------------ the branch -- - -test('the branch is subagent/, a slug of the description and the end of the call id', async () => { - const cases = [ - ['Investigate why the websocket reconnect loop never stops retrying', 'investigate-why-the-websocket-reconnect'], - ['a b c d e f g', 'a-b-c-d-e'], - ['Corrigir autenticação do usuário', 'corrigir-autenticação-do-usuário'], - ['x'.repeat(50), 'x'.repeat(40)], - ['!!! ???', 'agent'], - ['', 'agent'], - ] - for (const [description, slug] of cases) { - const { mod } = await delegate([onBranch('main'), exits(0, opened('answered', 'done'))], { ...ISOLATED, description }) - assert.equal(mod.ran[1].argv[6], `subagent/${slug}-ab12`, description) - } -}) - -test('the suffix is the last four letters or digits of the call id, lowercased', async () => { - const e = { ...ISOLATED, tool_use_id: 'toolu_01XyZ_9Q' } - const { mod } = await delegate([onBranch('main'), exits(0, opened('answered', 'done'))], e) - assert.equal(mod.ran[1].argv[6], 'subagent/fix-the-auth-flow-yz9q') -}) - -// ------------------------------------------------------------- the report -- - -test('an answer at the open comes back as the completed subagent, with no worktree of its own', async () => { - const { answer, passed, mod } = await delegate([exits(0, openedHere('answered', 'Fixed; tests pass.'))]) - assert.deepEqual(answer, completed(`Fixed; tests pass.${whereItIsHere}`, { worker: SHARED })) - assert.deepEqual(passed, []) - assert.deepEqual(mod.toasts, []) -}) - -test('an isolated answer at the open comes back with its worktree', async () => { - const { answer } = await delegate([onBranch('main'), exits(0, opened('answered', 'Fixed; tests pass.'))], ISOLATED) - assert.deepEqual(answer, completed(`Fixed; tests pass.${whereItIs}`)) -}) - -test('a task still pending at the open comes back at once as a backgrounded agent, never waited on', async () => { - const { answer, passed, mod } = await delegate([exits(2, openedHere('pending'))]) - assert.deepEqual(answer, backgrounded({ worker: SHARED })) - assert.equal(mod.ran.length, 1) - assert.deepEqual(passed, []) - assert.deepEqual(mod.toasts, []) -}) - -test('an isolated task still pending at the open says which branch the worker is on', async () => { - const { answer } = await delegate([onBranch('main'), exits(2, opened('pending'))], ISOLATED) - assert.deepEqual(answer, backgrounded()) -}) - -// A worker whose turn ended before it reported is usually still working: it -// left a command running in the background and resumes when it finishes. Its -// report still arrives as a , so the call is a backgrounded agent, -// never a finished one. -test('a worker that ended its turn without reporting comes back as a backgrounded agent', async () => { - const { answer, passed } = await delegate([exits(3, openedHere('unanswered'))]) - assert.deepEqual(answer, backgrounded({ worker: SHARED })) - assert.deepEqual(passed, []) - const isolated = await delegate([onBranch('main'), exits(3, opened('unanswered'))], ISOLATED) - assert.deepEqual(isolated.answer, backgrounded()) -}) - -test('a task that never reached the worker is denied, never run natively', async () => { - for (const status of ['unread', 'undelivered']) { - const { answer, passed } = await delegate([onBranch('main'), exits(3, opened(status))], ISOLATED) - assert.deepEqual(answer, { deny: `the task never reached "${BRANCH}" (${status}): open its card.` }) - assert.deepEqual(passed, []) - } -}) - -// -------------------------------------------- failing over before delegation -- - -test('a task over lich\'s byte limit runs natively, with a toast saying why', async () => { - const e = { ...AGENT, prompt: 'é'.repeat(4097) } - const { mod, answer, passed } = await delegate([], e) - assert.deepEqual(passed, [e]) - assert.equal(answer, NATIVE) - assert.deepEqual(mod.ran, []) - assert.deepEqual(mod.toasts, [ - 'lich: ran "Fix the auth flow" as a Claude Code subagent: the task is 8194 bytes, over lich\'s 8192', - ]) -}) - -test('a task exactly at the byte limit goes to lich', async () => { - const e = { ...AGENT, prompt: 'é'.repeat(4096) } - const { passed } = await delegate([exits(0, openedHere('answered', 'done'))], e) - assert.deepEqual(passed, []) -}) - -test('an open that failed runs natively, with lich\'s reason in a toast', async () => { - const { mod, answer, passed } = await delegate([exits(1, '', 'lich: no lich is running\n')]) - assert.deepEqual(passed, [AGENT]) - assert.equal(answer, NATIVE) - assert.deepEqual(mod.toasts, ['lich: ran "Fix the auth flow" as a Claude Code subagent: lich: no lich is running']) -}) - -test('an open whose task never reached the session runs natively, naming the card', async () => { - const { mod, passed } = await delegate([ - exits(1, OPENED, 'lich: the session is open, but the task did not reach it: its terminal ended\n'), - ]) - assert.deepEqual(passed, [AGENT]) - assert.equal(mod.toasts.length, 1) - assert.match(mod.toasts[0], new RegExp(`^lich: ran "Fix the auth flow" as a Claude Code subagent: the task did not reach "${BRANCH}"`)) -}) - -test('an open that could not run at all runs natively, with a toast', async () => { - const { mod, passed } = await delegate([rejects('$.process.run(lich) aborted: still running after 120000ms')]) - assert.deepEqual(passed, [AGENT]) - assert.deepEqual(mod.toasts, [ - 'lich: ran "Fix the auth flow" as a Claude Code subagent: $.process.run(lich) aborted: still running after 120000ms', - ]) -}) - -// Esc while the open is in flight: lich may already have opened the card and -// handed it the task, so running the agent natively as well could do it twice. -test('an open the user interrupted is denied, never run natively', async () => { - const interrupted = () => { - const stop = new AbortController() - const run = () => { - stop.abort() - return Promise.reject(new Error('$.process.run(lich) aborted')) - } - return { run, signal: stop.signal } - } - const here = interrupted() - const { answer, passed, mod } = await delegate([here.run], AGENT, { signal: here.signal }) - assert.deepEqual(passed, []) - assert.deepEqual(mod.toasts, []) - assert.deepEqual(answer, { - deny: 'interrupted; a lich session may already have the task, and a report it sends arrives here as a .', - }) - const isolated = interrupted() - const onItsBranch = await delegate([onBranch('main'), isolated.run], ISOLATED, { signal: isolated.signal }) - assert.deepEqual(onItsBranch.answer, { - deny: `interrupted; a lich session on branch ${BRANCH} may already have the task, and a report it sends arrives here as a .`, - }) -}) - -// ------------------------------------------------------------ permission -- - -// Claude Code refuses the call beneath the mod's `next` (a deny rule, the -// mode, the user's "no" in the dialog, a PreToolUse hook) and never raises -// `agent.spawn`: the refusal stands and lich opens nothing. -test('a call Claude Code refused opens no lich session', async () => { - for (const e of [AGENT, ISOLATED]) { - const runs = e === ISOLATED ? [onBranch('main')] : [] - const { mod, answer, passed } = await delegate(runs, e, { permission: 'reject' }) - assert.equal(answer, REJECTED) - assert.deepEqual(passed, []) - assert.equal(mod.ran.some(({ argv }) => argv[0] === LICH_BIN), false) - assert.deepEqual(mod.statuses, []) - } -}) - -test('a refused call leaves the next allowed one to open its session', async () => { - const mod = load({ runs: [exits(2, openedHere('pending'))] }) - await mod.start() - await mod.call(AGENT, { permission: 'reject' }) - const { answer } = await mod.call(AGENT) - assert.deepEqual(answer, backgrounded({ worker: SHARED })) -}) - -// ------------------------------------------------ never native after delegation -- - -test('a status this mod does not know is denied, never run natively', async () => { - const { answer, passed } = await delegate([exits(3, openedHere('mislaid'))]) - assert.deepEqual(passed, []) - assert.deepEqual(answer, { deny: `lich answered "mislaid" about "${SHARED.label}": open its card.` }) - const isolated = await delegate([onBranch('main'), exits(3, opened('mislaid'))], ISOLATED) - assert.deepEqual(isolated.answer, { deny: `lich answered "mislaid" about "${BRANCH}", on branch ${BRANCH}: open its card.` }) -}) - -// ---------------------------------------------------- workers in the status line -- - -// What `lich sessions --json` prints (relay.Peer in lich): the live sessions -// this one can address, each with the state its hooks last reported. -const peer = (worker, state) => ({ label: worker.label, name: worker.name, project: worker.project, kind: 'claude', state }) -const listed = (...peers) => exits(0, peers) -const SESSIONS = [LICH_BIN, 'sessions', '--json'] - -// A worker in this checkout is closed once it reported, so it runs until lich -// stops listing it: a turn it ended with a command left in the background is -// done but not finished. -test('a worker in this checkout shows in the status line until lich closes it', async () => { - const { mod } = await delegate([exits(2, openedHere('pending'))]) - assert.deepEqual(mod.statuses, ['lich: 1 worker']) - assert.equal(mod.timers.length, 1) - - await mod.tick(listed(peer(SHARED, 'busy'))) - assert.deepEqual(mod.ran.at(-1).argv, SESSIONS) - await mod.tick(listed(peer(SHARED, 'done'))) - assert.deepEqual(mod.statuses, ['lich: 1 worker']) - assert.equal(mod.timers.length, 1) - - await mod.tick(listed()) - assert.deepEqual(mod.statuses, ['lich: 1 worker', undefined]) - assert.equal(mod.timers.length, 0) -}) - -// An isolated worker keeps its card and worktree after it reported, so a done -// turn is the end there. -test('an isolated worker shows in the status line until lich lists its turn done', async () => { - const { mod } = await delegate([onBranch('main'), exits(2, opened('pending'))], ISOLATED) - await mod.tick(listed(peer(OPENED, 'busy'))) - assert.deepEqual(mod.statuses, ['lich: 1 worker']) - await mod.tick(listed(peer(OPENED, 'done'))) - assert.deepEqual(mod.statuses, ['lich: 1 worker', undefined]) -}) - -test('a worker waiting on a permission, or not reported yet, is still running', async () => { - const { mod } = await delegate([exits(2, openedHere('pending'))]) - await mod.tick(listed(peer(SHARED, 'waiting'))) - await mod.tick(listed(peer(SHARED, ''))) - assert.deepEqual(mod.statuses, ['lich: 1 worker']) - assert.equal(mod.timers.length, 1) -}) - -test('a worker lich no longer lists, closed once it reported, is finished', async () => { - const { mod } = await delegate([exits(2, openedHere('pending'))]) - await mod.tick(listed()) - assert.deepEqual(mod.statuses, ['lich: 1 worker', undefined]) - assert.equal(mod.timers.length, 0) -}) - -test('two workers count as two, and one finishing leaves one', async () => { - const mod = load({ runs: [exits(2, openedHere('pending')), onBranch('main'), exits(2, opened('pending'))], times: [1, 2, 3, 4] }) - await mod.start() - await mod.call(AGENT) - await mod.call(ISOLATED) - assert.deepEqual(mod.statuses, ['lich: 1 worker', 'lich: 2 workers']) - assert.equal(mod.timers.length, 1, 'one watch for every worker') - - await mod.tick(listed(peer(OPENED, 'busy'))) - assert.deepEqual(mod.statuses.at(-1), 'lich: 1 worker') -}) - -test('a list lich could not give keeps the count and asks again', async () => { - const { mod } = await delegate([exits(2, openedHere('pending'))]) - await mod.tick(exits(1, '', 'lich: no lich is running\n')) - await mod.tick(rejects('$.process.run(lich) failed')) - assert.deepEqual(mod.statuses, ['lich: 1 worker']) - assert.equal(mod.timers.length, 1) -}) - -test('a worker that answered at the open is never counted', async () => { - const { mod } = await delegate([exits(0, openedHere('answered', 'done'))]) - assert.deepEqual(mod.statuses, []) - assert.equal(mod.timers.length, 0) -}) - -// ---------------------------------------------------------------- TaskStop -- - -// Measured on Claude Code 2.1.289: TaskStop takes the agentId the Agent call -// answered as `task_id`, and answers with this shape. -const taskStop = (id) => ({ tool: 'TaskStop', task_id: id }) -const stopped = (id) => ({ - result: { - message: `Successfully stopped task: ${id} (${AGENT.description})`, - task_id: id, - task_type: 'local_agent', - command: AGENT.description, - }, -}) - -test('TaskStop on a worker in this checkout closes its session, which keeps nothing of its own', async () => { - const { mod } = await delegate([exits(2, openedHere('pending'))]) - mod.answer(exits(0, `Closed "${SHARED.label}".\n`)) - const { answer, passed } = await mod.call(taskStop(SHARED.name)) - assert.deepEqual(mod.ran.at(-1).argv, [LICH_BIN, 'close', SHARED.name]) - assert.deepEqual(passed, []) - assert.deepEqual(answer, stopped(SHARED.name)) - assert.deepEqual(mod.statuses, ['lich: 1 worker', undefined]) -}) - -test('TaskStop on an isolated worker stops its turn and leaves its worktree and card', async () => { - const { mod } = await delegate([onBranch('main'), exits(2, opened('pending'))], ISOLATED) - mod.answer(exits(0, `"${OPENED.label}" stopped its turn.\n`)) - const { answer } = await mod.call(taskStop(OPENED.name)) - assert.deepEqual(mod.ran.at(-1).argv, [LICH_BIN, 'control', OPENED.name, 'abort']) - assert.deepEqual(answer, stopped(OPENED.name)) - assert.deepEqual(mod.statuses.at(-1), undefined) -}) - -test('TaskStop on a task that is not a lich worker goes to Claude Code untouched', async () => { - const mod = load() - await mod.start() - const e = taskStop('a712043a56e1aafb1') - const { answer, passed } = await mod.call(e) - assert.deepEqual(passed, [e]) - assert.equal(answer, NATIVE) - assert.deepEqual(mod.ran, []) -}) - -test('TaskStop lich could not carry out is refused with its reason, and the worker still counts', async () => { - const { mod } = await delegate([exits(2, openedHere('pending'))]) - mod.answer(exits(1, '', `lich: no session named "${SHARED.name}"\n`)) - const { answer, passed } = await mod.call(taskStop(SHARED.name)) - assert.deepEqual(passed, []) - assert.deepEqual(answer, { deny: `lich could not stop "${SHARED.label}": lich: no session named "${SHARED.name}"` }) - assert.deepEqual(mod.statuses, ['lich: 1 worker']) -}) diff --git a/tests/contract.mjs b/tests/contract.mjs index d5ceb0d..e38d529 100644 --- a/tests/contract.mjs +++ b/tests/contract.mjs @@ -39,7 +39,7 @@ export const FIXTURE_OF = { '/session-touched': 'session-touched', '/mod/acks': 'mod-control', '/mod/usage': 'mod-usage', - '/mod/answer': 'mod-answer', + '/subagent': 'subagent-cards', } const readFixture = (name) => @@ -60,7 +60,7 @@ export const rejected = (endpoint) => CASES[endpoint].filter((c) => c.reject) export const STATES = new Set(accepted('/hook').map((c) => c.accept.state)) export const PROVIDERS = new Set(accepted('/session-start').map((c) => c.accept.provider)) export const MOD_KINDS = new Set(accepted('/mod/acks').map((c) => c.body.kind)) -export const UNANSWERED = new Set(accepted('/mod/answer').flatMap((c) => c.body.unanswered ?? [])) +export const SUBAGENT_CALLS = new Set(accepted('/subagent').map((c) => c.body.call).filter(Boolean)) /** * Providers this plugin already reports for, and lich does not accept yet. @@ -135,14 +135,15 @@ export const REJECT_RULES = { 'negative cost': (b) => b.cost_usd < 0, 'malformed json': (b, raw) => !isJsonObject(raw), }, - '/mod/answer': { - 'missing session_id': (b) => !('session_id' in b), - 'neither text nor unanswered': (b) => !('text' in b) && !('unanswered' in b), - 'text and unanswered together': (b) => 'text' in b && 'unanswered' in b, - 'an aborted turn is not reported': (b) => 'unanswered' in b && !UNANSWERED.has(b.unanswered), - 'blank text': (b) => typeof b.text === 'string' && b.text.trim() === '', - 'text is not a string': (b) => 'text' in b && typeof b.text !== 'string', - 'malformed json': (b, raw) => !isJsonObject(raw), + '/subagent': { + 'no tasks on a spawn': (b) => (b.call ?? 'spawn') === 'spawn' && (b.tasks ?? []).length === 0, + 'a task with no prompt': (b) => b.sealed !== true && (b.tasks ?? []).some((t) => blank(t.prompt)), + 'a wait carrying tasks': (b) => b.call === 'wait' && (b.tasks ?? []).length > 0, + 'an unknown call': (b) => 'call' in b && !SUBAGENT_CALLS.has(b.call), + 'an unknown isolation': (b) => typeof b.isolation === 'string' && !['', 'worktree'].includes(b.isolation.trim()), + 'no session id': (b) => !('session_id' in b), + 'no tool': (b) => blank(b.tool), + 'not JSON': (b, raw) => !isJsonObject(raw), }, '/mod/acks': { 'missing session_id': (b) => !('session_id' in b), @@ -174,7 +175,9 @@ export function isJsonObject(raw) { * Returns the name of the case it matches, or null. */ export function matchingAcceptCase(endpoint, body) { - const field = (o, k) => `${k}:${blank(o[k]) ? typeof o[k] + '(blank)' : typeof o[k]}` + const free = FREE_TEXT[endpoint] ?? [] + const field = (o, k) => + free.includes(k) ? `${k}:${typeof o[k]}` : `${k}:${blank(o[k]) ? typeof o[k] + '(blank)' : typeof o[k]}` const shape = (o) => Object.keys(o).sort().map((k) => field(o, k)).join(',') const rest = { ...body } for (const k of ANY_SHAPE[endpoint] ?? []) { @@ -194,6 +197,14 @@ export function matchingAcceptCase(endpoint, body) { */ const ANY_SHAPE = { '/hook': ['provider_session_id'] } +/** + * Fields whose value is whatever the provider gave, blank included, so only + * their type is the shape. subagent-cards.md: `tool_use_id` is empty when the + * provider gives none, `model` and `isolation` when the call asks for none, and + * the conversation is the provider's to name. + */ +const FREE_TEXT = { '/subagent': ['provider_session_id', 'tool_use_id', 'model', 'isolation'] } + export function assertContractHonoured(endpoint, request) { assert.equal( request.url, @@ -245,8 +256,11 @@ const liveStubs = new Set() */ export const settleStubs = () => Promise.all([...liveStubs].map((stub) => stub.settle())) -/** `status` is the answer to every request, or a function of the request. */ -export async function startStub({ status = 204 } = {}) { +/** + * `status` is the answer to every request, or a function of the request. + * `body`, when given, is the JSON text answered with it; `hang` never answers. + */ +export async function startStub({ status = 204, body, hang = false } = {}) { const requests = [] const sockets = new Set() const server = createServer((req, res) => { @@ -257,7 +271,10 @@ export async function startStub({ status = 204 } = {}) { }) req.on('end', () => { requests.push({ method: req.method, url: req.url, headers: req.headers, raw }) - res.writeHead(typeof status === 'function' ? status(req) : status).end() + if (hang) return + const code = typeof status === 'function' ? status(req) : status + if (body === undefined) res.writeHead(code).end() + else res.writeHead(code, { 'content-type': 'application/json' }).end(body) }) }) server.on('connection', (socket) => { diff --git a/tests/fixtures/mod-answer.jsonl b/tests/fixtures/mod-answer.jsonl deleted file mode 100644 index 18803b1..0000000 --- a/tests/fixtures/mod-answer.jsonl +++ /dev/null @@ -1,13 +0,0 @@ -{"name":"a worker's report","body":{"session_id":"s1","text":"Rewrote docs/cli.md; the tests pass."},"accept":{"session_id":"s1","text":"Rewrote docs/cli.md; the tests pass."}} -{"name":"a report keeps its lines","body":{"session_id":"s1","text":"Done.\n\n- a < b && c > d\n- `go test` green"},"accept":{"text":"Done.\n\n- a < b && c > d\n- `go test` green"}} -{"name":"extra fields are ignored","body":{"session_id":"s1","text":"Done.","turn_id":"t"},"accept":{"text":"Done."}} -{"name":"missing session_id","body":{"text":"Done."},"reject":"session_id is required"} -{"name":"neither text nor unanswered","body":{"session_id":"s1"},"reject":"exactly one of text and unanswered"} -{"name":"blank text","body":{"session_id":"s1","text":" \n\t"},"reject":"a blank text is no answer"} -{"name":"text is not a string","body":{"session_id":"s1","text":42},"reject":"text must be a string"} -{"name":"malformed json","raw":"{","reject":"body must be a JSON object"} -{"name":"a blank turn","body":{"session_id":"s1","unanswered":"blank"},"accept":{"session_id":"s1","unanswered":"blank"}} -{"name":"an api error","body":{"session_id":"s1","unanswered":"error"},"accept":{"unanswered":"error"}} -{"name":"a refusal","body":{"session_id":"s1","unanswered":"refusal"},"accept":{"unanswered":"refusal"}} -{"name":"an aborted turn is not reported","body":{"session_id":"s1","unanswered":"aborted"},"reject":"unanswered must be blank, error or refusal"} -{"name":"text and unanswered together","body":{"session_id":"s1","text":"Done.","unanswered":"blank"},"reject":"exactly one of text and unanswered"} diff --git a/tests/fixtures/subagent-cards.jsonl b/tests/fixtures/subagent-cards.jsonl new file mode 100644 index 0000000..9497d32 --- /dev/null +++ b/tests/fixtures/subagent-cards.jsonl @@ -0,0 +1,33 @@ +{"name": "a Claude Code general-purpose call becomes a card", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"call": "spawn", "tool": "Agent", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}]}, "answer": {"decision": "deny", "reason": "lich opened this task as the session \"Fix #412\" (ticket 4b9bc94e). Its report reaches you as a . Do not retry the tool and do not do the task yourself.", "sessions": [{"id": "w1", "label": "Fix #412", "ticket": "4b9bc94e"}]}} +{"name": "a Claude Code call naming no type runs as general-purpose", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": ""}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tool": "Agent"}, "answer": {"decision": "deny", "reason": "lich opened this task as the session \"Fix #412\" (ticket 4b9bc94e). Its report reaches you as a . Do not retry the tool and do not do the task yourself.", "sessions": [{"id": "w1", "label": "Fix #412", "ticket": "4b9bc94e"}]}} +{"name": "a typed Claude Code agent stays native", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Find callers", "prompt": "Find every caller of handshake().", "type": "Explore"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tool": "Agent"}, "answer": {"decision": "allow"}} +{"name": "a call from inside a native subagent stays native", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": true, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"nested": true}, "answer": {"decision": "allow"}} +{"name": "a session as deep as cards nest keeps its subagents native", "depth": 2, "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"session_id": "s1"}, "answer": {"decision": "allow"}} +{"name": "a Codex worker spawn becomes a card", "kind": "codex", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "spawn_agent", "tool_use_id": "exec-1", "tasks": [{"title": "", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": ""}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tool": "spawn_agent", "tool_use_id": "exec-1"}, "answer": {"decision": "deny", "reason": "lich opened this task as the session \"Fix #412\" (ticket 4b9bc94e). Its report reaches you as a . Do not retry the tool and do not do the task yourself.", "sessions": [{"id": "w1", "label": "Fix #412", "ticket": "4b9bc94e"}]}} +{"name": "a Codex explorer stays native", "kind": "codex", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "spawn_agent", "tool_use_id": "exec-1", "tasks": [{"title": "", "prompt": "List the files in the workspace.", "type": "explorer"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tasks": [{"title": "", "prompt": "List the files in the workspace.", "type": "explorer"}]}, "answer": {"decision": "allow"}} +{"name": "a sealed Codex spawn is redirected to open_session and opens nothing", "kind": "codex", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "collaborationspawn_agent", "tool_use_id": "exec-2", "tasks": [{"title": "fix_handshake", "prompt": "", "type": ""}], "model": "", "sealed": true, "isolation": "", "background": false}, "accept": {"sealed": true, "tasks": [{"title": "fix_handshake", "prompt": "", "type": ""}]}, "answer": {"decision": "deny", "reason": "lich cannot read this task: the tool hands it over encrypted. Hand the same task to lich's open_session tool instead, writing its prompt in full; its report reaches you as a . Do not retry this tool."}} +{"name": "a wait after every spawn was denied is denied", "kind": "codex", "before": [{"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "spawn_agent", "tool_use_id": "exec-1", "tasks": [{"title": "", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": ""}], "model": "", "sealed": false, "isolation": "", "background": false}], "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "wait", "tool": "collaborationwait_agent", "tool_use_id": "exec-3", "tasks": [], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"call": "wait", "tasks": []}, "answer": {"decision": "deny", "reason": "No native subagent is running: lich opened every task as a session of its own, and each report reaches you as a at your prompt. End your turn instead of waiting here."}} +{"name": "a wait after a sealed spawn is denied", "kind": "codex", "before": [{"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "collaborationspawn_agent", "tool_use_id": "exec-2", "tasks": [{"title": "fix_handshake", "prompt": "", "type": ""}], "model": "", "sealed": true, "isolation": "", "background": false}], "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "wait", "tool": "collaborationwait_agent", "tool_use_id": "exec-3", "tasks": [], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"call": "wait"}, "answer": {"decision": "deny", "reason": "No native subagent is running: lich opened every task as a session of its own, and each report reaches you as a at your prompt. End your turn instead of waiting here."}} +{"name": "a wait after a spawn lich allowed is allowed", "kind": "codex", "before": [{"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "spawn_agent", "tool_use_id": "exec-1", "tasks": [{"title": "", "prompt": "List the files in the workspace.", "type": "explorer"}], "model": "", "sealed": false, "isolation": "", "background": false}], "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "wait", "tool": "collaborationwait_agent", "tool_use_id": "exec-3", "tasks": [], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"call": "wait"}, "answer": {"decision": "allow"}} +{"name": "a wait with no spawn seen is allowed", "kind": "codex", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "wait", "tool": "collaborationwait_agent", "tool_use_id": "exec-3", "tasks": [], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"call": "wait"}, "answer": {"decision": "allow"}} +{"name": "a Kiro call starting two subagents opens two cards", "kind": "kiro", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "use_subagent", "tool_use_id": "tooluse_1", "tasks": [{"title": "", "prompt": "Map the relay package.", "type": ""}, {"title": "", "prompt": "Fix #412.", "type": ""}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tool": "use_subagent"}, "answer": {"decision": "deny", "reason": "lich opened these tasks as the sessions \"Fix #412\" (ticket 4b9bc94e), \"Docs sweep\" (ticket 7c1d2e3f). Their reports reach you as blocks. Do not retry the tool and do not do the tasks yourself.", "sessions": [{"id": "w1", "label": "Fix #412", "ticket": "4b9bc94e"}, {"id": "w2", "label": "Docs sweep", "ticket": "7c1d2e3f"}]}} +{"name": "an oh-my-pi call with a scout among its tasks stays native as a whole", "kind": "omp", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "task", "tool_use_id": "toolu_1", "tasks": [{"title": "scan", "prompt": "Map the relay package.", "type": "scout"}, {"title": "fix", "prompt": "Fix #412.", "type": "task"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tasks": [{"title": "scan", "prompt": "Map the relay package.", "type": "scout"}, {"title": "fix", "prompt": "Fix #412.", "type": "task"}]}, "answer": {"decision": "allow"}} +{"name": "a worktree-isolated call", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "worktree", "background": false}, "accept": {"isolation": "worktree"}, "answer": {"decision": "deny", "reason": "lich opened this task as the session \"Fix #412\" (ticket 4b9bc94e). Its report reaches you as a . Do not retry the tool and do not do the task yourself.", "sessions": [{"id": "w1", "label": "Fix #412", "ticket": "4b9bc94e"}]}} +{"name": "isolation is trimmed", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": " worktree ", "background": false}, "accept": {"isolation": "worktree"}, "answer": {"decision": "deny", "reason": "lich opened this task as the session \"Fix #412\" (ticket 4b9bc94e). Its report reaches you as a . Do not retry the tool and do not do the task yourself.", "sessions": [{"id": "w1", "label": "Fix #412", "ticket": "4b9bc94e"}]}} +{"name": "the same tool call twice opens one card", "before": [{"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}], "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tool_use_id": "toolu_1"}, "answer": {"decision": "deny", "reason": "lich opened this task as the session \"Fix #412\" (ticket 4b9bc94e). Its report reaches you as a . Do not retry the tool and do not do the task yourself.", "sessions": [{"id": "w1", "label": "Fix #412", "ticket": "4b9bc94e"}]}} +{"name": "a new call with the same prompt while its worker runs opens nothing", "before": [{"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}], "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_2", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tool_use_id": "toolu_2"}, "answer": {"decision": "deny", "reason": "lich opened this task as the session \"Fix #412\" (ticket 4b9bc94e). Its report reaches you as a . Do not retry the tool and do not do the task yourself.", "sessions": [{"id": "w1", "label": "Fix #412", "ticket": "4b9bc94e"}]}} +{"name": "a prompt over 8 KB runs natively as a whole", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "long", "prompt": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tool": "Agent"}, "answer": {"decision": "allow"}} +{"name": "call defaults to spawn", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"call": "spawn"}, "answer": {"decision": "deny", "reason": "lich opened this task as the session \"Fix #412\" (ticket 4b9bc94e). Its report reaches you as a . Do not retry the tool and do not do the task yourself.", "sessions": [{"id": "w1", "label": "Fix #412", "ticket": "4b9bc94e"}]}} +{"name": "an opencode explore stays native", "kind": "opencode", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "task", "tool_use_id": "toolu_1", "tasks": [{"title": "Map it", "prompt": "Map the relay package.", "type": "explore"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tool": "task"}, "answer": {"decision": "allow"}} +{"name": "an Antigravity research stays native", "kind": "antigravity", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "invoke_subagent", "tool_use_id": "toolu_1", "tasks": [{"title": "Map it", "prompt": "Map the relay package.", "type": "research"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tool": "invoke_subagent"}, "answer": {"decision": "allow"}} +{"name": "a Cursor CLI explore stays native", "kind": "cursor", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Task", "tool_use_id": "toolu_1", "tasks": [{"title": "Map it", "prompt": "Map the relay package.", "type": "explore"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tool": "Task"}, "answer": {"decision": "allow"}} +{"name": "a Kiro CLI call keeps no type native", "kind": "kiro", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "subagent", "tool_use_id": "toolu_1", "tasks": [{"title": "Map it", "prompt": "Map the relay package.", "type": "explore"}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tool": "subagent"}, "answer": {"decision": "deny", "reason": "lich opened this task as the session \"Fix #412\" (ticket 4b9bc94e). Its report reaches you as a . Do not retry the tool and do not do the task yourself.", "sessions": [{"id": "w1", "label": "Fix #412", "ticket": "4b9bc94e"}]}} +{"name": "a Crush agent call becomes a card", "kind": "crush", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Map it", "prompt": "Map the relay package.", "type": ""}], "model": "", "sealed": false, "isolation": "", "background": false}, "accept": {"tool": "agent"}, "answer": {"decision": "deny", "reason": "lich opened this task as the session \"Fix #412\" (ticket 4b9bc94e). Its report reaches you as a . Do not retry the tool and do not do the task yourself.", "sessions": [{"id": "w1", "label": "Fix #412", "ticket": "4b9bc94e"}]}} +{"name": "no tasks on a spawn", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [], "model": "", "sealed": false, "isolation": "", "background": false}, "reject": "a spawn starts at least one subagent"} +{"name": "a task with no prompt", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "x", "prompt": " ", "type": ""}], "model": "", "sealed": false, "isolation": "", "background": false}, "reject": "every task needs a prompt unless the call is sealed"} +{"name": "a wait carrying tasks", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "wait", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}, "reject": "a wait carries no tasks"} +{"name": "an unknown call", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "cancel", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}, "reject": "call is spawn or wait"} +{"name": "an unknown isolation", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "remote", "background": false}, "reject": "isolation is worktree or empty"} +{"name": "no session id", "body": {"provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "Agent", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}, "reject": "session_id is required"} +{"name": "no tool", "body": {"session_id": "s1", "provider_session_id": "p1", "nested": false, "call": "spawn", "tool": "", "tool_use_id": "toolu_1", "tasks": [{"title": "Fix the handshake race", "prompt": "Fix #412: the relay handshake races on reconnect.", "type": "general-purpose"}], "model": "", "sealed": false, "isolation": "", "background": false}, "reject": "tool is required"} +{"name": "not JSON", "raw": "{\"session_id\":", "reject": "body is not JSON"} diff --git a/tests/hooks.test.mjs b/tests/hooks.test.mjs index ba3dca5..1fbbe14 100644 --- a/tests/hooks.test.mjs +++ b/tests/hooks.test.mjs @@ -174,12 +174,29 @@ const eventsIn = (json) => json.hooks ?? json.lich * off here, so every assertion below stays about the report the script sent. */ function splitVerdict(command) { + const chained = command.match(ANTIGRAVITY_VETO_CHAIN) + if (chained) return { report: chained[1], stdout: chained[2] } const m = command.match(/;\s*printf\s+'(.*)'\s*$/) return m ? { report: command.slice(0, m.index), stdout: m[1] } : { report: command, stdout: '' } } +/** + * Antigravity's `PreToolUse` runs the tool report and the subagent veto as one + * command, so the tool call gets one verdict: how it would merge two is not + * measured. Both read the one payload, which the command keeps in a variable. + * The verdict is the veto's: for a call that starts no subagent it answers the + * allow the fallback spells, which is the stdout asserted here. The veto has + * its own suite (subagent.test.mjs). + */ +const ANTIGRAVITY_VETO_CHAIN = + /^payload=\$\(cat\); printf '%s' "\$payload" \| (hooks\/[a-z-]+\.sh); printf '%s' "\$payload" \| hooks\/veto-subagent\.sh antigravity \|\| printf '(.*)'$/ + +/** The subagent veto is no report: subagent.test.mjs runs its registrations. */ +const VETO_SCRIPT = 'veto-subagent.sh' + + function registrations() { const out = [] for (const { provider, file, pluginRoot = true } of HOOK_FILES) { @@ -189,6 +206,7 @@ function registrations() { for (const [event, groups] of Object.entries(events)) { for (const group of groups) { for (const hook of hooksIn(group)) { + if (hook.command.includes(VETO_SCRIPT) && !ANTIGRAVITY_VETO_CHAIN.test(hook.command)) continue const script = Object.keys(SCRIPTS).find((s) => hook.command.includes(s)) assert.ok(script, `unknown script in ${file}: ${hook.command}`) const command = hook.command.split(PLUGIN_ROOT_PLACEHOLDER).join(SPACED_ROOT) @@ -201,6 +219,7 @@ function registrations() { command, pluginRoot, stdout, + report, script, endpoint: SCRIPTS[script], argument: report.trim().split(/\s+/).slice(1).join(' '), @@ -480,9 +499,12 @@ test("Codex's registration runs every hook through the wrapper on Windows", () = assert.ok(hooks.length > 0) for (const hook of hooks) { assert.ok(hook.commandWindows, `no commandWindows for ${hook.command}`) + // The veto's answer is on stdout, which win-run.cmd drops: win-veto.cmd + // keeps it. + const wrapper = hook.command.includes(VETO_SCRIPT) ? 'win-veto.cmd' : 'win-run.cmd' assert.equal( hook.commandWindows, - `"\${CLAUDE_PLUGIN_ROOT}/hooks/win-run.cmd" ${hook.command}`, + `"\${CLAUDE_PLUGIN_ROOT}/hooks/${wrapper}" ${hook.command}`, `commandWindows must wrap the command unchanged: ${hook.command}`, ) } @@ -502,7 +524,7 @@ test("Antigravity's registration reaches for no plugin root", () => { ) for (const r of REGISTRATIONS.filter((r) => r.provider === 'antigravity')) { assert.match( - r.command, + r.report, /^hooks\/[a-z-]+\.sh\b/, `command must be relative to the plugin root: ${r.command}`, ) diff --git a/tests/prompt-text.test.mjs b/tests/prompt-text.test.mjs index 1002aed..89bea2c 100644 --- a/tests/prompt-text.test.mjs +++ b/tests/prompt-text.test.mjs @@ -9,7 +9,6 @@ import { test } from 'node:test' import assert from 'node:assert/strict' import { en, ptBR, zhCN, es, ja, ko, ru, say, promptLang } from '../hooks/prompt-text.js' -import { register as registerAgentCards } from '../hooks/agent-cards.js' import { register as registerEditGuard } from '../hooks/edit-guard.js' import { register as registerSelfCommand } from '../hooks/self-command.js' import { register as registerModControl } from '../hooks/mod-control.js' @@ -44,8 +43,8 @@ test('names that must stay literal are kept in every translation', () => { }) test('an unknown or absent language says the English text', () => { - for (const lang of [undefined, '', 'fr', 'PT-br']) assert.equal(say(lang, 'lichExited', { code: 2 }), 'lich exited 2') - assert.equal(say('pt-BR', 'lichExited', { code: 2 }), 'o lich saiu com 2') + for (const lang of [undefined, '', 'fr', 'PT-br']) assert.equal(say(lang, 'editNoteAgo', { minutes: 2 }), '2 min ago') + assert.equal(say('pt-BR', 'editNoteAgo', { minutes: 2 }), 'há 2 min') }) test('a key no catalog has is an error, not an empty text', () => { @@ -76,68 +75,6 @@ function hooksOf(register) { const pass = (value) => async () => value const exits = (code, stdout = '', stderr = '') => ({ exitCode: code, stdout, stderr }) -// Beneath an Agent call it allowed, Claude Code raises `agent.spawn` before the -// native agent starts (measured on 2.1.296), which is where the mod opens lich. -const allowedAgent = (hooks, $) => { - const signal = new AbortController().signal - const spawn = async (e) => { - const spawned = await hooks.get('agent.spawn')($, { tool_use_id: e.tool_use_id }, Object.assign(pass({ model: 'm' }), { signal })) - return spawned.deny === undefined ? { result: 'native' } : { result: `Error: ${spawned.deny}`, isError: true } - } - return Object.assign(spawn, { origin: { plugin: 'engine' }, signal }) -} - -test('agent-cards: the background note, the completed addendum and the denies speak pt-BR', async () => { - const OPENED = { name: 'w-1', label: 'w', path: '/wt/w', id: 'x' } - const env = { ...PT, LICH_BIN: '/lich', LICH_SESSION_ID: 'lich-1' } - const call = async (status, { stderr = '' } = {}) => { - const hooks = hooksOf(registerAgentCards) - const runs = [exits(2, JSON.stringify({ ...OPENED, delivery: { ticket: 't', target: 'w', status, answer: 'feito' } }), stderr)] - const $ = { - env: { get: async (n) => env[n] }, - clock: { now: async () => 0, after: () => ({ cancel() {} }) }, - process: { run: async () => runs.shift() }, - ui: { toast() {}, invalidate() {} }, - } - await hooks.get('session.start')($, { isInteractive: true }, async (x) => x) - const e = { tool: 'Agent', tool_use_id: 't1', description: 'd', prompt: 'p', subagent_type: 'general-purpose' } - return hooks.get('tool.call Agent')($, e, allowedAgent(hooks, $)) - } - - const background = await call('pending') - assert.match(background.context[0], /^O agente roda como a sessão lich "w", neste mesmo checkout, \/wt\/w/) - assert.match(background.context[0], /.*wait_for_answer.*SendMessage.*send_to_session ou lich send/) - - const done = await call('answered') - assert.match(done.result.content[0].text, /^feito\n\nO trabalho está neste mesmo checkout, \/wt\/w \(sessão lich "w"\)\./) - - assert.equal((await call('unread')).deny, 'a tarefa nunca chegou a "w" (unread): abra o card dela.') -}) - -test('agent-cards: TaskStop failure speaks pt-BR, the success message stays Claude Code\'s own wording', async () => { - const env = { ...PT, LICH_BIN: '/lich', LICH_SESSION_ID: 'lich-1' } - const hooks = hooksOf(registerAgentCards) - const runs = [ - exits(2, JSON.stringify({ name: 'w-1', label: 'w', path: '/w', delivery: { ticket: 't', target: 'w', status: 'pending', answer: '' } })), - exits(1, '', 'boom'), - exits(0, 'ok'), - ] - const $ = { - env: { get: async (n) => env[n] }, - clock: { now: async () => 0, after: () => ({ cancel() {} }) }, - process: { run: async () => runs.shift() }, - ui: { toast() {}, invalidate() {} }, - } - await hooks.get('session.start')($, { isInteractive: true }, async (x) => x) - const next = Object.assign(pass({ result: 'native' }), { origin: { plugin: 'engine' }, signal: new AbortController().signal }) - await hooks.get('tool.call Agent')($, { tool: 'Agent', tool_use_id: 't1', description: 'd', prompt: 'p', subagent_type: 'general-purpose' }, allowedAgent(hooks, $)) - - const failed = await hooks.get('tool.call TaskStop')($, { tool: 'TaskStop', task_id: 'w-1' }, next) - assert.equal(failed.deny, 'o lich não conseguiu parar "w": boom') - const stopped = await hooks.get('tool.call TaskStop')($, { tool: 'TaskStop', task_id: 'w-1' }, next) - assert.equal(stopped.result.message, 'Successfully stopped task: w-1 (d)') -}) - test('edit-guard: the note about another session speaks pt-BR', async () => { const MIN = 60_000 const T0 = Date.parse('2026-10-05T12:00:00.000Z') @@ -243,7 +180,7 @@ for (const [tag, catalog] of Object.entries(NEW_LOCALES)) { test(`${tag}: LICH_PROMPT_LANG selects the catalog`, () => { assert.equal(promptLang(tag), tag) - assert.notEqual(say(tag, 'lichExited', { code: 2 }), 'lich exited 2') + assert.notEqual(say(tag, 'editNoteAgo', { minutes: 2 }), '2 min ago') }) } @@ -251,10 +188,6 @@ for (const [tag, catalog] of Object.entries(NEW_LOCALES)) { // way the pt-BR tests above drive it, with only the language swapped. const EXPECTED = { 'zh-CN': { - background: /^agent 作为 lich 会话 "w" 运行,在同一个 checkout \/wt\/w 中/, - done: /^feito\n\n工作位于同一个 checkout \/wt\/w(lich 会话 "w")中。/, - deny: '任务从未送达 "w"(unread):请打开它的卡片。', - stop: 'lich 无法停止 "w":boom', edit: /^\/r\/a\.js 也被 lich 会话 lich-a 在 2026-10-05T12:00:00\.000Z(3 分钟前)编辑过/, skill: /^base\n\n在此会话中,内置斜杠命令/, control: /传入 session "lich-1"。/, @@ -263,10 +196,6 @@ const EXPECTED = { ask: /^这是在你的回合之外/, }, es: { - background: /^El agente se ejecuta como la sesión lich "w", en este mismo checkout, \/wt\/w/, - done: /^feito\n\nEl trabajo está en este mismo checkout, \/wt\/w \(sesión lich "w"\)\./, - deny: 'la tarea nunca llegó a "w" (unread): abre su tarjeta.', - stop: 'lich no pudo detener "w": boom', edit: /^\/r\/a\.js también fue editado por la sesión lich lich-a en 2026-10-05T12:00:00\.000Z \(hace 3 min\)/, skill: /^base\n\nEn esta sesión, un slash command integrado/, control: /pasa session "lich-1"\./, @@ -275,10 +204,6 @@ const EXPECTED = { ask: /^Esta es una pregunta lateral hecha desde fuera de tu turno/, }, ja: { - background: /^エージェントは lich セッション "w" として動いています(同じこのチェックアウト \/wt\/w で/, - done: /^feito\n\n作業は同じこのチェックアウト \/wt\/w にあります(lich セッション "w")。/, - deny: 'タスクは "w" に届きませんでした(unread):そのカードを開いてください。', - stop: 'lich は "w" を停止できませんでした:boom', edit: /^\/r\/a\.js は lich セッション lich-a によっても 2026-10-05T12:00:00\.000Z(3 分前)に編集されています/, skill: /^base\n\nこのセッションでは、ユーザーが実行を求めたときに、組み込みのスラッシュコマンド/, control: /session に "lich-1" を渡してください。/, @@ -287,10 +212,6 @@ const EXPECTED = { ask: /^これは、あなたが作業している間にターンの外から尋ねられた横からの質問です/, }, ko: { - background: /^에이전트는 lich 세션 "w"에서 실행됩니다\(같은 체크아웃 \/wt\/w, 당신처럼 그 파일을 수정함\)\./, - done: /^feito\n\n작업은 같은 체크아웃 \/wt\/w에 있습니다\(lich 세션 "w"\)\./, - deny: '작업이 "w"에 한 번도 전달되지 않았습니다(unread): 그 카드를 열어 보세요.', - stop: 'lich가 "w"을(를) 멈추지 못했습니다: boom', edit: /^\/r\/a\.js은\(는\) lich 세션 lich-a도 2026-10-05T12:00:00\.000Z\(3분 전\)에 수정했습니다/, skill: /^base\n\n이 세션에서는 사용자가 실행을 요청하면 내장 슬래시 명령/, control: /session에 "lich-1"를 전달하세요\./, @@ -299,10 +220,6 @@ const EXPECTED = { ask: /^이것은 당신이 작업하는 동안 턴 밖에서 들어온 곁가지 질문입니다/, }, ru: { - background: /^Агент работает как сессия lich "w", в этой же рабочей копии, \/wt\/w/, - done: /^feito\n\nРабота находится в этой же рабочей копии, \/wt\/w \(сессия lich "w"\)\./, - deny: 'задача так и не дошла до "w" (unread): откройте её карточку.', - stop: 'lich не смог остановить "w": boom', edit: /^\/r\/a\.js также редактировала сессия lich lich-a в 2026-10-05T12:00:00\.000Z \(3 мин назад\)/, skill: /^base\n\nВ этой сессии здесь также можно назвать встроенную slash-команду/, control: /передайте session "lich-1"\./, @@ -315,35 +232,6 @@ const EXPECTED = { for (const [tag, want] of Object.entries(EXPECTED)) { const LANG = { LICH_PROMPT_LANG: tag } - test(`${tag}: agent-cards renders the background note, the completed addendum and the denies`, async () => { - const OPENED = { name: 'w-1', label: 'w', path: '/wt/w', id: 'x' } - const env = { ...LANG, LICH_BIN: '/lich', LICH_SESSION_ID: 'lich-1' } - const call = async (status, tool = 'Agent', stderr = '') => { - const hooks = hooksOf(registerAgentCards) - const runs = [ - exits(2, JSON.stringify({ ...OPENED, delivery: { ticket: 't', target: 'w', status, answer: 'feito' } })), - exits(1, '', 'boom'), - ] - const $ = { - env: { get: async (n) => env[n] }, - clock: { now: async () => 0, after: () => ({ cancel() {} }) }, - process: { run: async () => runs.shift() }, - ui: { toast() {}, invalidate() {} }, - } - await hooks.get('session.start')($, { isInteractive: true }, async (x) => x) - const next = Object.assign(pass({ result: 'native' }), { origin: { plugin: 'engine' }, signal: new AbortController().signal }) - const e = { tool: 'Agent', tool_use_id: 't1', description: 'd', prompt: 'p', subagent_type: 'general-purpose' } - const first = await hooks.get('tool.call Agent')($, e, allowedAgent(hooks, $)) - if (tool === 'Agent') return first - return hooks.get('tool.call TaskStop')($, { tool: 'TaskStop', task_id: 'w-1' }, next) - } - - assert.match((await call('pending')).context[0], want.background) - assert.match((await call('answered')).result.content[0].text, want.done) - assert.equal((await call('unread')).deny, want.deny) - assert.equal((await call('pending', 'TaskStop')).deny, want.stop) - }) - test(`${tag}: edit-guard renders the note about another session`, async () => { const T0 = Date.parse('2026-10-05T12:00:00.000Z') const disk = new Map() diff --git a/tests/refresh-fixtures.sh b/tests/refresh-fixtures.sh index bc113a3..212271f 100755 --- a/tests/refresh-fixtures.sh +++ b/tests/refresh-fixtures.sh @@ -21,7 +21,7 @@ base=$raw/docs/hooks/fixtures for file in session-start.jsonl session-state.jsonl session-title.jsonl \ session-touched.jsonl mod-usage.jsonl mod-control.jsonl \ - mod-status.json mod-answer.jsonl; do + mod-status.json; do curl -fsSL "$base/$file" -o "$here/fixtures/$file" echo "refreshed $file at $ref" done @@ -35,6 +35,14 @@ curl -fsSL "https://raw.githubusercontent.com/lichdotdev/lich/$unreleased/docs/h -o "$here/fixtures/mod-commands.json" echo "refreshed mod-commands.json at $unreleased (unreleased)" +# subagent-cards is a contract of its own, merged in lich at d33b02a8 and in no +# release yet, so it is read at that commit. Once a release ships it, move +# tests/lich-ref to that release and put the file back in the loop above. +unreleased=d33b02a87e4ea8b3a171cb57e56e1f8a81426c05 +curl -fsSL "https://raw.githubusercontent.com/lichdotdev/lich/$unreleased/docs/hooks/fixtures/subagent-cards.jsonl" \ + -o "$here/fixtures/subagent-cards.jsonl" +echo "refreshed subagent-cards.jsonl at $unreleased (unreleased)" + # validate.mjs reads its token sets off this copy, so a token lich adds reaches # the validator by moving tests/lich-ref, not by hand. curl -fsSL "$raw/themes/template.json" -o "$here/../skills/theme/template.json" diff --git a/tests/status-line.test.mjs b/tests/status-line.test.mjs index c2e3484..6a6d261 100644 --- a/tests/status-line.test.mjs +++ b/tests/status-line.test.mjs @@ -13,9 +13,9 @@ test('parts share the one line in a fixed order, and the line goes with the last const lines = [] for (const [part, text] of [ ['edits', 'app.js also edited by "docs"'], - ['workers', '2 workers'], + ['errands', '1 task out'], ['edits', undefined], - ['workers', undefined], + ['errands', undefined], ]) { setStatusPart(part, text) lines.push(footerLine()) @@ -23,24 +23,12 @@ test('parts share the one line in a fixed order, and the line goes with the last assert.deepEqual(lines, [ 'lich: app.js also edited by "docs"', - 'lich: 2 workers · app.js also edited by "docs"', - 'lich: 2 workers', + 'lich: 1 task out · app.js also edited by "docs"', + 'lich: 1 task out', undefined, ]) }) -test("the worker count is left out while lich's errands show, which include every worker", () => { - setStatusPart('workers', '1 worker') - setStatusPart('errands', '1 task out') - const withErrands = footerLine() - setStatusPart('errands', undefined) - const without = footerLine() - setStatusPart('workers', undefined) - - assert.equal(withErrands, 'lich: 1 task out') - assert.equal(without, 'lich: 1 worker') -}) - test("the line goes after Claude Code's own modes, which are kept", () => { let draw register((event, matcher, hook) => { @@ -52,7 +40,7 @@ test("the line goes after Claude Code's own modes, which are kept", () => { const passOn = (rewritten) => rewritten assert.equal(draw({}, e, passOn), e, 'with no part the footer is passed on untouched') - setStatusPart('workers', '1 worker') - assert.deepEqual(draw({}, e, passOn).props.modes, ['focus', 'lich: 1 worker']) - setStatusPart('workers', undefined) + setStatusPart('errands', '1 task out') + assert.deepEqual(draw({}, e, passOn).props.modes, ['focus', 'lich: 1 task out']) + setStatusPart('errands', undefined) }) diff --git a/tests/subagent.test.mjs b/tests/subagent.test.mjs new file mode 100644 index 0000000..d126928 --- /dev/null +++ b/tests/subagent.test.mjs @@ -0,0 +1,543 @@ +// Pins the subagent veto to lich's subagent-cards contract: the body each +// harness's client sends /subagent for its own subagent call, the veto each +// turns lich's deny into, with the reason untouched, and the allow every other +// outcome is. The script harnesses run hooks/veto-subagent.sh as their own +// registration spells it; opencode and omp run their modules in process. +// +// The answers are lich's own, replayed from subagent-cards.jsonl. The request +// payloads are the provider's, written here from the contract's table (Event → +// veto mapping): lich measured those names, and this suite holds the clients to +// them, not to a real run. +// +// Run: node --test tests/ + +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { spawn } from 'node:child_process' +import { mkdtempSync, readFileSync, symlinkSync } from 'node:fs' +import { tmpdir } from 'node:os' +import path from 'node:path' + +import { CASES, LICH_SESSION_ID, ROOT, TOKEN, assertContractHonoured, assertReportHonoured, lichEnv, settleStubs, startStub, withStub } from './contract.mjs' +import { LichPlugin } from '../opencode/lich.js' +import lichPlugin from '../omp/lich.js' + +const ENDPOINT = '/subagent' +const FIXTURES = CASES[ENDPOINT] + +// ----------------------------------------------------------------- clients -- + +const BASE_ENV = Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith('LICH_'))) +const TMP = mkdtempSync(path.join(tmpdir(), 'lich-plugin-veto-')) +const SPACED_ROOT = path.join(TMP, 'Application Support') +symlinkSync(ROOT, SPACED_ROOT) + +const read = (file) => JSON.parse(readFileSync(path.join(ROOT, file), 'utf8')) +const groupsOf = (json, event) => (json.hooks ?? json.lich)[event] +const hooksIn = (group) => (Array.isArray(group.hooks) ? group.hooks : [group]) + +/** The registered veto entry of a hook file, with its matcher. */ +function vetoEntry(file) { + for (const group of groupsOf(read(file), 'PreToolUse')) { + for (const hook of hooksIn(group)) { + if (hook.command.includes('veto-subagent.sh')) return { matcher: group.matcher, ...hook } + } + } + assert.fail(`${file} registers no subagent veto`) +} + +// Kiro's hooks are written by lich into the agent's config, so the suite runs +// the line lich is told to register (docs/subagent-cards.md, Registration lich writes). +const COMMANDS = { + claude: vetoEntry('hooks/hooks.json').command, + codex: vetoEntry('hooks/codex-hooks.json').command, + antigravity: vetoEntry('hooks.json').command, + crush: vetoEntry('hooks/crush-hooks.json').command.split('').join(SPACED_ROOT), + kiro: `"${SPACED_ROOT}/hooks/veto-subagent.sh" kiro`, +} + +/** Antigravity runs a hook with the plugin root as its working directory. */ +function runScript(harness, payload, env) { + return new Promise((resolve) => { + const child = spawn('/bin/sh', ['-c', COMMANDS[harness]], { + cwd: SPACED_ROOT, + env: { + ...BASE_ENV, + TMPDIR: mkdtempSync(path.join(TMP, 'run-')), + ...(harness === 'antigravity' ? {} : { CLAUDE_PLUGIN_ROOT: SPACED_ROOT }), + ...env, + }, + stdio: ['pipe', 'pipe', 'pipe'], + }) + let stdout = '' + let stderr = '' + child.stdout.on('data', (c) => (stdout += c)) + child.stderr.on('data', (c) => (stderr += c)) + child.stdin.on('error', () => {}) + child.stdin.end(JSON.stringify(payload)) + child.on('close', (code) => settleStubs().then(() => resolve({ code, stdout, stderr }))) + }) +} + +/** + * Runs one harness's client on its own payload and says what the call became: + * `{ veto: reason }` when it was refused with lich's text, `{ allow: true }` + * when it runs. Anything else (a veto in the wrong shape, output on allow, a + * crash) fails here, so every caller only has to compare outcomes. + */ +async function outcome(harness, payload, env) { + if (harness === 'opencode') return opencodeOutcome(payload, env) + if (harness === 'omp') return ompOutcome(payload, env) + const result = await runScript(harness, payload, env) + if (harness === 'kiro' || harness === 'crush') { + assert.equal(result.stdout, '', 'a veto by exit code says nothing on stdout') + if (result.code === 2) return { veto: result.stderr } + assert.equal(result.code, 0, `exited ${result.code}: ${result.stderr}`) + assert.equal(result.stderr, '', 'an allowed call writes nothing') + return { allow: true } + } + assert.equal(result.code, 0, `exited ${result.code}: ${result.stderr}`) + if (harness === 'antigravity') { + const verdict = JSON.parse(result.stdout) + if (verdict.decision === 'allow') { + assert.deepEqual(verdict, { decision: 'allow' }) + return { allow: true } + } + assert.deepEqual(Object.keys(verdict).sort(), ['decision', 'reason']) + assert.equal(verdict.decision, 'deny') + return { veto: verdict.reason } + } + if (result.stdout === '') return { allow: true } + const out = JSON.parse(result.stdout) + assert.deepEqual(Object.keys(out), ['hookSpecificOutput']) + const { hookEventName, permissionDecision, permissionDecisionReason } = out.hookSpecificOutput + assert.deepEqual(Object.keys(out.hookSpecificOutput).sort(), ['hookEventName', 'permissionDecision', 'permissionDecisionReason']) + assert.equal(hookEventName, 'PreToolUse') + assert.equal(permissionDecision, 'deny') + return { veto: permissionDecisionReason } +} + +async function withEnv(env, fn) { + const saved = { ...process.env } + for (const key of Object.keys(process.env)) if (key.startsWith('LICH_')) delete process.env[key] + Object.assign(process.env, env) + try { + return await fn() + } finally { + for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key] + Object.assign(process.env, saved) + } +} + +/** opencode refuses a call by the hook throwing; the model reads the message. */ +async function opencodeOutcome({ input, args, subSession }, env) { + return withEnv(env, async () => { + const hooks = await LichPlugin() + if (subSession) await hooks.event({ event: { type: 'session.created', properties: { info: { id: input.sessionID, parentID: 'root' } } } }) + try { + await hooks['tool.execute.before'](input, { args }) + return { allow: true } + } catch (error) { + assert.ok(error instanceof Error) + return { veto: error.message } + } + }) +} + +/** omp refuses a call by the tool_call handler returning `{block, reason}`. */ +async function ompOutcome({ event, sessionId }, env) { + return withEnv(env, async () => { + const handlers = new Map() + lichPlugin({ on: (name, handler) => handlers.set(name, [...(handlers.get(name) ?? []), handler]) }) + const ctx = { sessionManager: { getSessionId: () => sessionId } } + const answers = await Promise.all((handlers.get('tool_call') ?? []).map((h) => h(event, ctx))) + const blocks = answers.filter((a) => a !== undefined) + if (blocks.length === 0) return { allow: true } + assert.equal(blocks.length, 1) + assert.deepEqual(Object.keys(blocks[0]).sort(), ['block', 'reason']) + assert.equal(blocks[0].block, true) + return { veto: blocks[0].reason } + }) +} + +const IN_PROCESS = new Set(['opencode', 'omp']) + +/** The /subagent request among a stub's requests, held to the contract. */ +function subagentRequest(harness, stub) { + const asked = stub.requests.filter((r) => r.url.split('?')[0] === ENDPOINT) + assert.equal(asked.length, 1, `${harness} asked lich ${asked.length} times`) + const [request] = asked + // A script's token rides a header, as every report script's does; a module + // is handed no process command line, so it keeps `?token=`. + if (IN_PROCESS.has(harness)) return assertContractHonoured(ENDPOINT, request).body + assert.equal(request.url, ENDPOINT) + assert.equal(request.headers.authorization, `Bearer ${TOKEN}`) + return assertReportHonoured(ENDPOINT, request).body +} + +// --------------------------------------------------------------- payloads -- + +const FIX = 'Fix #412: the relay handshake races on reconnect.' +const DENY = FIXTURES.find((c) => c.answer?.decision === 'deny').answer + +/** A body as the contract spells it, for the fields a call leaves at default. */ +const body = (fields) => ({ + session_id: LICH_SESSION_ID, + provider_session_id: 'p1', + nested: false, + call: 'spawn', + tool_use_id: '', + model: '', + sealed: false, + isolation: '', + background: false, + ...fields, +}) + +/** + * One call per harness and shape the contract's table names, the payload the + * provider hands its hook, and the body lich must receive for it. + */ +const CALLS = [ + { + name: 'a Claude Code Agent call, every field set', + harness: 'claude', + payload: { + session_id: 'p1', + tool_name: 'Agent', + tool_use_id: 'toolu_1', + tool_input: { + description: 'Fix the handshake race', + prompt: FIX, + subagent_type: 'general-purpose', + model: 'opus', + isolation: 'worktree', + run_in_background: true, + }, + }, + body: body({ + tool: 'Agent', + tool_use_id: 'toolu_1', + tasks: [{ title: 'Fix the handshake race', prompt: FIX, type: 'general-purpose' }], + model: 'opus', + isolation: 'worktree', + background: true, + }), + }, + { + name: 'a Claude Code Agent call from inside a native subagent', + harness: 'claude', + payload: { session_id: 'p1', agent_id: 'a1', tool_name: 'Agent', tool_use_id: 'toolu_2', tool_input: { description: 'd', prompt: FIX } }, + body: body({ nested: true, tool: 'Agent', tool_use_id: 'toolu_2', tasks: [{ title: 'd', prompt: FIX, type: '' }] }), + }, + { + name: "a Cursor CLI Task call, through the Claude Code install's hook", + harness: 'claude', + payload: { session_id: 'p1', tool_name: 'Task', tool_input: { description: 'Map it', prompt: 'Map the relay package.', subagent_type: 'explore' } }, + body: body({ tool: 'Task', tasks: [{ title: 'Map it', prompt: 'Map the relay package.', type: 'explore' }] }), + }, + { + name: 'a Codex v1 spawn_agent call', + harness: 'codex', + payload: { session_id: 'p1', tool_name: 'spawn_agent', tool_use_id: 'exec-1', tool_input: { message: FIX, agent_type: 'worker' } }, + body: body({ tool: 'spawn_agent', tool_use_id: 'exec-1', tasks: [{ title: '', prompt: FIX, type: 'worker' }] }), + }, + { + name: 'a Codex v2 spawn, its message encrypted', + harness: 'codex', + payload: { session_id: 'p1', tool_name: 'collaborationspawn_agent', tool_use_id: 'exec-2', tool_input: { task_name: 'fix_handshake', message: 'gAAAAABo-ciphertext' } }, + body: body({ tool: 'collaborationspawn_agent', tool_use_id: 'exec-2', sealed: true, tasks: [{ title: 'fix_handshake', prompt: '', type: '' }] }), + }, + { + name: 'a Codex v2 wait', + harness: 'codex', + payload: { session_id: 'p1', tool_name: 'collaborationwait_agent', tool_use_id: 'exec-3', tool_input: { targets: ['fix_handshake'] } }, + body: body({ call: 'wait', tool: 'collaborationwait_agent', tool_use_id: 'exec-3', tasks: [] }), + }, + { + name: 'an Antigravity invoke_subagent call', + harness: 'antigravity', + payload: { conversationId: 'p1', toolCall: { name: 'invoke_subagent', args: { Prompt: FIX, TypeName: 'general' } } }, + body: body({ tool: 'invoke_subagent', tasks: [{ title: '', prompt: FIX, type: 'general' }] }), + }, + { + name: 'a Kiro CLI subagent call (ACP)', + harness: 'kiro', + payload: { session_id: 'p1', tool_name: 'subagent', tool_input: { task: FIX, stages: [{ name: 'Fix it' }, { name: 'Review' }] } }, + body: body({ tool: 'subagent', tasks: [{ title: 'Fix it', prompt: FIX, type: '' }] }), + }, + { + name: 'a Kiro CLI use_subagent call starting two subagents', + harness: 'kiro', + payload: { + session_id: 'p1', + tool_name: 'use_subagent', + tool_input: { command: 'InvokeSubagents', content: { subagents: [{ query: 'Map the relay package.' }, { query: 'Fix #412.' }] } }, + }, + body: body({ + tool: 'use_subagent', + tasks: [ + { title: '', prompt: 'Map the relay package.', type: '' }, + { title: '', prompt: 'Fix #412.', type: '' }, + ], + }), + }, + { + name: 'a Crush agent call', + harness: 'crush', + payload: { session_id: 'p1', tool_name: 'agent', tool_input: { prompt: 'Map the relay package.' } }, + body: body({ tool: 'agent', tasks: [{ title: '', prompt: 'Map the relay package.', type: '' }] }), + }, + { + name: 'an opencode task call', + harness: 'opencode', + payload: { + input: { tool: 'task', sessionID: 'p1', callID: 'call_1' }, + args: { description: 'Map it', prompt: 'Map the relay package.', subagent_type: 'general' }, + }, + body: body({ tool: 'task', tool_use_id: 'call_1', tasks: [{ title: 'Map it', prompt: 'Map the relay package.', type: 'general' }] }), + }, + { + name: "an opencode task call from a sub-session", + harness: 'opencode', + payload: { + input: { tool: 'task', sessionID: 'child', callID: 'call_2' }, + args: { description: 'Map it', prompt: 'Map the relay package.', subagent_type: 'general' }, + subSession: true, + }, + body: body({ + provider_session_id: 'child', + nested: true, + tool: 'task', + tool_use_id: 'call_2', + tasks: [{ title: 'Map it', prompt: 'Map the relay package.', type: 'general' }], + }), + }, + { + name: 'an oh-my-pi task call with two tasks and a shared context', + harness: 'omp', + payload: { + sessionId: 'p1', + event: { + type: 'tool_call', + toolCallId: 'toolu_1', + toolName: 'task', + input: { + context: 'The relay is in internal/relay.', + tasks: [ + { name: 'scan', task: 'Map the relay package.', agent: 'scout' }, + { name: 'fix', task: 'Fix #412.', agent: 'task' }, + ], + }, + }, + }, + body: body({ + tool: 'task', + tool_use_id: 'toolu_1', + tasks: [ + { title: 'scan', prompt: 'The relay is in internal/relay.\n\nMap the relay package.', type: 'scout' }, + { title: 'fix', prompt: 'The relay is in internal/relay.\n\nFix #412.', type: 'task' }, + ], + }), + }, +] + +const HARNESSES = [...new Set(CALLS.map((c) => c.harness))] +const callOf = (harness) => CALLS.find((c) => c.harness === harness) + +// ---------------------------------------------------------------- requests -- + +for (const call of CALLS) { + test(`${call.name}: asks lich with the contract's body`, async () => { + await withStub( + async (stub) => { + await outcome(call.harness, call.payload, lichEnv(stub.port)) + assert.deepEqual(subagentRequest(call.harness, stub), call.body) + }, + { status: 200, body: JSON.stringify({ decision: 'allow' }) }, + ) + }) +} + +// Calls that start no subagent, or one lich would refuse for want of a prompt, +// are left native without a request: lich's 400 would be an allow anyway. +const NOT_ASKED = [ + ['claude', { session_id: 'p1', tool_name: 'Bash', tool_input: { command: 'ls' } }], + ['claude', { session_id: 'p1', tool_name: 'Agent', tool_input: { description: 'd', prompt: ' ' } }], + ['codex', { session_id: 'p1', tool_name: 'shell', tool_input: { command: ['ls'] } }], + ['codex', { session_id: 'p1', tool_name: 'spawn_agent', tool_input: {} }], + ['antigravity', { conversationId: 'p1', toolCall: { name: 'run_command', args: { CommandLine: 'ls' } } }], + ['kiro', { session_id: 'p1', tool_name: 'use_subagent', tool_input: { command: 'ListAgents' } }], + ['kiro', { session_id: 'p1', tool_name: 'use_subagent', tool_input: { command: 'InvokeSubagents', content: { subagents: [] } } }], + ['crush', { session_id: 'p1', tool_name: 'bash', tool_input: { command: 'ls' } }], + ['opencode', { input: { tool: 'bash', sessionID: 'p1', callID: 'c' }, args: { command: 'ls' } }], + ['opencode', { input: { tool: 'task', sessionID: 'p1', callID: 'c' }, args: { description: 'd', prompt: '' } }], + ['omp', { sessionId: 'p1', event: { type: 'tool_call', toolCallId: 'c', toolName: 'bash', input: { command: 'ls' } } }], + ['omp', { sessionId: 'p1', event: { type: 'tool_call', toolCallId: 'c', toolName: 'task', input: { tasks: [] } } }], +] + +for (const [harness, payload] of NOT_ASKED) { + const tool = payload.tool_name ?? payload.toolCall?.name ?? payload.input?.tool ?? payload.event?.toolName + test(`${harness}: a ${tool} call that starts no subagent lich would take is not asked about`, async () => { + await withStub( + async (stub) => { + assert.deepEqual(await outcome(harness, payload, lichEnv(stub.port)), { allow: true }) + assert.deepEqual( + stub.requests.filter((r) => r.url.split('?')[0] === ENDPOINT), + [], + ) + }, + { status: 200, body: JSON.stringify(DENY) }, + ) + }) +} + +// ------------------------------------------------------------------ vetoes -- + +// Every answer lich's fixture gives, replayed for every harness, plus a reason +// in another script and with a newline, since lich writes it in the session's +// prompt language: a deny reaches the model as that harness's own veto with +// the reason byte for byte, and an allow lets the call run. +const ANSWERS = [ + ...new Map(FIXTURES.filter((c) => c.answer).map((c) => [JSON.stringify(c.answer), c.answer])).values(), + { decision: 'deny', reason: 'lich abriu esta tarefa como a sessão "Ação" (ticket 4b9bc94e).\nNão repita a ferramenta.', sessions: [] }, +] + +for (const harness of HARNESSES) { + test(`${harness}: every answer lich gives becomes the harness's own veto, or lets the call run`, async () => { + for (const answer of ANSWERS) { + await withStub( + async (stub) => { + const got = await outcome(harness, callOf(harness).payload, lichEnv(stub.port)) + assert.deepEqual(got, answer.decision === 'deny' ? { veto: answer.reason } : { allow: true }, JSON.stringify(answer)) + }, + { status: 200, body: JSON.stringify(answer) }, + ) + } + }) +} + +// --------------------------------------------------------------- fail open -- + +const FAILURES = [ + ['a status other than 200', { status: 500, body: JSON.stringify(DENY) }], + ['a 400', { status: 400, body: '{"error":"tool is required"}' }], + ['a body that is not JSON', { status: 200, body: 'deny' }], + ['a deny with no reason', { status: 200, body: '{"decision":"deny"}' }], + ['a decision lich does not send', { status: 200, body: '{"decision":"maybe","reason":"x"}' }], +] + +for (const harness of HARNESSES) { + test(`${harness}: outside lich the call runs and nothing is asked`, async () => { + await withStub(async (stub) => { + assert.deepEqual(await outcome(harness, callOf(harness).payload, {}), { allow: true }) + assert.equal(stub.requests.length, 0) + }) + }) + + test(`${harness}: lich refusing the connection lets the call run`, async () => { + const stub = await startStub() + const env = lichEnv(stub.port) + await stub.close() + assert.deepEqual(await outcome(harness, callOf(harness).payload, env), { allow: true }) + }) + + for (const [what, answer] of FAILURES) { + test(`${harness}: ${what} lets the call run`, async () => { + await withStub(async (stub) => { + assert.deepEqual(await outcome(harness, callOf(harness).payload, lichEnv(stub.port)), { allow: true }) + }, answer) + }) + } +} + +// lich closes what it opened when nobody read its answer, so a client that gave +// up lets the call run. 10 seconds is the contract's wait; one client of each +// kind waits it out, side by side. +test('a lich that never answers lets the call run after the 10 seconds the contract waits', async () => { + const waited = await Promise.all( + ['claude', 'opencode', 'omp'].map(async (harness) => { + const stub = await startStub({ hang: true }) + const started = Date.now() + try { + assert.deepEqual(await outcome(harness, callOf(harness).payload, lichEnv(stub.port)), { allow: true }) + return [harness, Date.now() - started] + } finally { + await stub.close() + } + }), + ) + for (const [harness, ms] of waited) { + assert.ok(ms >= 9500 && ms < 14000, `${harness} gave up after ${ms} ms`) + } +}) + +// Without jq the script has nothing safe to build a body or read an answer +// with, so it asks nothing and the call runs. Antigravity still gets its +// verdict. +test('without jq the script asks nothing and the call runs', async () => { + const bin = mkdtempSync(path.join(TMP, 'bin-')) + for (const tool of ['sh', 'cat', 'curl', 'sed', 'tail', 'dirname', 'grep', 'head', 'printf']) { + const found = await new Promise((resolve) => { + const which = spawn('/bin/sh', ['-c', `command -v ${tool}`]) + let out = '' + which.stdout.on('data', (c) => (out += c)) + which.on('close', () => resolve(out.trim())) + }) + if (found.startsWith('/')) symlinkSync(found, path.join(bin, tool)) + } + for (const harness of ['claude', 'antigravity', 'kiro']) { + await withStub( + async (stub) => { + const env = { ...lichEnv(stub.port), PATH: bin } + assert.deepEqual(await outcome(harness, callOf(harness).payload, env), { allow: true }) + // Antigravity's command runs the tool report too, which has a sed + // fallback of its own. + assert.equal(stub.requests.filter((r) => r.url.split('?')[0] === ENDPOINT).length, 0) + }, + { status: 200, body: JSON.stringify(DENY) }, + ) + } +}) + +// ----------------------------------------------------------- registrations -- + +// The tool names each registration's matcher lets through are the contract's +// table, and nothing else reaches the veto: a matcher that names a tool the +// harness does not call vetoes nothing, quietly. Antigravity's entry matches +// every tool, because its veto shares the tool report's command (one verdict +// per call), and the script itself answers allow for any other tool. +test("each registration's matcher names the contract's subagent tools", () => { + assert.equal(vetoEntry('hooks/hooks.json').matcher, 'Agent|Task') + assert.equal(vetoEntry('hooks/codex-hooks.json').matcher, 'spawn_agent|collaborationspawn_agent|collaborationwait_agent') + assert.equal(vetoEntry('hooks/crush-hooks.json').matcher, '^agent$') + assert.equal(vetoEntry('hooks.json').matcher, '') +}) + +// The hook waits 10 seconds for lich; a harness that kills it first lets the +// call run while lich may still open a card for it. +test('every registration gives the veto longer than the 10 seconds it waits', () => { + for (const file of ['hooks/hooks.json', 'hooks/codex-hooks.json', 'hooks/crush-hooks.json', 'hooks.json']) { + assert.ok(vetoEntry(file).timeout > 10, `${file} kills the veto at ${vetoEntry(file).timeout}s`) + } +}) + +// ---------------------------------------------------------------- fixtures -- + +test('every body lich accepts passes the contract helper, and no rejected one does', () => { + for (const c of FIXTURES) { + if (c.accept) assertReportHonoured(ENDPOINT, fakeRequest(JSON.stringify(c.body))) + if (c.reject) { + assert.throws(() => assertReportHonoured(ENDPOINT, fakeRequest(c.raw ?? JSON.stringify(c.body))), undefined, c.name) + } + } +}) + +function fakeRequest(raw) { + return { + method: 'POST', + url: ENDPOINT, + headers: { 'content-type': 'application/json', 'x-lich-plugin': JSON.parse(readFileSync(path.join(ROOT, '.claude-plugin', 'plugin.json'), 'utf8')).version }, + raw, + } +} diff --git a/tests/worker-answer.engine.test.ts b/tests/worker-answer.engine.test.ts deleted file mode 100644 index c178761..0000000 --- a/tests/worker-answer.engine.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -// The worker's answer under Claude Code's own engine: `claude plugin test .` -// loads the plugin's hooks module (hooks/lich.js, which registers -// hooks/worker-answer.js) from hooks/hooks.json the way a session does, the -// test's hooks standing for lich (`http.fetch`). tests/worker-answer.test.mjs -// is the suite CI runs against the contract fixtures; this one proves the -// module loads beside mod-control.js's own turn.complete hook and that its -// hooks chain in the engine that runs it. - -import { expect, mock, test } from 'claude-code/testing' -import type { On, TurnCompleteInput } from 'claude-code' - -const WORKER = { LICH_PORT: '47999', LICH_TOKEN: 'tok', LICH_SESSION_ID: 'lich-1', LICH_SUBAGENT_CARDS: 'off' } - -const ANSWERED: TurnCompleteInput = { answer: 'Rewrote docs/cli.md.', reason: 'answer', isAborted: false, turnId: 't1', durationMs: 1000 } - -/** - * Records every answer and parks every poll, as lich does with nothing - * queued; also stands for the engine's own session start, Stop and turn end, which - * the kit leaves to the test. - */ -function lich(on: On) { - const answers: Record[] = [] - on('session.start', async (_$, e) => ({ cwd: e.cwd })) - on('turn.complete', async (_$, e) => ({ text: e.answer })) - on('classic.Stop', async () => ({})) - on('http.fetch', async (_$, e) => { - if (e.url.includes('/mod/answer')) { - answers.push(JSON.parse(e.init?.body ?? '{}')) - return { value: { status: 204, ok: true, headers: {}, text: '' } } - } - return new Promise(() => {}) - }) - return { answers } -} - -test("a worker's last message is posted as its answer", async ($, on) => { - mock.env(on, WORKER) - const clock = mock.clock(on) - const world = lich(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await $.classic.Stop({ stop_hook_active: false, last_assistant_message: 'Rewrote docs/cli.md.', background_tasks: [] }) - await $.turn.complete(ANSWERED) - await clock.settle() - expect(world.answers).toEqual([{ session_id: 'lich-1', text: 'Rewrote docs/cli.md.' }]) -}) - -test('a turn with work in the background answers nothing', async ($, on) => { - mock.env(on, WORKER) - const clock = mock.clock(on) - const world = lich(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await $.classic.Stop({ - stop_hook_active: false, - last_assistant_message: 'WAITING', - background_tasks: [{ id: 'b1', type: 'shell', status: 'running', description: 'sleep 20' }], - }) - await $.turn.complete({ ...ANSWERED, answer: 'WAITING' }) - await clock.settle() - expect(world.answers).toHaveLength(0) -}) - -test('a worker lich names by its depth answers with subagent cards left on', async ($, on) => { - mock.env(on, { LICH_PORT: '47999', LICH_TOKEN: 'tok', LICH_SESSION_ID: 'lich-1', LICH_SUBAGENT_DEPTH: '1' }) - const clock = mock.clock(on) - const world = lich(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await $.classic.Stop({ stop_hook_active: false, last_assistant_message: 'Rewrote docs/cli.md.', background_tasks: [] }) - await $.turn.complete(ANSWERED) - await clock.settle() - expect(world.answers).toEqual([{ session_id: 'lich-1', text: 'Rewrote docs/cli.md.' }]) -}) - -test('a blank turn is reported unanswered', async ($, on) => { - mock.env(on, WORKER) - const clock = mock.clock(on) - const world = lich(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await $.classic.Stop({ stop_hook_active: false, last_assistant_message: '', background_tasks: [] }) - await $.turn.complete({ ...ANSWERED, answer: '' }) - await clock.settle() - expect(world.answers).toEqual([{ session_id: 'lich-1', unanswered: 'blank' }]) -}) - -test('a refused turn, which fires no Stop, reports nothing', async ($, on) => { - mock.env(on, WORKER) - const clock = mock.clock(on) - const world = lich(on) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await $.turn.complete({ ...ANSWERED, answer: '', reason: 'refusal' }) - await clock.settle() - expect(world.answers).toEqual([]) -}) - -test('a worker whose classic.Stop never fires answers from turn.complete', async ($, on) => { - mock.env(on, WORKER) - const clock = mock.clock(on) - const world = lich(on) - on('agent.list', async () => ({ value: [] })) - await $.session.start({ cwd: '/w', surface: 'terminal', isInteractive: true }) - await $.turn.complete(ANSWERED) - await clock.settle() - expect(world.answers).toEqual([{ session_id: 'lich-1', text: 'Rewrote docs/cli.md.' }]) -}) diff --git a/tests/worker-answer.test.mjs b/tests/worker-answer.test.mjs deleted file mode 100644 index 8022c21..0000000 --- a/tests/worker-answer.test.mjs +++ /dev/null @@ -1,353 +0,0 @@ -// Pins the Claude Code mod that answers a lich subagent worker's task -// (hooks/worker-answer.js) to lich's mod-answer contract. -// -// Like mod-usage.test.mjs, it imports the module and hands it a fake engine, -// recording every fetch as contract.mjs reads a request, so the reports answer -// to the same fixtures lich asserts (mod-answer.jsonl). The `classic.Stop` and -// `turn.complete` payloads below are the shapes Claude Code 2.1.289 delivered. -// -// Run: node --test tests/ - -import { test } from 'node:test' -import assert from 'node:assert/strict' - -import { LICH_SESSION_ID, assertContractHonoured, lichEnv } from './contract.mjs' -import { register } from '../hooks/worker-answer.js' - -const PORT = 47997 -const WORKER_ENV = { ...lichEnv(PORT), LICH_SUBAGENT_CARDS: 'off' } -const NO_CONTENT = { status: 204, ok: true, headers: {}, text: '' } - -const SHELL = { id: 'bib80qpy1', type: 'shell', status: 'running', description: 'sleep 20', command: 'sleep 20' } - -const stop = (last, backgroundTasks = []) => ({ - hook_event_name: 'Stop', - stop_hook_active: false, - last_assistant_message: last, - background_tasks: backgroundTasks, - session_crons: [], -}) - -const complete = (answer, reason = 'answer') => ({ - answer, - reason, - isAborted: reason === 'aborted', - turnId: 't1', - durationMs: 1000, -}) - -const settle = () => new Promise((r) => setTimeout(r, 20)) - -/** - * Registers the module against a fake engine. A hook registered with a - * matcher runs only for an event that matches it, as the engine runs it. - */ -function load({ env = WORKER_ENV, answer = () => Promise.resolve(NO_CONTENT), agents = async () => [] } = {}) { - const hooks = new Map() - register((event, ...rest) => { - const hook = rest.pop() - hooks.set(event, [...(hooks.get(event) ?? []), { matcher: rest[0] ?? {}, hook }]) - }) - const requests = [] - const $ = { - env: { get: async (name) => env[name] }, - agent: { list: agents }, - http: { - fetch: (url, init = {}) => { - const { pathname, search } = new URL(url) - const headers = Object.fromEntries(Object.entries(init.headers ?? {}).map(([k, v]) => [k.toLowerCase(), v])) - requests.push({ method: init.method ?? 'GET', url: pathname + search, headers, raw: init.body ?? '' }) - return answer() - }, - }, - } - const passOn = async (e) => e - const fire = (event, e) => { - const matching = hooks.get(event).filter(({ matcher }) => - Object.entries(matcher).every(([key, value]) => e[key] === value), - ) - const chain = matching.reduceRight((next, { hook }) => (ev) => hook($, ev, next), passOn) - return chain(e) - } - const turn = async (stopEvent, completeEvent) => { - if (stopEvent) await fire('classic.Stop', stopEvent) - await fire('turn.complete', completeEvent) - await settle() - } - return { - requests, - bodies: () => requests.map((r) => JSON.parse(r.raw)), - start: (isInteractive = true) => fire('session.start', { cwd: '/w', surface: 'terminal', isInteractive }), - turn, - } -} - -test("a worker's final message reaches lich as the contract spells it", async () => { - const mod = load() - await mod.start() - - await mod.turn(stop('Rewrote docs/cli.md.'), complete('Rewrote docs/cli.md.')) - - assert.equal(mod.requests.length, 1) - assertContractHonoured('/mod/answer', mod.requests[0]) - assert.deepEqual(mod.bodies()[0], { session_id: LICH_SESSION_ID, text: 'Rewrote docs/cli.md.' }) -}) - -test('a turn that handed work to the background answers only once it resumes', async () => { - const mod = load() - await mod.start() - - await mod.turn(stop('WAITING', [SHELL]), complete('WAITING')) - assert.equal(mod.requests.length, 0, 'answered while a shell still ran') - - await mod.turn(stop('FINISHED: DONE'), complete('FINISHED: DONE')) - assert.deepEqual(mod.bodies().map((b) => b.text), ['FINISHED: DONE']) -}) - -test('a blank final message is reported unanswered as the contract spells it', async () => { - const mod = load() - await mod.start() - - await mod.turn(stop(' \n'), complete(' \n')) - await mod.turn(stop(undefined), complete('')) - - assert.deepEqual(mod.bodies(), [ - { session_id: LICH_SESSION_ID, unanswered: 'blank' }, - { session_id: LICH_SESSION_ID, unanswered: 'blank' }, - ]) - for (const request of mod.requests) assertContractHonoured('/mod/answer', request) -}) - -test('a blank turn that handed work to the background reports nothing', async () => { - const mod = load() - await mod.start() - - await mod.turn(stop('', [SHELL]), complete('')) - - assert.equal(mod.requests.length, 0) -}) - -// Measured on Claude Code 2.1.296: a refusal ends the turn through StopFailure, -// then turn.complete with reason refusal, and fires no Stop. -test('a refused turn reports nothing', async () => { - const mod = load() - await mod.start() - - await mod.turn(undefined, complete('', 'refusal')) - - assert.equal(mod.requests.length, 0) -}) - -// An API error fires StopFailure, which carries no background_tasks, so the -// mod cannot tell the failed turn left nothing running (docs/mod-answer.md). -test('an aborted or failed turn reports nothing', async () => { - const mod = load() - await mod.start() - - await mod.turn(undefined, complete('half a sentence', 'aborted')) - await mod.turn(undefined, complete('', 'error')) - await mod.turn(stop('partial'), complete('partial', 'error')) - await mod.turn(stop(''), complete('', 'error')) - - assert.equal(mod.requests.length, 0) -}) - -test('an aborted turn drops the Stop it read, so a later blank turn cannot use it', async () => { - const mod = load() - await mod.start() - - await mod.turn(stop(''), complete('', 'aborted')) - await mod.turn(undefined, complete('')) - - assert.equal(mod.requests.length, 0) -}) - -// classic.Stop fires only on the main loop; turn.complete fires for every -// subagent's turn too, and one of those is never the worker's answer. -test("a subagent's turn inside the worker answers nothing", async () => { - const mod = load() - await mod.start() - - await mod.turn(undefined, { ...complete('SUBDONE'), agentId: 'af8fcd1f2b867337f' }) - - assert.equal(mod.requests.length, 0) -}) - -// An aborted turn fires no Stop, so the verdict of the turn before it must not -// stand in for one. -test("a turn without a Stop of its own does not reuse the last one's", async () => { - const mod = load() - await mod.start() - - await mod.turn(stop('WAITING', [SHELL]), complete('WAITING')) - await mod.turn(undefined, complete('something else')) - - assert.equal(mod.requests.length, 0) -}) - -test('an ordinary session never answers', async () => { - const mod = load({ env: lichEnv(PORT) }) - await mod.start() - - await mod.turn(stop('Done.'), complete('Done.')) - - assert.equal(mod.requests.length, 0) -}) - -test('a worker lich names by its depth answers, with subagent cards left on', async () => { - const mod = load({ env: { ...lichEnv(PORT), LICH_SUBAGENT_DEPTH: '1' } }) - await mod.start() - - await mod.turn(stop('Done.'), complete('Done.')) - - assert.deepEqual(mod.bodies(), [{ session_id: LICH_SESSION_ID, text: 'Done.' }]) -}) - -test('a worker at lich\'s depth limit answers, though its subagent cards are off', async () => { - const mod = load({ env: { ...WORKER_ENV, LICH_SUBAGENT_DEPTH: '2' } }) - await mod.start() - - await mod.turn(stop('Done.'), complete('Done.')) - - assert.equal(mod.requests.length, 1) -}) - -// The depth decides once lich sets it: cards off at depth 0 is the user's -// setting, not a worker. -test('a top-level session with subagent cards turned off never answers', async () => { - const mod = load({ env: { ...WORKER_ENV, LICH_SUBAGENT_DEPTH: '0' } }) - await mod.start() - - await mod.turn(stop('Done.'), complete('Done.')) - - assert.equal(mod.requests.length, 0) -}) - -test('a lich older than the depth variable marks a worker by cards off alone', async () => { - const mod = load({ env: WORKER_ENV }) - await mod.start() - - await mod.turn(stop('Done.'), complete('Done.')) - - assert.equal(mod.requests.length, 1) -}) - -test('outside lich nothing is sent', async () => { - const mod = load({ env: { LICH_SUBAGENT_CARDS: 'off' } }) - await mod.start() - - await mod.turn(stop('Done.'), complete('Done.')) - - assert.equal(mod.requests.length, 0) -}) - -test('a non-interactive run never answers for the card that started it', async () => { - const mod = load() - await mod.start(false) - - await mod.turn(stop('Done.'), complete('Done.')) - - assert.equal(mod.requests.length, 0) -}) - -test('a long answer is cut where the contract says', async () => { - const mod = load() - await mod.start() - const long = 'x'.repeat(20000) - - await mod.turn(stop(long), complete(long)) - - const text = mod.bodies()[0].text - assert.equal(text, `${'x'.repeat(16000)}\n[truncated]`) - assertContractHonoured('/mod/answer', mod.requests[0]) -}) - -test('the turn is never held up by lich, and a failure is dropped', async () => { - const hung = load({ answer: () => new Promise(() => {}) }) - await hung.start() - const e = complete('Done.') - await hung.turn(stop('Done.'), e) - assert.equal(hung.requests.length, 1) - - const failing = load({ answer: () => Promise.reject(new Error('connect ECONNREFUSED')) }) - await failing.start() - await failing.turn(stop('Done.'), complete('Done.')) - assert.equal(failing.requests.length, 1, 'a failed answer was retried') -}) - -// Measured on Claude Code 2.1.306: under managed settings the builtin -// cc-plugin-sec-default sends classic.Stop on past user plugins, so a worker -// there sees turn.complete alone. -test('a worker whose Stop is bypassed answers from the completion', async () => { - const mod = load() - await mod.start() - - await mod.turn(undefined, complete('Rewrote docs/cli.md.')) - - assert.equal(mod.requests.length, 1) - assertContractHonoured('/mod/answer', mod.requests[0]) - assert.deepEqual(mod.bodies()[0], { session_id: LICH_SESSION_ID, text: 'Rewrote docs/cli.md.' }) -}) - -test('a blank turn whose Stop is bypassed is reported unanswered', async () => { - const mod = load() - await mod.start() - - await mod.turn(undefined, complete(' \n')) - - assert.deepEqual(mod.bodies(), [{ session_id: LICH_SESSION_ID, unanswered: 'blank' }]) - assertContractHonoured('/mod/answer', mod.requests[0]) -}) - -test("a subagent's turn answers nothing when the Stop is bypassed", async () => { - const mod = load() - await mod.start() - - await mod.turn(undefined, { ...complete('SUBDONE'), agentId: 'af8fcd1f2b867337f' }) - - assert.equal(mod.requests.length, 0) -}) - -test('a refused, failed or aborted turn whose Stop is bypassed reports nothing', async () => { - const mod = load() - await mod.start() - - await mod.turn(undefined, complete('', 'refusal')) - await mod.turn(undefined, complete('', 'error')) - await mod.turn(undefined, complete('half a sentence', 'aborted')) - - assert.equal(mod.requests.length, 0) -}) - -// $.agent.list() as Claude Code 2.1.306 answers it: subagents only, no shells. -test('a bypassed Stop holds the answer while a subagent is still at work', async () => { - let agents = [{ id: 'a1', description: 'scan', type: 'local_agent', status: 'running' }] - const mod = load({ agents: async () => agents }) - await mod.start() - - await mod.turn(undefined, complete('WAITING')) - assert.equal(mod.requests.length, 0, 'answered while a subagent still ran') - - agents = [{ ...agents[0], status: 'completed' }] - await mod.turn(undefined, complete('FINISHED: DONE')) - assert.deepEqual(mod.bodies().map((b) => b.text), ['FINISHED: DONE']) -}) - -test('a bypassed Stop holds the answer when the subagents cannot be listed', async () => { - const mod = load({ agents: () => Promise.reject(new Error('no session bound')) }) - await mod.start() - - await mod.turn(undefined, complete('Done.')) - - assert.equal(mod.requests.length, 0) -}) - -test('a session that saw a Stop keeps answering from Stops only', async () => { - const mod = load() - await mod.start() - - await mod.turn(stop('Done.'), complete('Done.')) - await mod.turn(undefined, complete('something else')) - - assert.deepEqual(mod.bodies().map((b) => b.text), ['Done.']) -}) From fae96e6cbdcd6dad6d37e57dfb10c842dda55b2f Mon Sep 17 00:00:00 2001 From: omartelo Date: Mon, 23 Nov 2026 06:43:12 -0300 Subject: [PATCH 2/2] docs: say where the subagent veto speaks on stdout, and steady the hung-lich test --- CLAUDE.md | 6 ++++-- docs/providers.md | 11 ++++++++--- tests/hooks.test.mjs | 12 ++++++++---- tests/subagent.test.mjs | 35 +++++++++++++++++++++-------------- 4 files changed, 41 insertions(+), 23 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 15dd3a4..8a4a157 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -43,7 +43,9 @@ namespaced folder: the root is the plugin directory once the clone is linked in. It also sets no plugin-root variable, running a hook through `sh -c` with the working directory set to that root, so its registration alone spells relative paths; and it reads a JSON verdict off the hook's stdout, so the registration -appends one per event while the scripts stay silent. `agy plugin validate .` +appends one per event while the report scripts stay silent. `PreToolUse` is the +exception: there the subagent veto, chained after the tool report so a call +gets one verdict, prints it. `agy plugin validate .` checks the bundle from a clone. Three harnesses do not fit the script model, each its own way. **opencode** runs @@ -53,7 +55,7 @@ it with `--extension` into one list it `import()`s, so its "hooks" are modules too, and its client is `omp/lich.js`. **Crush** runs the scripts unchanged — its hooks are Claude Code-compatible down to the stdin payload — but has exactly one event, `PreToolUse`, so only the session id and the touched refresh are -registered for it. +registered for it, plus the subagent veto, which needs no end of turn. ## Contracts diff --git a/docs/providers.md b/docs/providers.md index a341e96..f42997e 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -253,7 +253,9 @@ listener. 17.x moves fast — re-measure before trusting a name. down to the stdin payload and the exit codes, so the scripts run unchanged — but with nothing that fires at the end of a turn, only two of the four reports can be honest. Crush reports its session id and refreshes git status; it shows - no spinner, no check, no bell, and keeps the card's own name. + no spinner, no check, no bell, and keeps the card's own name. Its `agent` + calls go through the subagent veto ([subagent-cards.md](subagent-cards.md)), + which needs no end of turn. - **`busy` is deliberately not registered.** A `busy` with no `Stop` behind it would pin a spinner to the card until the next turn — wrong for longer than it is right. The day Crush ships an end-of-turn event, `report-state.sh` and @@ -300,8 +302,11 @@ against a stub listener — not off a name that reads plausibly. where `continue` refuses to let the loop end. Silence is not the neutral answer it is on every other harness, so the registration appends the verdict the event asks for — `{"decision":"allow"}` before a tool, `{"decision":""}` on - `Stop`, `{}` elsewhere. The scripts stay silent, because on Codex their stdout - would answer a permission request instead. + `Stop`, `{}` elsewhere. The report scripts stay silent, because on Codex their + stdout would answer a permission request instead. Before a tool the verdict is + the subagent veto's, which runs after the tool report in the same command and + prints `allow` for every tool but a vetoed `invoke_subagent` + ([subagent-cards.md](subagent-cards.md)). - **Payloads are camelCase** (protojson): `conversationId` is the session id, `workspacePaths[0]` the session's directory, `transcriptPath` the JSONL log. Tool calls arrive as `toolCall.name` with PascalCase arguments under diff --git a/tests/hooks.test.mjs b/tests/hooks.test.mjs index 1fbbe14..7aa8a61 100644 --- a/tests/hooks.test.mjs +++ b/tests/hooks.test.mjs @@ -83,7 +83,7 @@ function runHook(command, { env = {}, stdin = '', pluginRoot = true, tmpdir = nu }) } -// A hook script never speaks on stdout: on Codex the session-state hook rides +// A report script never speaks on stdout: on Codex the session-state hook rides // PermissionRequest, where output and a non-zero exit are an answer to the // request rather than an observation. // @@ -91,7 +91,9 @@ function runHook(command, { env = {}, stdin = '', pluginRoot = true, tmpdir = nu // stdout and acts on it, and a PreToolUse handler that says nothing leaves the // tool call without the `decision` its contract makes required. So the verdict // is appended by the registration, not printed by the shared script, and what -// arrives on stdout is exactly that verdict and nothing the script added. +// arrives on stdout is exactly that verdict and nothing the script added. The +// subagent veto is the one script that speaks, its stdout being the veto: on +// Antigravity's PreToolUse it prints the verdict (ANTIGRAVITY_VETO_CHAIN). function assertHookSucceeded(result, stdout = '') { assert.equal(result.code, 0, `exited ${result.code}: ${result.stderr}`) assert.equal(result.stdout, stdout, `stdout was ${JSON.stringify(result.stdout)}`) @@ -142,6 +144,7 @@ const SCRIPTS = { /** * What each harness registers. Claude Code, Codex and Antigravity carry every * report; Crush carries the two its single `PreToolUse` event can honour, + * besides the subagent veto, which is no report (subagent.test.mjs), * because a `busy` nothing can end would pin a spinner to a card * (docs/providers.md). */ @@ -534,9 +537,10 @@ test("Antigravity's registration reaches for no plugin root", () => { // Antigravity reads a JSON object off the hook's stdout and acts on it, so // silence is not the neutral answer it is everywhere else: `decision` is // required on PreToolUse, and an unanswered tool call is a turn this plugin -// interfered with. The shared scripts stay silent — Codex reads their stdout as +// interfered with. The report scripts stay silent — Codex reads their stdout as // an answer to a permission request — so the verdict belongs to the -// registration, and every handler carries one. +// registration, and every handler carries one; on PreToolUse it is the subagent +// veto's, chained after the tool report. const ANTIGRAVITY_VERDICT = { // Let the tool run: this is an observation, never a gate. PreToolUse: '{"decision":"allow"}', diff --git a/tests/subagent.test.mjs b/tests/subagent.test.mjs index d126928..577d872 100644 --- a/tests/subagent.test.mjs +++ b/tests/subagent.test.mjs @@ -455,20 +455,27 @@ for (const harness of HARNESSES) { // up lets the call run. 10 seconds is the contract's wait; one client of each // kind waits it out, side by side. test('a lich that never answers lets the call run after the 10 seconds the contract waits', async () => { - const waited = await Promise.all( - ['claude', 'opencode', 'omp'].map(async (harness) => { - const stub = await startStub({ hang: true }) - const started = Date.now() - try { - assert.deepEqual(await outcome(harness, callOf(harness).payload, lichEnv(stub.port)), { allow: true }) - return [harness, Date.now() - started] - } finally { - await stub.close() - } - }), - ) - for (const [harness, ms] of waited) { - assert.ok(ms >= 9500 && ms < 14000, `${harness} gave up after ${ms} ms`) + // One stub and one environment for all three: the two in-process clients + // read process.env, which the outer withEnv holds steady while they run. + const stub = await startStub({ hang: true }) + const env = lichEnv(stub.port) + try { + const waited = await withEnv(env, () => + Promise.all( + ['claude', 'opencode', 'omp'].map(async (harness) => { + const started = Date.now() + assert.deepEqual(await outcome(harness, callOf(harness).payload, env), { allow: true }) + return [harness, Date.now() - started] + }), + ), + ) + // A script's run also waits for the stub to have read every connection + // (settleStubs), the in-process clients' included, so its ceiling is looser. + for (const [harness, ms] of waited) { + assert.ok(ms >= 9500 && ms < 20000, `${harness} gave up after ${ms} ms`) + } + } finally { + await stub.close() } })