@nxxxsooo/opencode-annotate 0.19.0 → 0.20.1

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,24 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.20.1 — Send AGY notes on quit
4
+
5
+ - In AGY reviews, `q` sends pending notes and closes, matching OpenCode.
6
+ With no notes, `q` just closes. `Ctrl+C` still closes without sending.
7
+ - `/annotate` in a Herdr AGY pane no longer leaves AGY showing `Working…`
8
+ after the review opens, so Send delivers right away instead of queueing.
9
+ - Model-invoked AGY reviews open in a split without stealing focus when the AGY
10
+ pane is unfocused.
11
+ - Declined AGY slash interceptions and popup outcomes are logged to
12
+ `~/.local/share/opencode-annotate/agy-review.log`.
13
+
14
+ ## 0.20.0 — AGY reviews in Herdr
15
+
16
+ - In a configured AGY pane, run `/annotate` or press `prefix+a` to open the
17
+ native reviewer as a Herdr overlay without starting a model turn. **Send**
18
+ returns notes to the originating conversation; `q` and `Ctrl+C` do not send.
19
+ - Configured Kitty toolbar images render at full size in Herdr instead of
20
+ showing only their upper-left portion.
21
+
3
22
  ## 0.19.0 — Annotate files
4
23
 
5
24
  - Choose **Annotate a file (TUI)** or run `/annotate-file [query]` to find text
package/README.md CHANGED
@@ -114,6 +114,15 @@ Numbered `/annotate N`, `/annotate-last` and `/annotate-web` are retired. Use `/
114
114
 
115
115
  ## Herdr
116
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
+ Press `q` to send pending notes and close, or `Ctrl+C` to close without
122
+ sending. Claude, Codex, Pi, and OpenCode use the existing `herdr last`
123
+ route. With the AGY hooks installed, `/annotate` can open the same popup before
124
+ the model runs; the skill remains available as a fallback.
125
+
117
126
  Run the bundled `annotate-tui` directly from a Herdr pane. Herdr needs an enabled
118
127
  `annotate` plugin with a `doc` pane entrypoint; see the [TUI setup](tui/README.md#herdr).
119
128
  OpenCode's `/annotate` keeps its own session delivery, even when OpenCode runs in Herdr.
@@ -151,11 +160,26 @@ documents and webpages.
151
160
 
152
161
  ## Antigravity (AGY) support
153
162
 
154
- `opencode-annotate` provides companion support for Google Antigravity CLI (`agy`) via `agy-annotate`:
163
+ In a configured Herdr AGY pane, `/annotate` opens a native overlay before the
164
+ model runs. `prefix+a` opens the latest reply, and `/annotate <local-document>`
165
+ can review a file. Outside Herdr on macOS, the skill opens Ghostty or Terminal
166
+ for text reviews. URL and HTML targets use the browser companion.
167
+
168
+ Set up AGY manually from one installed package (`npm install -g @nxxxsooo/opencode-annotate`;
169
+ find the package under `npm root -g`) or a checkout with `npm run build:tui`:
170
+
171
+ 1. Link the package's `agy/skills/annotate` directory as `~/.agents/skills/annotate`.
172
+ 2. Merge the `agy-annotate` entries from `agy/hooks.json` into
173
+ `~/.gemini/config/hooks.json`, replacing `./hooks.mjs` in all three commands
174
+ with the absolute path to `agy/hooks.mjs` from that installation.
175
+ 3. For Herdr, follow the [manifest and keybinding setup](tui/README.md#herdr)
176
+ using the CLI and native reviewer from the same installation.
177
+
178
+ **Send** (`Ctrl+S` or the Send button) returns feedback to the captured AGY
179
+ conversation. In Herdr it starts a turn if AGY is idle or done, or queues
180
+ feedback for its lifecycle hooks if AGY is working. `q` sends pending notes and
181
+ closes; with no notes it just closes. `Ctrl+C` closes without sending.
155
182
 
156
- - **Slash command `/annotate`**: Built-in AGY skill at `agy/skills/annotate/` handles text and explicit URL/HTML review within active AGY sessions.
157
- - **Interactive TUI**: Uses the same bundled reviewer as OpenCode, with Dracula theme inheritance and one-key send.
158
- - **Native Delivery**: Hooks into AGY lifecycle (`SessionStart`, `PreInvocation`, `Stop`) to deliver feedback directly into the conversation turn without network listeners.
159
183
  - **CLI Commands**:
160
184
  ```sh
