Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 37 additions & 4 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,7 @@ closures; `controller.ts` (`PlannotatorMod`) is the per-session state machine;
`launch.ts` (detached launcher, launch-directory layout, command table, copy),
`delivery.ts` (turn vs log, 12 KB inline limit), `plan.ts` (ExitPlanMode
decisions and deny copy), `turns.ts` and `bridge.ts` (Ask this session),
`shell-words.ts` (argument splitting), `tool.ts` (the `plannotator` tool contract, a copy of `packages/shared/plannotator-tool.ts`). The mod is self-contained: a plugin
`shell-words.ts` (argument splitting), `tool.ts` (the `plannotator` tool contract, a copy of `packages/shared/plannotator-tool.ts`), `take-over.ts` (agent-run Bash `plannotator` commands answered through the tool). The mod is self-contained: a plugin
installed from the marketplace is only `apps/hook/`, and a hooks module may
import only its own files.

Expand Down Expand Up @@ -452,14 +452,47 @@ description, validation, argument mapping, result text) lives once in
copy of its CONTRACT section in `hooks/mod/tool.ts` and `tool.test.ts` fails
when they differ (edit the shared file, then paste). The core `plannotator`
skill carries one host-neutral line: use a `plannotator` tool when the agent has
one. Direct CLI runs are unchanged, including gated `--json` runs an agent
makes on purpose (nothing intercepts Bash `plannotator` commands); plan review
stays on ExitPlanMode. Checked live on 2.1.288: the tool is DEFERRED behind tool
one. Plan review stays on ExitPlanMode. Checked live on 2.1.288: the tool is DEFERRED behind tool
search (no `alwaysLoad` is possible through `$.tool.register`), so Claude sees
only its name until it searches; with the updated skill it searched and called
the tool for "open notes.md in plannotator", while a profile still holding the
older installed skill text loaded that skill and ran the CLI instead.

