@nxxxsooo/opencode-annotate 0.18.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.20.0 — AGY reviews in Herdr
4
+
5
+ - In a configured AGY pane, run `/annotate` or press `prefix+a` to open the
6
+ native reviewer as a Herdr overlay without starting a model turn. **Send**
7
+ returns notes to the originating conversation; `q` and `Ctrl+C` do not send.
8
+ - Configured Kitty toolbar images render at full size in Herdr instead of
9
+ showing only their upper-left portion.
10
+
11
+ ## 0.19.0 — Annotate files
12
+
13
+ - Choose **Annotate a file (TUI)** or run `/annotate-file [query]` to find text
14
+ and config files in the current session's directory using OpenCode's `@`
15
+ file search.
16
+ - Pass a supported file path directly to `/annotate` as before. Non-Markdown
17
+ files display as code blocks, preserving their formatting. `.env` and
18
+ credential-looking filenames are excluded.
19
+
3
20
  ## 0.18.0 — Select page areas
4
21
 
5
22
  - Choose **Select area** in the browser panel and drag a rectangle. Feedback
package/README.md CHANGED
@@ -63,15 +63,19 @@ Empty and cancelled reviews submit nothing. Opening a review makes no model call
63
63
 
64
64
  For a selection that spans messages, `/annotate-selection` reviews just the selected text.
65
65
 
66
- ### Review Markdown and text documents
66
+ ### Review text and config files
67
67
 
68
68
  ```text
69
69
  /annotate docs/plan.md # Review a Markdown document
70
70
  /annotate "docs/release plan.md" # Path with spaces
71
71
  /annotate ~/Documents/notes.txt # Plain text
72
+ /annotate-file # Pick a file from this session's directory
73
+ /annotate-file settings # Narrow the file search
72
74
  ```
73
75
 
74
- Local UTF-8 `.md`, `.mdx`, `.markdown` and `.txt` files up to 2 MiB. Relative paths resolve against the captured session's working directory, not the directory from which the terminal client happened to start. Absolute and `~/` paths work too. The file must exist on the machine running the terminal client.
76
+ `/annotate-file` uses OpenCode's `@` file search in the session's directory and its subdirectories, then lets you filter the results in the picker. You can also pass a supported path directly to `/annotate`.
77
+
78
+ Supported files include Markdown, plain text, CSV, logs, JSON, YAML, TOML, XML, and common config files such as `.editorconfig`, `.gitignore`, `Dockerfile`, and `Makefile`. Files must be local UTF-8 and no larger than 2 MiB. `.env` and credential-looking names are excluded. Relative paths resolve against the captured session's working directory; absolute and `~/` paths work too.
75
79
 
76
80
  The reviewer reads a fixed snapshot and does not edit the original file. Feedback includes the original path and snapshot hash, with instructions to re-read the current file before applying suggestions. Document review works even before the session has an assistant reply.
77
81
 
@@ -99,6 +103,7 @@ Browser setup is separate from the plugin install. Safari supports local notes a
99
103
  /annotate docs/plan.md Review a Markdown document
100
104
  /annotate "docs/release plan.md" Review a path containing spaces
101
105
  /annotate ~/Documents/notes.txt Review a plain-text document
106
+ /annotate-file [query] Choose a text or config file in the session directory
102
107
  /annotate-pick Choose a recent reply or mid-turn progress update
103
108
  /annotate-selection Review the message containing your last transcript selection
104
109
  /annotate page.html Review local HTML in the configured browser