161
185
  npx --package @nxxxsooo/opencode-annotate@latest agy-annotate status
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, recordHerdrOutcome } 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,186 @@ 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
+ export function herdrTuiPlacement(pane) {
184
+ // Herdr overlays belong to the active pane; --target-pane is split-only. The
185
+ // model often finishes after Mingjian has moved on, so never steal focus then.
186
+ return pane.focused
187
+ ? ["--placement", "overlay", "--focus"]
188
+ : ["--placement", "split", "--target-pane", pane.pane_id, "--direction", "right", "--no-focus"]
189
+ }
188
190
 
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
- }
191
+ async function openHerdrTui({ bin, pane }, directory) {
192
+ try {
193
+ const { stdout } = await execute(bin, [
194
+ "plugin", "pane", "open", "--plugin", "annotate", "--entrypoint", "agy",
195
+ ...herdrTuiPlacement(pane),
196
+ "--cwd", directory, "--env", `ANNOTATE_AGY_REVIEW_DIR=${directory}`,
197
+ ], { timeout: 5000 })
198
+ const opened = JSON.parse(stdout).result?.plugin_pane?.pane
199
+ if (!opened?.pane_id) throw new Error("Herdr did not return the opened pane ID.")
200
+ if (opened.tab_id !== pane.tab_id) {
201
+ await execute(bin, ["pane", "close", opened.pane_id], { timeout: 2000 })
202
+ throw new Error("Herdr placed the overlay outside the AGY tab. Focus the AGY tab and try again.")
213
203
  }
214
- return
204
+ if (!pane.focused) {
205
+ await herdrCommand(bin, ["notification", "show", "Annotate", "--body", "Review opened beside the AGY pane."]).catch(() => {})
206
+ }
207
+ return opened.pane_id
208
+ } catch (err) {
209
+ throw new Error(`Failed to open the Herdr review overlay. Check that the annotate plugin has the agy pane entrypoint.\n${err.message}`)
210
+ }
211
+ }
212
+
213
+ function runReviewer({ binary, snapshotFile, env }, directory) {
214
+ const child = spawn(binary, [snapshotFile], {
215
+ cwd: directory,
216
+ env: { ...process.env, ...env },
217
+ stdio: "inherit",
218
+ })
219
+ return new Promise((resolve, reject) => {
220
+ child.on("exit", (code, signal) => {
221
+ if (code === 0) resolve()
222
+ else reject(new Error(`Reviewer exited with ${signal || code}.`))
223
+ })
224
+ child.on("error", reject)
225
+ })
226
+ }
227
+
228
+ async function runTuiPane(directory) {
229
+ if (!directory || !path.isAbsolute(directory)) throw new Error("Missing AGY review directory.")
230
+ let result = "closed"
231
+ try {
232
+ const request = JSON.parse(await readFile(path.join(directory, "request.json"), "utf8"))
233
+ if (request.sourcePane && focusedPane(process.env) !== request.sourcePane) {
234
+ throw new Error("Herdr focus changed before the popup opened. Open Annotate again from the AGY pane.")
235
+ }
236
+ await runReviewer(request, directory)
237
+ } catch (err) {
238
+ result = err.message
239
+ }
240
+ await writeFile(path.join(directory, "done.tmp"), result, { mode: 0o600 })
241
+ await rename(path.join(directory, "done.tmp"), path.join(directory, "done"))
242
+ }
243
+
244
+ async function readOptional(file) {
245
+ return readFile(file, "utf8").catch(err => {
246
+ if (err.code !== "ENOENT") throw err
247
+ return null
248
+ })
249
+ }
250
+
251
+ async function waitForTuiPane(directory, herdrPane) {
252
+ const deadline = Date.now() + 300_000
253
+ while (Date.now() < deadline) {
254
+ const result = await readOptional(path.join(directory, "done"))
255
+ if (result === "closed") return true
256
+ if (result !== null) throw new Error(result)
257
+ if (herdrPane) {
258
+ const { bin, id } = herdrPane
259
+ const missing = await execute(bin, ["pane", "get", id], { timeout: 2000 }).then(() => false, err => {
260
+ try { return JSON.parse(err.stderr).error?.code === "pane_not_found" } catch { return false }
261
+ })
262
+ if (missing && await readOptional(path.join(directory, "done")) === null) return false
263
+ }
264
+ await wait(500)
265
+ }
266
+ throw new Error("Timed out waiting for Annotate.")
267
+ }
268
+
269
+ // The hook is the only feedback channel. Neither the pane nor the waiting tool
270
+ // returns the Markdown, and no other pending batch can finish this review.
271
+ export async function finishTuiReview({ intentPath, conversationId, header, exportFeedback, enqueue = enqueueAnnotations, deliver }) {
272
+ if (await readOptional(intentPath) !== "send\n") return "Review closed without sending annotations."
273
+ const feedback = (await exportFeedback()).trim()
274
+ if (!feedback || feedback === "No annotations.") return "No annotations to send."
275
+ const batch = {
276
+ batchID: `tui-${randomUUID()}`,
277
+ markdown: `${header}\n\n${feedback}`,
278
+ promptID: `msg_${randomUUID()}`,
279
+ }
280
+ if (deliver) return deliver(batch)
281
+ await enqueue(conversationId, batch)
282
+ return "Annotations queued for this AGY conversation. The lifecycle hook will deliver them."
283
+ }
284
+
285
+ async function cmdTui(targetPath, options) {
286
+ const session = await resolveSession(options.session || process.env.ANTIGRAVITY_CONVERSATION_ID)
287
+ const binary = path.resolve(resolveTuiBinary(options.binary))
288
+ const opener = await selectTuiOpener({ env: process.env, tty: process.stdin.isTTY })
289
+ await reviewTui(targetPath, { session, binary, opener })
290
+ }
291
+
292
+ async function cmdHerdrReview(options, shortcut) {
293
+ const bin = process.env.HERDR_BIN_PATH || "herdr"
294
+ const binary = path.resolve(resolveTuiBinary(options.binary))
295
+ try {
296
+ const pane = shortcut?.pane ?? focusedPane(process.env)
297
+ const agent = await readHerdrAgent(bin, pane)
298
+ if (!shortcut && ["claude", "codex", "pi", "opencode"].includes(agent.agent)) {
299
+ const { stdout } = await execute(binary, ["herdr", "last", "--newest", "--deliver-to", pane], { timeout: 5000 })
300
+ console.log(stdout.trim())
301
+ return
302
+ }
303
+ if (agent.agent !== "agy") throw new Error("This action supports AGY, Claude, Codex, Pi, and OpenCode panes.")
304
+ const captured = { ...await captureHerdrConversation(bin, pane, agent), bin, pane, terminalId: agent.terminal_id }
305
+ if (shortcut && (!agent.focused || captured.conversationId !== shortcut.conversationId)) {
306
+ throw new Error("The AGY pane or conversation changed before Annotate opened.")
307
+ }
308
+ const session = { conversationId: captured.conversationId, title: `AGY ${captured.conversationId.slice(0, 8)}` }
309
+ const status = await reviewTui(shortcut?.document, { session, binary, opener: { kind: "popup" }, captured })
310
+ await recordHerdrOutcome(captured.conversationId, status)
311
+ if (status) await herdrCommand(bin, ["notification", "show", "Annotate", "--body", status]).catch(() => {})
312
+ } catch (err) {
313
+ await recordHerdrOutcome(shortcut?.conversationId, `error: ${err.message}`)
314
+ await herdrCommand(bin, ["notification", "show", "Annotate", "--body", err.message]).catch(() => {})
315
+ throw err
215
316
  }
317
+ }
216
318
 