**Agent-run CLI commands are taken over (Bash).** Because the tool is deferred
and the skill also documents the CLI, Claude sometimes runs
`plannotator annotate x.html --gate --json` in Bash anyway; that blocked the
session and started a server with no bridge token, so Ask AI offered separate
SDK agents instead of "Ask this session". With the mod on, the `tool.call` hook
on the MAIN LOOP's `Bash` parses the command with the host-neutral
`plannotatorCommandToToolInput` (CONTRACT section of
`packages/shared/plannotator-tool.ts`, so it is in the mod's copy too) and, when
it returns a tool input, answers the call itself through the SAME `runTool` →
`open` launch the tool uses (`hooks/mod/take-over.ts`): the command never runs,
the Bash result is the Bash tool's own record `{ stdout: <the tool's opened
text>, stderr: "", interrupted: false }` (a startup error is a `deny`), and a
gated take-over delivers its bare approval as a turn exactly like a gated tool
call. A subagent's Bash command always runs as written: a subagent may work in
its own cwd or worktree, while the mod launches in the session's cwd, so its
`review` or `annotate notes.md` would open the wrong diff or file. Taken over: ONE simple command (no
`; & | < > ( )`, line break, `$`, backtick, unquoted glob/brace, comment, `~user`, unterminated
quote; quoting follows `splitShellWords`, nothing is expanded) whose program is
exactly `plannotator` (the binary on PATH; a path such as `./plannotator` or
`/tmp/dev/plannotator` is a dev build and runs for real), subcommand
`annotate` (one target, `--gate`, `--markdown`), `review` (at most one target, `--base <ref>`),
or `annotate-last` / `last` (no arguments); `--json` is accepted and dropped
(the decision arrives as a message), and the result must pass
`parsePlannotatorToolInput`. Everything else runs as written: other
subcommands, every other flag (`--require-approval`, `--result-file`, `--hook`,
`--tailscale`, `--static`, `--app`, `--no-jina`, `--render-html`,
`--diff-type`, `--local`, `--patch-file`, `--stdin`, `--help`, ...), repeated
flags, several targets, environment prefixes, and any compound command
(`cd x && plannotator ...`, pipes, redirects, substitutions), so scripted
strict gates keep the real CLI and its exit codes. With the mod off, in `-p`/SDK
runs and on Windows nothing is taken over. The CLI the mod launches runs in the
session's cwd (`$.process.run`'s default), the same as for the tool. Pi and
OpenCode do not take over shell runs: there an agent-run `plannotator` command
still runs the CLI.

**Plan review.** The `tool.call` hook on the main loop's ExitPlanMode resolves
the plan (the plan file when it is an absolute `.md` regular file within the
2 MB cap, else the inline `plan`: the #1667 rule), then:
Expand Down
14 changes: 14 additions & 0 deletions apps/hook/hooks/mod/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
* - The `plannotator` tool (`$.tool.register`, tool.ts): when Claude itself is
* asked to open something in Plannotator it calls this tool instead of the
* CLI; the call goes through the same detached launch and returns at once.
* A main-loop Bash call that runs the CLI in a form the tool can represent
* (`plannotator annotate|review|last ...`, take-over.ts) is answered the
* same way instead of running.
* - "Ask this session": each launched server gets a pull-bridge token; the
* mod polls it and runs the reviewer's questions as turns (bridge.ts).
* - `PLANNOTATOR_SESSION_TAG=claude-code:<session id>` in the environment
Expand All @@ -45,6 +48,7 @@ import { resolveClaudeModEnabled } from './enabled'
import type { Host } from './host'
import { COMMANDS, dataDirOf, isModCommand, waitArgv } from './launch'
import { PLAN_TOOL } from './plan'
import { answerShellCall, SHELL_TOOL, shellTakeOver } from './take-over'
import { PLANNOTATOR_TOOL_DESCRIPTION, PLANNOTATOR_TOOL_INPUT_SCHEMA, PLANNOTATOR_TOOL_NAME } from './tool'

// Minimal local types: the engine's declarations are written by `/plugin-types`
Expand Down Expand Up @@ -260,6 +264,16 @@ export function register(on: On) {
const answer = await instance.runTool(toolArgsOf(e))
return 'deny' in answer ? { deny: answer.deny } : { result: answer.text }
}
// Claude running `plannotator annotate|review|last` in Bash on the main
// loop: the same launch and result as the tool (take-over.ts); anything
// the tool cannot represent, and every subagent's command, runs as written.
if (allowed && e.tool === SHELL_TOOL) {
const input = shellTakeOver(e.command, !!e.agentId)
if (!input) return next(e)
const instance = await currentMod($)
if (!instance) return next(e)
return answerShellCall(instance, input)
}
// Only the main loop's ExitPlanMode: a subagent's keeps the classic flow.
if (!allowed || e.tool !== PLAN_TOOL || e.agentId) return next(e)
const instance = await currentMod($)
Expand Down
115 changes: 115 additions & 0 deletions apps/hook/hooks/mod/take-over.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
import { describe, expect, test } from 'bun:test'
import { PlannotatorMod } from './controller'
import { answerShellCall, shellTakeOver } from './take-over'
import { fakeHost, type FakeHost, type RunCall } from './testing/fake-host'

const SESSION = { sessionId: 'session-1', dataDir: '/data', interactive: true }

function isLaunch(call: RunCall): boolean {
return call.argv[0] === '/bin/sh' && call.argv[3] === 'plannotator-launch'
}

function serveOnLaunch(host: FakeHost, port = 4321) {
host.onRun = (call) => {
if (isLaunch(call)) host.files.set(`${call.argv[4]}/ready`, `${JSON.stringify({ url: `http://localhost:${port}`, isRemote: false, port })}\n`)
}
}

/** What register.ts does with a Bash call: the answer, or 'run' when the command runs as written. */
async function bashCall(mod: PlannotatorMod, command: string, agentId?: string) {
const input = shellTakeOver(command, !!agentId)
if (!input) return 'run' as const
return answerShellCall(mod, input)
}

// The failure: Claude runs the CLI through Bash (the owner's case: annotate
// INDEX.html --gate --json), the session blocks, and Ask AI offers separate
// AIs because the server was started without the session's bridge token.
describe('Bash take-over', () => {
test('an agent-run annotate opens through the tool launch, with the bridge, and answers with the tool text', async () => {
const host = fakeHost()
serveOnLaunch(host, 7070)
const mod = new PlannotatorMod(host, SESSION)

const answer = await bashCall(mod, 'plannotator annotate /work/INDEX.html --gate --json')
const viaTool = await mod.runTool({ action: 'annotate', target: '/work/INDEX.html', gate: true })

const [byBash, byTool] = host.runs.filter(isLaunch)
expect(byBash?.argv.slice(5)).toEqual(['plannotator', 'annotate', '/work/INDEX.html', '--gate'])
expect(byBash?.argv.slice(5)).toEqual(byTool?.argv.slice(5))
expect(byBash?.env?.PLANNOTATOR_SESSION_BRIDGE_TOKEN?.length).toBeGreaterThanOrEqual(32)
expect(byBash?.env?.PLANNOTATOR_HOST_RESULT_FILE).toBe(`${byBash?.argv[4]}/result.json`)
// The Bash result is the tool's own text, in the Bash tool's record shape.
expect(answer).toEqual({ result: { stdout: 'text' in viaTool ? viaTool.text : '', stderr: '', interrupted: false } })
expect(JSON.stringify(answer)).toContain('http://localhost:7070')
})

test('a gated agent-run annotate delivers the bare approval, as the tool does', async () => {
const host = fakeHost()
serveOnLaunch(host)
const mod = new PlannotatorMod(host, SESSION)
await bashCall(mod, 'plannotator annotate spec.md --gate --json')

const [launch] = host.runs.filter(isLaunch)
host.files.set(`${launch?.argv[4]}/result.json`, JSON.stringify({ v: 1, surface: 'annotate', decision: 'approved', message: 'The user approved.', noop: true }))
await host.tick()

expect(host.submits).toHaveLength(1)
expect(host.submits[0]).toContain('The user approved.')
})

test('a startup failure is an error result for the Bash call', async () => {
const host = fakeHost()
host.onRun = (call) => {
if (isLaunch(call)) {
host.files.set(`${call.argv[4]}/stderr`, 'File not found: nope.md')
host.files.set(`${call.argv[4]}/exit`, '1')
}
}
const mod = new PlannotatorMod(host, SESSION)

const answer = await bashCall(mod, 'plannotator annotate nope.md')
expect('deny' in (answer as object) && (answer as { deny: string }).deny).toContain('File not found: nope.md')
})

test('strict gates, pipelines and compound commands run as written, and nothing launches', async () => {
const host = fakeHost()
serveOnLaunch(host)
const mod = new PlannotatorMod(host, SESSION)

for (const command of [
'plannotator annotate a.md --gate --json --require-approval',
'plannotator annotate a.md --gate --json --result-file out.json',
'plannotator annotate a.md --gate --json | jq .decision',
'cd docs && plannotator annotate a.md',
'git status',
]) {
expect([command, await bashCall(mod, command)]).toEqual([command, 'run'])
}
expect(host.runs.filter(isLaunch)).toHaveLength(0)
})

// The failure: a subagent working in its own worktree runs `plannotator
// review` and the mod, launching in the session's cwd, opens the wrong diff.
test('a subagent\'s command always runs as written', async () => {
const host = fakeHost()
serveOnLaunch(host)
host.transcript = [{ role: 'assistant', text: 'Main session answer.' }]
const mod = new PlannotatorMod(host, SESSION)

for (const command of ['plannotator review', 'plannotator annotate notes.md --gate --json', 'plannotator last']) {
expect([command, await bashCall(mod, command, 'agent-7')]).toEqual([command, 'run'])
}
expect(host.runs.filter(isLaunch)).toHaveLength(0)
})