@@ -109,6 +114,14 @@ Numbered `/annotate N`, `/annotate-last` and `/annotate-web` are retired. Use `/
109
114
 
110
115
  ## Herdr
111
116
 
117
+ Bind **prefix, then `a`** (`Ctrl+B`, then `a` by default) to
118
+ `annotate.review` using the [manifest and keybinding setup](tui/README.md#herdr).
119
+ In AGY this opens a floating Markdown reviewer without starting a model turn.
120
+ Send starts a turn if AGY is idle or done, or queues feedback if it is working.
121
+ Quit sends nothing. Claude, Codex, Pi, and OpenCode use the existing `herdr last`
122
+ route. With the AGY hooks installed, `/annotate` can open the same popup before
123
+ the model runs; the skill remains available as a fallback.
124
+
112
125
  Run the bundled `annotate-tui` directly from a Herdr pane. Herdr needs an enabled
113
126
  `annotate` plugin with a `doc` pane entrypoint; see the [TUI setup](tui/README.md#herdr).
114
127
  OpenCode's `/annotate` keeps its own session delivery, even when OpenCode runs in Herdr.
@@ -146,11 +159,25 @@ documents and webpages.
146
159
 
147
160
  ## Antigravity (AGY) support
148
161
 
149
- `opencode-annotate` provides companion support for Google Antigravity CLI (`agy`) via `agy-annotate`:
162
+ In a configured Herdr AGY pane, `/annotate` opens a native overlay before the
163
+ model runs. `prefix+a` opens the latest reply, and `/annotate <local-document>`
164
+ can review a file. Outside Herdr on macOS, the skill opens Ghostty or Terminal
165
+ for text reviews. URL and HTML targets use the browser companion.
166
+
167
+ Set up AGY manually from one installed package (`npm install -g @nxxxsooo/opencode-annotate`;
168
+ find the package under `npm root -g`) or a checkout with `npm run build:tui`:
169
+
170
+ 1. Link the package's `agy/skills/annotate` directory as `~/.agents/skills/annotate`.
171
+ 2. Merge the `agy-annotate` entries from `agy/hooks.json` into
172
+ `~/.gemini/config/hooks.json`, replacing `./hooks.mjs` in all three commands
173
+ with the absolute path to `agy/hooks.mjs` from that installation.
174
+ 3. For Herdr, follow the [manifest and keybinding setup](tui/README.md#herdr)
175
+ using the CLI and native reviewer from the same installation.
176
+
177
+ **Send** (`Ctrl+S` or the Send button) returns feedback to the captured AGY
178
+ conversation. In Herdr it starts a turn if AGY is idle or done, or queues
179
+ feedback for its lifecycle hooks if AGY is working. `q` and `Ctrl+C` do not send.
150
180
 
151
- - **Slash command `/annotate`**: Built-in AGY skill at `agy/skills/annotate/` handles text and explicit URL/HTML review within active AGY sessions.
152
- - **Interactive TUI**: Uses the same bundled reviewer as OpenCode, with Dracula theme inheritance and one-key send.
153
- - **Native Delivery**: Hooks into AGY lifecycle (`SessionStart`, `PreInvocation`, `Stop`) to deliver feedback directly into the conversation turn without network listeners.
154
181
  - **CLI Commands**:
155
182
  ```sh
156
183
  npx --package @nxxxsooo/opencode-annotate@latest agy-annotate status
@@ -211,7 +238,7 @@ After a page reload or same-site navigation, the panel reconnects its page tools
211
238
 
212
239
  ### Explicit routing
213
240
 
214
- Plain `/annotate`, `/annotate-pick` and `/annotate-selection` use the TUI; Markdown and plain-text files do too. Explicit URLs and HTML paths passed to `/annotate` enter the browser workflow. A reply containing HTML links or code fences does not change the default.
241
+ Plain `/annotate`, `/annotate-file`, `/annotate-pick` and `/annotate-selection` use the TUI; text and config paths do too. Explicit URLs and HTML paths passed to `/annotate` enter the browser workflow. A reply containing HTML links or code fences does not change the default.
215
242
 
216
243
  ### Browser safeguards and limitations
217
244
 
@@ -366,6 +393,7 @@ See [release instructions](docs/releasing.md) and [changelog](CHANGELOG.md).
366
393
 
367
394
  - `/annotate`:批注上一条完整回复。
368
395
  - `/annotate 文档.md`:批注文档,支持中文、空格和相对路径。
396
+ - `/annotate-file [关键词]`:从当前会话目录及其子目录中选择文本或配置文件。
369
397
  - `/annotate-pick`:从最近的回复和运行中的进度说明里选一条批注。
370
398
  - `/annotate-selection`:先在会话里拖选文字,再批注包含这段文字的消息。
371
399
  - 0.16.0 移除 `/ref` 和代理会话搜索/读取工具,交由 Another 提供跨代理引用:安装 Another 0.28.0 或更高版本并运行 `another setup` 即可。原有插件配置继续有效,请移除 `annotate_session_*` 权限规则。
package/agy/cli.mjs CHANGED
@@ -1,21 +1,19 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn, execFile } from "node:child_process"
3
3
  import { promisify } from "node:util"
4
- import { mkdtemp, mkdir, rm, readFile, writeFile } from "node:fs/promises"
4
+ import { mkdtemp, mkdir, rename, rm, readFile, writeFile } from "node:fs/promises"
5
+ import { setTimeout as wait } from "node:timers/promises"
5
6
  import path from "node:path"
6
7
  import os from "node:os"
7
8
  import { fileURLToPath } from "node:url"
8
9
  import { randomUUID, createHash } from "node:crypto"
9
10
  import { findSessionForDirectory, getActiveAgySessions } from "./session.mjs"
10
- import { extractAgyReplies, latestCompletedReply, defaultBrainDir } from "./transcript.mjs"
11
- import { enqueueAnnotations, listPendingBatches, defaultInboxRoot } from "./inbox.mjs"
12
- import { startAgyDaemon } from "./daemon.mjs"
13
- import { listTargets, registryRoot } from "../bridge/receiver.mjs"
14
- import { browserTarget } from "../targets.mjs"
15
- import { openInBrowser } from "../scripts/browser-target.mjs"
11
+ import { extractAgyReplies, defaultBrainDir } from "./transcript.mjs"
12
+ import { enqueueAnnotations, listPendingBatches } from "./inbox.mjs"
16
13
  import { prepareTheme } from "../theme.mjs"