319
+ async function reviewTui(targetPath, { session, binary, opener, captured }) {
217
320
  let sourceText = ""
218
321
  let snapshotName = "last-reply.md"
219
322
  let filePath = null
220
323
  let sourceHash = null
221
324
 
222
325
  if (targetPath) {
223
- const resolvedPath = path.resolve(session.directory, targetPath)
326
+ const resolvedPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(session.directory, targetPath)
224
327
  sourceText = await readFile(resolvedPath, "utf8")
225
328
  filePath = resolvedPath
226
329
  snapshotName = path.basename(resolvedPath)
227
330
  sourceHash = createHash("sha256").update(Buffer.from(sourceText)).digest("hex")
228
331
  } else {
229
- const replies = await extractAgyReplies(brainDir)
230
- const latest = latestCompletedReply(replies)
332
+ const [latest] = await extractAgyReplies(defaultBrainDir(session.conversationId), { latestOnly: true })
231
333
  if (!latest || !latest.text.trim()) {
232
334
  throw new Error(`No completed assistant replies found in session "${session.title}".`)
233
335
  }
@@ -243,67 +345,82 @@ async function cmdTui(targetPath, options) {
243
345
  await mkdir(dataDir, { recursive: true, mode: 0o700 })
244
346
  await writeFile(snapshotFile, sourceText, { mode: 0o600 })
245
347
 
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
348
  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
- }
349
+ let textSource
350
+ let complete = false
262
351
 
263
352
  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
353
+ // Keep ASCII active before the first usable frame. Run the switch alongside
354
+ // theme setup, but wait for it even if the theme fails so it can be restored.
355
+ const [themedResult] = await Promise.allSettled([
356
+ prepareTheme({ binary, theme: getAdaptedThemeTokens(), directory: tempDir, env: process.env }),
357
+ inputSource.ascii().then(previous => { textSource = previous }),
358
+ ])
359
+ if (themedResult.status === "rejected") throw themedResult.reason
360
+ const themed = themedResult.value
361
+ const env = {
362
+ PLANNOTATOR_DATA_DIR: dataDir,
363
+ PLANNOTATOR_FEEDBACK_HISTORY: "0",
364
+ PLANNOTATOR_TUI_SEND_INTENT: intentPath,
290
365
  }
366
+ if (themed.PLANNOTATOR_TUI_CONFIG) env.PLANNOTATOR_TUI_CONFIG = themed.PLANNOTATOR_TUI_CONFIG
291
367
 
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}`
368
+ if (inputSource.command && textSource) {
369
+ env.PLANNOTATOR_TUI_INPUT_SOURCE = inputSource.command
370
+ env.PLANNOTATOR_TUI_TEXT_INPUT_SOURCE = textSource
371
+ }
372
+ const request = { binary, snapshotFile, env, sourcePane: captured?.pane }
373
+ if (opener.kind === "tty") {
374
+ await runReviewer(request, tempDir)
375
+ } else {
376
+ await writeFile(path.join(tempDir, "request.json"), JSON.stringify(request), { mode: 0o600 })
377
+ let herdrPane
378
+ if (captured) {
379
+ const { bin } = captured
380
+ const popupEnv = {
381
+ ...env,
382
+ PLANNOTATOR_TUI_FILE: snapshotFile,
383
+ ANNOTATE_AGY_REVIEW_DIR: tempDir,
384
+ ANNOTATE_AGY_SOURCE_PANE: captured.pane,
385
+ }
386
+ const result = await herdrCommand(bin, [
387
+ "plugin", "pane", "open", "--plugin", process.env.HERDR_PLUGIN_ID || "annotate",
388
+ "--entrypoint", "agy-popup", "--cwd", tempDir,
389
+ ...Object.entries(popupEnv).flatMap(([key, value]) => ["--env", `${key}=${value}`]),
390
+ ])
391
+ if (result?.type !== "ok") throw new Error("The agy-popup entrypoint must declare placement = \"popup\".")
392
+ } else if (opener.kind === "herdr") herdrPane = { bin: opener.bin, id: await openHerdrTui(opener, tempDir) }
393
+ else await openTuiWindow(tempDir, session.title)
394
+ console.log(`Opened Annotate ${opener.kind === "herdr" ? "overlay" : opener.kind}. Waiting for Send or quit…`)
395
+ if (!await waitForTuiPane(tempDir, herdrPane)) {
396
+ console.log(`Review pane closed without sending. Review files retained at ${tempDir}`)
397
+ return
398
+ }
399
+ }
296
400
 
297
- await enqueueAnnotations(session.conversationId, {
298
- batchID: `tui-${Date.now()}`,
299
- markdown: combined,
300
- promptID: `msg_${randomUUID()}`,
401
+ const status = await finishTuiReview({
402
+ intentPath,
403
+ conversationId: session.conversationId,
404
+ deliver: captured && (batch => deliverHerdrReview(captured, batch)),
405
+ header: filePath
406
+ ? `Annotations on document \`${filePath}\` (SHA-256: ${sourceHash}):`
407
+ : `Annotations on latest assistant response in session "${session.title}":`,
408
+ exportFeedback: async () => {
409
+ const { stdout } = await execute(binary, ["--export", snapshotFile], {
410
+ cwd: tempDir, env: { ...process.env, ...env }, timeout: 15000,
411
+ })
412
+ await writeFile(path.join(tempDir, "feedback.md"), stdout, { mode: 0o600 })
413
+ return stdout
414
+ },
301
415
  })
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.`)
416
+ complete = true
417
+ console.log(status)
418
+ return status
419
+ } catch (err) {
420
+ throw new Error(`${err.message} Review files retained at ${tempDir}`, { cause: err })
305
421
  } finally {
306
- await rm(tempDir, { recursive: true, force: true })
422
+ await inputSource.select(textSource)
423
+ if (complete) await rm(tempDir, { recursive: true, force: true })
307
424
  }
308
425
  }
309
426
 
@@ -315,6 +432,17 @@ async function main() {
315
432
  }
316
433
 
317
434
  const command = args[0]
435
+ if (command === "tui-pane") {
436
+ await runTuiPane(args[1] || process.env.ANNOTATE_AGY_REVIEW_DIR)
437
+ return
438
+ }
439
+ if (command === "herdr-slash") {
440
+ const [, pane, conversationId, binary, document] = args
441
+ if (process.env.HERDR_ENV !== "1" || !pane || pane !== process.env.HERDR_PANE_ID ||
442
+ !conversationId || (document && !path.isAbsolute(document))) throw new Error("Invalid AGY slash launch.")
443
+ await cmdHerdrReview({ binary: binary || undefined }, { pane, conversationId, document })
444
+ return
445
+ }
318
446
  const options = {}
319
447
  let posArg = null
320
448
 
@@ -323,8 +451,6 @@ async function main() {
323
451
  options.session = args[++i]
324
452
  } else if (args[i] === "--binary") {
325
453
  options.binary = args[++i]
326
- } else if (args[i] === "--interactive-tty") {
327
- options.interactiveTty = true
328
454
  } else if (args[i] === "--browser") {
329
455
  options.browser = args[++i]
330
456
  } else if (!args[i].startsWith("-") && !posArg) {
@@ -342,6 +468,9 @@ async function main() {
342
468
  case "tui":
343
469
  await cmdTui(posArg, options)
344
470
  break
471
+ case "herdr-review":
472
+ await cmdHerdrReview(options)
473
+ break
345
474
  case "queue":
346
475
  await cmdQueue(options)
347
476
  break
package/agy/cli.test.mjs CHANGED
@@ -2,11 +2,66 @@ 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, herdrTuiPlacement, 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("a focused AGY pane gets an overlay; an unfocused one gets a split without stealing focus", () => {
29
+ assert.deepEqual(herdrTuiPlacement({ pane_id: "w5:p2", focused: true }), ["--placement", "overlay", "--focus"])
30
+ assert.deepEqual(herdrTuiPlacement({ pane_id: "w5:p2", focused: false }),
31
+ ["--placement", "split", "--target-pane", "w5:p2", "--direction", "right", "--no-focus"])
32
+ })
33
+
34
+ test("only exact Send intent may export or enqueue; only one target hook gets the notes", async t => {
35
+ const root = await mkdtemp(path.join(os.tmpdir(), "agy-finish-test-"))
36
+ t.after(() => rm(root, { recursive: true, force: true }))
37
+ const intentPath = path.join(root, "intent")
38
+ const inboxRoot = path.join(root, "inbox")
39
+ const conversationId = "captured"
40
+ const note = "Private review content"
41
+ let exports = 0
42
+ const finish = () => finishTuiReview({
43
+ intentPath, conversationId, header: "Review header",
44
+ exportFeedback: async () => { exports++; return note },
45
+ enqueue: (id, batch) => enqueueAnnotations(id, batch, inboxRoot),
46
+ })
47
+ assert.match(await finish(), /without sending/)
48
+ await writeFile(intentPath, "cancel\n")
49
+ assert.match(await finish(), /without sending/)
50
+ assert.equal(exports, 0)
51
+ await writeFile(intentPath, "send\n")
52
+ const status = await finish()
53
+ assert.match(status, /queued/)
54
+ assert.ok(!status.includes(note))
55
+ assert.equal(exports, 1)
56
+ assert.deepEqual(await handleStop({ conversationId: "unrelated" }, { inboxRoot }), {})
57
+ const outcomes = await Promise.all([
58
+ handleStop({ conversationId }, { inboxRoot }),
59
+ handlePreInvocation({ conversationId }, { inboxRoot }),
60
+ ])
61
+ assert.equal(JSON.stringify(outcomes).split(note).length - 1, 1)
62
+ assert.deepEqual(await handleStop({ conversationId }, { inboxRoot }), {})
63
+ })
64
+
10
65
  test("both adapters resolve the packaged reviewer or an explicit custom binary", () => {
11
66
  const custom = "/custom/bin/annotate-tui"
12
67
  assert.equal(resolveTuiBinary(custom), custom)