test('a dev build run by path runs for real', async () => {
const host = fakeHost()
serveOnLaunch(host)
const mod = new PlannotatorMod(host, SESSION)

expect(await bashCall(mod, './plannotator review')).toBe('run')
expect(await bashCall(mod, '/tmp/dev/plannotator annotate x.md')).toBe('run')
expect(host.runs.filter(isLaunch)).toHaveLength(0)
})
})
43 changes: 43 additions & 0 deletions apps/hook/hooks/mod/take-over.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**
* Claude running the `plannotator` CLI through Bash, answered by the mod.
*
* The skill and the tool steer Claude to the `plannotator` tool, but a model
* that reaches for `plannotator annotate x.md --gate --json` in Bash would
* otherwise block the session on the CLI and give Ask AI a separate AI. When
* the command is one the tool can represent (`plannotatorCommandToToolInput`
* in tool.ts decides, host-neutral), the `tool.call` hook answers the Bash call
* with the tool's own launch and result text; the command never runs. Anything
* else (strict gates, pipelines, unknown flags, a dev build run by path) runs
* as written.
*
* Main loop only: a subagent may run in its own cwd or worktree, while the
* mod launches in the session's cwd, so its `review` or `annotate notes.md`
* would open the wrong diff or file. A subagent's command runs for real.
*/

import { plannotatorCommandToToolInput, type PlannotatorToolInput } from './tool'

/** Claude Code's shell tool. */
export const SHELL_TOOL = 'Bash'

/** The tool input a main-loop Bash call's command stands for; null runs it as written. */
export function shellTakeOver(command: unknown, fromSubagent: boolean): PlannotatorToolInput | null {
if (fromSubagent || typeof command !== 'string') return null
return plannotatorCommandToToolInput(command)
}

/** The Bash tool's result record, carrying the tool's text as the command's output. */
export interface ShellResult {
stdout: string
stderr: string
interrupted: boolean
}

/** Open through the tool's launch; the tool's text becomes the Bash result, its error a deny. */
export async function answerShellCall(
mod: { runTool(input: unknown): Promise<{ text: string } | { deny: string }> },
input: PlannotatorToolInput,
): Promise<{ result: ShellResult } | { deny: string }> {
const answer = await mod.runTool(input)
return 'deny' in answer ? { deny: answer.deny } : { result: { stdout: answer.text, stderr: '', interrupted: false } }
}
Loading
Loading