17
14
  import { createInputSource } from "../input-source.mjs"
18
15
  import { resolveTuiBinary } from "../tui/binary.mjs"
16
+ import { captureHerdrConversation, deliverHerdrReview, focusedPane, herdrCommand, readHerdrAgent } from "./herdr.mjs"
19
17
 
20
18
  const execute = promisify(execFile)
21
19
 
@@ -71,6 +69,7 @@ async function resolveSession(targetId) {
71
69
  }
72
70
 
73
71
  async function cmdStatus() {
72
+ const { listTargets } = await import("../bridge/receiver.mjs")
74
73
  const sessions = getActiveAgySessions()
75
74
  const targets = await listTargets()
76
75
 
@@ -93,6 +92,7 @@ async function cmdStatus() {
93
92
  }
94
93
 
95
94
  async function cmdWeb(targetArg, options) {
95
+ const { listTargets } = await import("../bridge/receiver.mjs")
96
96
  const session = await resolveSession(options.session)
97
97
  const targets = await listTargets()
98
98
  let paired = targets.find(t => t.sessionID === session.conversationId)
@@ -121,10 +121,12 @@ async function cmdWeb(targetArg, options) {
121
121
  console.log(` Open the "Annotate" extension and choose this session (Safari copies notes locally).`)
122
122
 
123
123
  if (targetArg && targetArg.trim()) {
124
+ const { browserTarget } = await import("../targets.mjs")
124
125
  const target = await browserTarget(targetArg, session.directory)
125
126
  if (target?.url) {
126
127
  console.log(` Opening target: ${target.url}`)
127
128
  if (process.platform === "darwin") {
129
+ const { openInBrowser } = await import("../scripts/browser-target.mjs")
128
130
  await openInBrowser(target.url, options)
129
131
  }
130
132
  }
@@ -148,86 +150,175 @@ async function cmdQueue(options) {
148
150
  }
149
151
  }
150
152
 
151
- async function cmdTui(targetPath, options) {
152
- const session = await resolveSession(options.session)
153
- const binary = resolveTuiBinary(options.binary)
154
- const brainDir = defaultBrainDir(session.conversationId)
155
- const calledByAgent = Boolean(process.env.ANTIGRAVITY_AGENT || process.env.AGENT_TOOL_CALL)
156
- const isInteractiveTTY = Boolean(options.interactiveTty) || (!calledByAgent && Boolean(process.stdin.isTTY) && !options.spawnWindow)
157
-
158
- if (!isInteractiveTTY) {
159
- const launcherScript = path.join(os.tmpdir(), `agy-annotate-launch-${Date.now()}.sh`)
160
- const doneMarker = path.join(os.tmpdir(), `agy-annotate-done-${Date.now()}.txt`)
161
- const cliScript = path.resolve(new URL(import.meta.url).pathname)
162
- const tuiArgs = [cliScript, "tui", "--interactive-tty", "--session", session.conversationId]
163
- if (targetPath) tuiArgs.push(targetPath)
164
- if (options.binary) tuiArgs.push("--binary", options.binary)
165
-
166
- const escapedTitle = (session.title || "Review").replace(/'/g, "'\\''")
167
- const shellCmd = `printf '\\033]0;Annotate: %s\\007' '${escapedTitle}'\n${process.execPath} ${tuiArgs.map(a => `'${a.replace(/'/g, "'\\''")}'`).join(" ")}; echo done > '${doneMarker}'`
168
- await writeFile(launcherScript, `#!/bin/sh\n${shellCmd}\n`, { mode: 0o755 })
169
-
170
- const beforeBatches = await listPendingBatches(session.conversationId)
171
-
172
- let launched = false
153
+ export async function selectTuiOpener({ env, tty, exec = execute }) {
154
+ if (env.HERDR_ENV === "1" && env.HERDR_PANE_ID) {
155
+ const bin = env.HERDR_BIN_PATH || "herdr"
156
+ const response = await exec(bin, ["pane", "get", env.HERDR_PANE_ID], { env, timeout: 2000 }).catch(() => null)
157
+ if (response) {
158
+ const { result } = JSON.parse(response.stdout)
159
+ if (result?.pane?.pane_id && result.pane.tab_id) return { kind: "herdr", bin, pane: result.pane }
160
+ }
161
+ }
162
+ const calledByAgent = Boolean(env.ANTIGRAVITY_CONVERSATION_ID || env.ANTIGRAVITY_AGENT || env.AGENT_TOOL_CALL)
163
+ return { kind: tty && !calledByAgent ? "tty" : "window" }
164
+ }
165
+
166
+ async function openTuiWindow(directory, title) {
167
+ const launcher = path.join(directory, "launch.sh")
168
+ const quote = value => `'${value.replaceAll("'", "'\\''")}'`
169
+ const windowTitle = `Annotate: ${title}`.replace(/[\x00-\x1f\x7f-\x9f]/g, "")
170
+ const command = [process.execPath, fileURLToPath(import.meta.url), "tui-pane", directory].map(quote).join(" ")
171
+ await writeFile(launcher, `#!/bin/sh\nprintf '\\033]0;%s\\007' ${quote(windowTitle)}\nexec ${command}\n`, { mode: 0o700 })
172
+ try {
173
+ await execute("open", ["-na", "Ghostty", "--args", "--window-width=172", "--window-height=48", `--title=${windowTitle}`, "-e", launcher])
174
+ } catch {
173
175
  try {
174
- const windowTitle = `Annotate: ${session.title}`
175
- await execute("open", ["-na", "Ghostty", "--args", "--window-width=172", "--window-height=48", `--title=${windowTitle}`, "-e", launcherScript])
176
- launched = true
177
- } catch {
178
- try {
179
- await execute("osascript", ["-e", `tell application "Terminal" to do script "${launcherScript}"`, "-e", 'tell application "Terminal" to activate'])
180
- launched = true
181
- } catch (err) {
182
- throw new Error(`Failed to spawn interactive review window: ${err.message}`)
183
- }
176
+ await execute("osascript", ["-e", `tell application "Terminal" to do script ${JSON.stringify(quote(launcher))}`, "-e", 'tell application "Terminal" to activate'])
177
+ } catch (err) {
178
+ throw new Error(`Failed to spawn interactive review window: ${err.message}`)
184
179
  }
180
+ }
181
+ }
185
182
 
186
- console.log(`Opened interactive Annotate TUI window for "${session.title}".`)
187
- console.log("Waiting for user to complete annotations (press 'q' or Ctrl+S to finish)...")
183
+ async function openHerdrTui({ bin, pane }, directory) {
184
+ // Herdr overlays belong to the active pane; --target-pane is split-only.
185
+ if (!pane.focused) throw new Error("Focus the AGY pane in Herdr and retry /annotate.")
186
+ try {
187
+ const { stdout } = await execute(bin, [
188
+ "plugin", "pane", "open", "--plugin", "annotate", "--entrypoint", "agy",
189
+ "--placement", "overlay",
190
+ "--focus", "--cwd", directory, "--env", `ANNOTATE_AGY_REVIEW_DIR=${directory}`,
191
+ ], { timeout: 5000 })
192
+ const opened = JSON.parse(stdout).result?.plugin_pane?.pane
193
+ if (!opened?.pane_id) throw new Error("Herdr did not return the opened pane ID.")
194
+ if (opened.tab_id !== pane.tab_id) {
195
+ await execute(bin, ["pane", "close", opened.pane_id], { timeout: 2000 })
196
+ throw new Error("Herdr placed the overlay outside the AGY tab. Focus the AGY tab and try again.")
197
+ }
198
+ return opened.pane_id
199
+ } catch (err) {
200
+ throw new Error(`Failed to open the Herdr review overlay. Check that the annotate plugin has the agy pane entrypoint.\n${err.message}`)
201
+ }
202
+ }
188
203
 
189
- for (let i = 0; i < 300; i++) {
190
- await new Promise(r => setTimeout(r, 1000))
191
- const currentBatches = await listPendingBatches(session.conversationId)
192
- if (currentBatches.length > beforeBatches.length) {
193
- const newest = currentBatches[currentBatches.length - 1]
194
- console.log(`\n✓ Annotations received from review window:\n\n${newest.markdown}`)
195
- try { await rm(launcherScript, { force: true }); await rm(doneMarker, { force: true }) } catch {}
196
- return
197
- }
198
- try {
199
- await readFile(doneMarker)
200
- await new Promise(r => setTimeout(r, 500))
201
- const finalBatches = await listPendingBatches(session.conversationId)
202
- if (finalBatches.length > beforeBatches.length) {
203
- const newest = finalBatches[finalBatches.length - 1]
204
- console.log(`\n✓ Annotations received from review window:\n\n${newest.markdown}`)
205
- } else {
206
- console.log("Interactive review window closed without annotations.")
207
- }
208
- try { await rm(launcherScript, { force: true }); await rm(doneMarker, { force: true }) } catch {}
209
- return
210
- } catch {
211
- // Still waiting
212
- }
204
+ function runReviewer({ binary, snapshotFile, env }, directory) {
205
+ const child = spawn(binary, [snapshotFile], {
206
+ cwd: directory,
207
+ env: { ...process.env, ...env },
208
+ stdio: "inherit",
209
+ })
210
+ return new Promise((resolve, reject) => {
211
+ child.on("exit", (code, signal) => {
212
+ if (code === 0) resolve()
213
+ else reject(new Error(`Reviewer exited with ${signal || code}.`))
214
+ })
215
+ child.on("error", reject)
216
+ })
217
+ }
218
+
219
+ async function runTuiPane(directory) {
220
+ if (!directory || !path.isAbsolute(directory)) throw new Error("Missing AGY review directory.")
221
+ let result = "closed"
222
+ try {
223
+ const request = JSON.parse(await readFile(path.join(directory, "request.json"), "utf8"))
224
+ if (request.sourcePane && focusedPane(process.env) !== request.sourcePane) {
225
+ throw new Error("Herdr focus changed before the popup opened. Open Annotate again from the AGY pane.")
213
226
  }
214
- return
227
+ await runReviewer(request, directory)
228
+ } catch (err) {
229
+ result = err.message
215
230
  }
231
+ await writeFile(path.join(directory, "done.tmp"), result, { mode: 0o600 })
232
+ await rename(path.join(directory, "done.tmp"), path.join(directory, "done"))
233
+ }
234
+
235
+ async function readOptional(file) {
236
+ return readFile(file, "utf8").catch(err => {
237
+ if (err.code !== "ENOENT") throw err
238
+ return null
239
+ })
240
+ }
241
+
242
+ async function waitForTuiPane(directory, herdrPane) {
243
+ const deadline = Date.now() + 300_000
244
+ while (Date.now() < deadline) {
245
+ const result = await readOptional(path.join(directory, "done"))
246
+ if (result === "closed") return true
247
+ if (result !== null) throw new Error(result)
248
+ if (herdrPane) {
249
+ const { bin, id } = herdrPane
250
+ const missing = await execute(bin, ["pane", "get", id], { timeout: 2000 }).then(() => false, err => {
251
+ try { return JSON.parse(err.stderr).error?.code === "pane_not_found" } catch { return false }
252
+ })
253
+ if (missing && await readOptional(path.join(directory, "done")) === null) return false
254
+ }
255
+ await wait(500)
256
+ }
257
+ throw new Error("Timed out waiting for Annotate.")
258
+ }
216
259
 
260
+ // The hook is the only feedback channel. Neither the pane nor the waiting tool
261
+ // returns the Markdown, and no other pending batch can finish this review.
262
+ export async function finishTuiReview({ intentPath, conversationId, header, exportFeedback, enqueue = enqueueAnnotations, deliver }) {
263
+ if (await readOptional(intentPath) !== "send\n") return "Review closed without sending annotations."
264
+ const feedback = (await exportFeedback()).trim()
265
+ if (!feedback || feedback === "No annotations.") return "No annotations to send."
266
+ const batch = {
267
+ batchID: `tui-${randomUUID()}`,
268
+ markdown: `${header}\n\n${feedback}`,
269
+ promptID: `msg_${randomUUID()}`,
270
+ }
271
+ if (deliver) return deliver(batch)
272
+ await enqueue(conversationId, batch)
273
+ return "Annotations queued for this AGY conversation. The lifecycle hook will deliver them."
274
+ }
275
+
276
+ async function cmdTui(targetPath, options) {
277
+ const session = await resolveSession(options.session || process.env.ANTIGRAVITY_CONVERSATION_ID)
278
+ const binary = path.resolve(resolveTuiBinary(options.binary))
279
+ const opener = await selectTuiOpener({ env: process.env, tty: process.stdin.isTTY })
280
+ await reviewTui(targetPath, { session, binary, opener })
281
+ }
282
+
283
+ async function cmdHerdrReview(options, shortcut) {
284
+ const bin = process.env.HERDR_BIN_PATH || "herdr"
285
+ const binary = path.resolve(resolveTuiBinary(options.binary))
286
+ try {
287
+ const pane = shortcut?.pane ?? focusedPane(process.env)
288
+ const agent = await readHerdrAgent(bin, pane)
289
+ if (!shortcut && ["claude", "codex", "pi", "opencode"].includes(agent.agent)) {
290
+ const { stdout } = await execute(binary, ["herdr", "last", "--newest", "--deliver-to", pane], { timeout: 5000 })
291
+ console.log(stdout.trim())
292
+ return
293
+ }
294
+ if (agent.agent !== "agy") throw new Error("This action supports AGY, Claude, Codex, Pi, and OpenCode panes.")
295
+ const captured = { ...await captureHerdrConversation(bin, pane, agent), bin, pane, terminalId: agent.terminal_id }
296
+ if (shortcut && (!agent.focused || captured.conversationId !== shortcut.conversationId)) {
297
+ throw new Error("The AGY pane or conversation changed before Annotate opened.")
298
+ }
299
+ const session = { conversationId: captured.conversationId, title: `AGY ${captured.conversationId.slice(0, 8)}` }
300
+ const status = await reviewTui(shortcut?.document, { session, binary, opener: { kind: "popup" }, captured })
301
+ if (status) await herdrCommand(bin, ["notification", "show", "Annotate", "--body", status]).catch(() => {})
302
+ } catch (err) {
303
+ await herdrCommand(bin, ["notification", "show", "Annotate", "--body", err.message]).catch(() => {})
304
+ throw err
305
+ }
306
+ }
307
+
308
+ async function reviewTui(targetPath, { session, binary, opener, captured }) {
217
309
  let sourceText = ""
218
310
  let snapshotName = "last-reply.md"
219
311
  let filePath = null
220
312
  let sourceHash = null
221
313
 
222
314
  if (targetPath) {
223
- const resolvedPath = path.resolve(session.directory, targetPath)
315
+ const resolvedPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(session.directory, targetPath)
224
316
  sourceText = await readFile(resolvedPath, "utf8")
225
317
  filePath = resolvedPath
226
318
  snapshotName = path.basename(resolvedPath)
227
319
  sourceHash = createHash("sha256").update(Buffer.from(sourceText)).digest("hex")
228
320
  } else {
229
- const replies = await extractAgyReplies(brainDir)
230
- const latest = latestCompletedReply(replies)
321
+ const [latest] = await extractAgyReplies(defaultBrainDir(session.conversationId), { latestOnly: true })
231
322
  if (!latest || !latest.text.trim()) {
232
323
  throw new Error(`No completed assistant replies found in session "${session.title}".`)
233
324
  }
@@ -243,67 +334,83 @@ async function cmdTui(targetPath, options) {
243
334
  await mkdir(dataDir, { recursive: true, mode: 0o700 })
244
335
  await writeFile(snapshotFile, sourceText, { mode: 0o600 })
245
336
 
246
- let env = {
247
- ...process.env,
248
- PLANNOTATOR_DATA_DIR: dataDir,
249
- PLANNOTATOR_FEEDBACK_HISTORY: "0",
250
- PLANNOTATOR_TUI_SEND_INTENT: intentPath,
251
- }
252
-
253
- env = await prepareTheme({ binary, theme: getAdaptedThemeTokens(), directory: tempDir, env })
254
-
255
- // Browse in ASCII so an input method cannot swallow review keys; see input-source.mjs.
256
337
  const inputSource = createInputSource()
257
- const textSource = await inputSource.ascii()
258
- if (inputSource.command && textSource) {
259
- env.PLANNOTATOR_TUI_INPUT_SOURCE = inputSource.command
260
- env.PLANNOTATOR_TUI_TEXT_INPUT_SOURCE = textSource
261
- }
338
+ let textSource
339
+ let complete = false
262
340
 
263
341
  try {
264
- // Run the bundled reviewer interactively.
265
- const child = spawn(binary, [snapshotFile], {
266
- cwd: tempDir,
267
- env,
268
- stdio: "inherit",
269
- })
270
-
271
- await new Promise((resolve, reject) => {
272
- child.on("exit", (code, signal) => {
273
- if (signal) reject(new Error(`TUI killed by signal ${signal}`))
274
- else resolve(code)
275
- })
276
- child.on("error", reject)
277
- }).finally(() => inputSource.select(textSource))
278
-
279
- // Export annotations
280
- const { stdout } = await execute(binary, ["--export", snapshotFile], {
281
- cwd: tempDir,
282
- env,
283
- timeout: 15000,
284
- })
285
- const feedback = stdout.trim()
286
-
287
- if (!feedback || feedback === "No annotations.") {
288
- console.log("No annotations created. Returned to terminal.")
289
- return
342
+ // Keep ASCII active before the first usable frame. Run the switch alongside
343
+ // theme setup, but wait for it even if the theme fails so it can be restored.
344
+ const [themedResult] = await Promise.allSettled([
345
+ prepareTheme({ binary, theme: getAdaptedThemeTokens(), directory: tempDir, env: process.env }),
346
+ inputSource.ascii().then(previous => { textSource = previous }),
347
+ ])
348
+ if (themedResult.status === "rejected") throw themedResult.reason
349
+ const themed = themedResult.value
350
+ const env = {
351
+ PLANNOTATOR_DATA_DIR: dataDir,
352
+ PLANNOTATOR_FEEDBACK_HISTORY: "0",
353
+ PLANNOTATOR_TUI_SEND_INTENT: intentPath,
354
+ PLANNOTATOR_TUI_EXPLICIT_SEND: "1",
290
355
  }
356
+ if (themed.PLANNOTATOR_TUI_CONFIG) env.PLANNOTATOR_TUI_CONFIG = themed.PLANNOTATOR_TUI_CONFIG
291
357
 
292
- const header = filePath
293
- ? `Annotations on document \`${filePath}\` (SHA-256: ${sourceHash}):`
294
- : `Annotations on latest assistant response in session "${session.title}":`
295
- const combined = `${header}\n\n${feedback}`
358
+ if (inputSource.command && textSource) {
359
+ env.PLANNOTATOR_TUI_INPUT_SOURCE = inputSource.command
360
+ env.PLANNOTATOR_TUI_TEXT_INPUT_SOURCE = textSource
361
+ }
362
+ const request = { binary, snapshotFile, env, sourcePane: captured?.pane }
363
+ if (opener.kind === "tty") {
364
+ await runReviewer(request, tempDir)
365
+ } else {
366
+ await writeFile(path.join(tempDir, "request.json"), JSON.stringify(request), { mode: 0o600 })
367
+ let herdrPane
368
+ if (captured) {
369
+ const { bin } = captured
370
+ const popupEnv = {
371
+ ...env,
372
+ PLANNOTATOR_TUI_FILE: snapshotFile,
373
+ ANNOTATE_AGY_REVIEW_DIR: tempDir,
374
+ ANNOTATE_AGY_SOURCE_PANE: captured.pane,
375
+ }
376
+ const result = await herdrCommand(bin, [
377
+ "plugin", "pane", "open", "--plugin", process.env.HERDR_PLUGIN_ID || "annotate",
378
+ "--entrypoint", "agy-popup", "--cwd", tempDir,
379
+ ...Object.entries(popupEnv).flatMap(([key, value]) => ["--env", `${key}=${value}`]),
380
+ ])
381
+ if (result?.type !== "ok") throw new Error("The agy-popup entrypoint must declare placement = \"popup\".")
382
+ } else if (opener.kind === "herdr") herdrPane = { bin: opener.bin, id: await openHerdrTui(opener, tempDir) }
383
+ else await openTuiWindow(tempDir, session.title)
384
+ console.log(`Opened Annotate ${opener.kind === "herdr" ? "overlay" : opener.kind}. Waiting for Send or quit…`)
385
+ if (!await waitForTuiPane(tempDir, herdrPane)) {
386
+ console.log(`Review pane closed without sending. Review files retained at ${tempDir}`)
387
+ return
388
+ }
389
+ }
296
390
 
297
- await enqueueAnnotations(session.conversationId, {
298
- batchID: `tui-${Date.now()}`,
299
- markdown: combined,
300
- promptID: `msg_${randomUUID()}`,
391
+ const status = await finishTuiReview({
392
+ intentPath,
393
+ conversationId: session.conversationId,
394
+ deliver: captured && (batch => deliverHerdrReview(captured, batch)),
395
+ header: filePath
396
+ ? `Annotations on document \`${filePath}\` (SHA-256: ${sourceHash}):`
397
+ : `Annotations on latest assistant response in session "${session.title}":`,
398
+ exportFeedback: async () => {
399
+ const { stdout } = await execute(binary, ["--export", snapshotFile], {
400
+ cwd: tempDir, env: { ...process.env, ...env }, timeout: 15000,
401
+ })
402
+ await writeFile(path.join(tempDir, "feedback.md"), stdout, { mode: 0o600 })
403
+ return stdout
404
+ },
301
405
  })
302
-
303
- console.log(`\n✓ Enqueued annotations for AGY session: "${session.title}"`)
304
- console.log(` The next AGY turn or invocation will ingest this feedback.`)
406
+ complete = true
407
+ console.log(status)
408
+ return status
409
+ } catch (err) {
410
+ throw new Error(`${err.message} Review files retained at ${tempDir}`, { cause: err })
305
411
  } finally {
306
- await rm(tempDir, { recursive: true, force: true })
412
+ await inputSource.select(textSource)
413
+ if (complete) await rm(tempDir, { recursive: true, force: true })
307
414
  }
308
415
  }
309
416
 
@@ -315,6 +422,17 @@ async function main() {
315
422
  }
316
423
 
317
424
  const command = args[0]
425
+ if (command === "tui-pane") {
426
+ await runTuiPane(args[1] || process.env.ANNOTATE_AGY_REVIEW_DIR)
427
+ return
428
+ }
429
+ if (command === "herdr-slash") {
430
+ const [, pane, conversationId, binary, document] = args
431
+ if (process.env.HERDR_ENV !== "1" || !pane || pane !== process.env.HERDR_PANE_ID ||
432
+ !conversationId || (document && !path.isAbsolute(document))) throw new Error("Invalid AGY slash launch.")
433
+ await cmdHerdrReview({ binary: binary || undefined }, { pane, conversationId, document })
434
+ return
435
+ }
318
436
  const options = {}
319
437
  let posArg = null
320
438
 
@@ -323,8 +441,6 @@ async function main() {
323
441
  options.session = args[++i]
324
442
  } else if (args[i] === "--binary") {
325
443
  options.binary = args[++i]
326
- } else if (args[i] === "--interactive-tty") {
327
- options.interactiveTty = true
328
444
  } else if (args[i] === "--browser") {
329
445
  options.browser = args[++i]
330
446
  } else if (!args[i].startsWith("-") && !posArg) {
@@ -342,6 +458,9 @@ async function main() {
342
458
  case "tui":
343
459
  await cmdTui(posArg, options)
344
460
  break
461
+ case "herdr-review":
462
+ await cmdHerdrReview(options)
463
+ break
345
464
  case "queue":
346
465
  await cmdQueue(options)
347
466
  break
package/agy/cli.test.mjs CHANGED
@@ -2,11 +2,60 @@ import { test } from "node:test"
2
2
  import assert from "node:assert/strict"
3
3
  import path from "node:path"
4
4
  import os from "node:os"
5
- import { mkdir, rm } from "node:fs/promises"
6
- import { getAdaptedThemeTokens } from "./cli.mjs"
5
+ import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"
6
+ import { finishTuiReview, getAdaptedThemeTokens, selectTuiOpener } from "./cli.mjs"
7
+ import { handlePreInvocation, handleStop } from "./hooks.mjs"
8
+ import { enqueueAnnotations } from "./inbox.mjs"
7
9
  import { bundledBinary, resolveTuiBinary } from "../tui/binary.mjs"
8
10
  import { prepareTheme } from "../theme.mjs"
9
11
 
12
+ test("Herdr opens an overlay only via a reachable calling pane; other calls keep their opener", async () => {
13
+ const env = { HERDR_ENV: "1", HERDR_PANE_ID: "w5:p2", HERDR_BIN_PATH: "/fixture/herdr" }
14
+ const pane = { pane_id: "w5:p2", workspace_id: "w5", tab_id: "w5:t2" }
15
+ const exec = async (bin, args, options) => {
16
+ assert.equal(bin, env.HERDR_BIN_PATH)
17
+ assert.deepEqual(args, ["pane", "get", env.HERDR_PANE_ID])
18
+ assert.equal(options.env, env)
19
+ return { stdout: JSON.stringify({ result: { pane } }) }
20
+ }
21
+ assert.deepEqual(await selectTuiOpener({ env, exec, tty: false }), { kind: "herdr", bin: env.HERDR_BIN_PATH, pane })
22
+ const unavailable = async () => { throw new Error("no server") }
23
+ assert.deepEqual(await selectTuiOpener({ env, exec: unavailable, tty: false }), { kind: "window" })
24
+ assert.deepEqual(await selectTuiOpener({ env: {}, tty: true }), { kind: "tty" })
25
+ assert.deepEqual(await selectTuiOpener({ env: { AGENT_TOOL_CALL: "1" }, tty: true }), { kind: "window" })
26
+ })
27
+
28
+ test("only exact Send intent may export or enqueue; only one target hook gets the notes", async t => {
29
+ const root = await mkdtemp(path.join(os.tmpdir(), "agy-finish-test-"))
30
+ t.after(() => rm(root, { recursive: true, force: true }))
31
+ const intentPath = path.join(root, "intent")
32
+ const inboxRoot = path.join(root, "inbox")
33
+ const conversationId = "captured"
34
+ const note = "Private review content"
35
+ let exports = 0
36
+ const finish = () => finishTuiReview({
37
+ intentPath, conversationId, header: "Review header",
38
+ exportFeedback: async () => { exports++; return note },
39
+ enqueue: (id, batch) => enqueueAnnotations(id, batch, inboxRoot),
40
+ })
41
+ assert.match(await finish(), /without sending/)
42
+ await writeFile(intentPath, "cancel\n")
43
+ assert.match(await finish(), /without sending/)
44
+ assert.equal(exports, 0)
45
+ await writeFile(intentPath, "send\n")
46
+ const status = await finish()
47
+ assert.match(status, /queued/)
48
+ assert.ok(!status.includes(note))
49
+ assert.equal(exports, 1)
50
+ assert.deepEqual(await handleStop({ conversationId: "unrelated" }, { inboxRoot }), {})
51
+ const outcomes = await Promise.all([
52
+ handleStop({ conversationId }, { inboxRoot }),
53
+ handlePreInvocation({ conversationId }, { inboxRoot }),
54
+ ])
55
+ assert.equal(JSON.stringify(outcomes).split(note).length - 1, 1)
56
+ assert.deepEqual(await handleStop({ conversationId }, { inboxRoot }), {})
57
+ })
58
+
10
59
  test("both adapters resolve the packaged reviewer or an explicit custom binary", () => {
11
60
  const custom = "/custom/bin/annotate-tui"
12
61
  assert.equal(resolveTuiBinary(custom), custom)