@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/agy/herdr.mjs ADDED
@@ -0,0 +1,103 @@
1
+ import { execFile } from "node:child_process"
2
+ import { promisify } from "node:util"
3
+ import { getActiveAgySessions } from "./session.mjs"
4
+ import { enqueueAnnotations } from "./inbox.mjs"
5
+
6
+ const execute = promisify(execFile)
7
+ const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i
8
+
9
+ export function focusedPane(env) {
10
+ if (env.HERDR_ENV !== "1") throw new Error("Run Annotate from a Herdr plugin action.")
11
+ const context = JSON.parse(env.HERDR_PLUGIN_CONTEXT_JSON || "{}")
12
+ if (!context.focused_pane_id) throw new Error("Focus an agent pane before opening Annotate.")
13
+ return context.focused_pane_id
14
+ }
15
+
16
+ export async function herdrCommand(bin, args, timeout = 5000) {
17
+ const { stdout } = await execute(bin, args, { timeout })
18
+ return JSON.parse(stdout).result
19
+ }
20
+
21
+ export async function readHerdrAgent(bin, pane, timeout) {
22
+ const agent = (await herdrCommand(bin, ["agent", "get", pane], timeout)).agent
23
+ if (!agent?.terminal_id) throw new Error("Herdr did not identify the focused agent terminal.")
24
+ return agent
25
+ }
26
+
27
+ async function promptHerdrAgent(bin, pane, markdown) {
28
+ try {
29
+ await herdrCommand(bin, ["agent", "prompt", pane, markdown])
30
+ } catch (err) {
31
+ let code
32
+ try { code = JSON.parse(err.stderr).error?.code } catch {}
33
+ if (code === "agent_blocked") throw new Error("AGY is blocked and needs input. Nothing was sent.")
34
+ if (code === "pane_not_found" || code === "agent_not_found" || code === "agent_not_ready") {
35
+ throw new Error("The AGY pane is no longer ready. Nothing was sent.")
36
+ }
37
+ throw new Error("Herdr did not confirm submission. Check the AGY conversation before retrying.")
38
+ }
39
+ }
40
+
41
+ export function resolveHerdrConversation(agent, processes = [], sessions = []) {
42
+ const ref = agent.agent_session
43
+ if (ref) {
44
+ const id = ref.kind === "id" ? ref.value
45
+ : ref.kind === "path" ? /(?:^|[/\\])brain[/\\]([^/\\]+)[/\\]\.system_generated[/\\]logs[/\\]transcript(?:_full)?\.jsonl$/.exec(ref.value)?.[1]
46
+ : undefined
47
+ if (!uuid.test(id ?? "")) throw new Error("Herdr did not report a valid AGY conversation ID.")
48
+ return { conversationId: id, reported: true }
49
+ }
50
+ // A cwd can be shared by multiple AGY panes. Match the live presence lock
51
+ // to the foreground AGY process instead of picking a directory match.
52
+ const pids = new Set(processes.map(p => p.pid))
53
+ const matches = sessions.filter(session => pids.has(session.pid))
54
+ if (matches.length !== 1 || !uuid.test(matches[0].conversationId)) {
55
+ throw new Error("Cannot identify one AGY conversation in this pane. Enable Herdr's Antigravity CLI session integration.")
56
+ }
57
+ return { conversationId: matches[0].conversationId, reported: false, pid: matches[0].pid }
58
+ }
59
+
60
+ export async function captureHerdrConversation(bin, pane, agent) {
61
+ if (agent.agent_session) return resolveHerdrConversation(agent)
62
+ const { process_info } = await herdrCommand(bin, ["pane", "process-info", "--pane", pane])
63
+ return resolveHerdrConversation(agent, process_info.foreground_processes, getActiveAgySessions())
64
+ }
65
+
66
+ export function herdrDeliveryRoute(captured, agent, current) {
67
+ if (agent.agent !== "agy" || agent.terminal_id !== captured.terminalId ||
68
+ current.conversationId !== captured.conversationId ||
69
+ (captured.reported && !current.reported) ||
70
+ (!captured.reported && !current.reported && captured.pid !== current.pid)) {
71
+ throw new Error("The pane no longer matches the captured AGY conversation. Nothing was sent.")
72
+ }
73
+ switch (agent.agent_status) {
74
+ case "idle":
75
+ case "done":
76
+ return "prompt"
77
+ case "working":
78
+ return "inbox"
79
+ case "blocked":
80
+ throw new Error("AGY is blocked and needs input. Nothing was sent.")
81
+ default:
82
+ throw new Error("AGY is not ready to receive feedback: Herdr could not determine its state. Nothing was sent.")
83
+ }
84
+ }
85
+
86
+ export async function deliverHerdrReview(captured, batch, {
87
+ getAgent = readHerdrAgent, getConversation = captureHerdrConversation,
88
+ prompt = promptHerdrAgent,
89
+ enqueue = enqueueAnnotations,
90
+ } = {}) {
91
+ const { bin, pane, conversationId } = captured
92
+ const agent = await getAgent(bin, pane)
93
+ if (agent.agent !== "agy") throw new Error("The pane no longer contains AGY. Nothing was sent.")
94
+ const current = await getConversation(bin, pane, agent)
95
+ if (herdrDeliveryRoute(captured, agent, current) === "inbox") {
96
+ await enqueue(conversationId, batch)
97
+ return "Annotations queued for the captured AGY conversation."
98
+ }
99
+ // Herdr blocks a prompt if the pane needs input. Never retry or enqueue
100
+ // after an attempted prompt: a transport error may have followed admission.
101
+ await prompt(bin, pane, batch.markdown)
102
+ return "Annotations submitted to AGY."
103
+ }
@@ -0,0 +1,54 @@
1
+ import { test } from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import { deliverHerdrReview, focusedPane, resolveHerdrConversation } from "./herdr.mjs"
4
+
5
+ const id = "605c8a34-bd80-4007-9164-345de6a351bd"
6
+ const other = "650229ca-30db-4a36-bb7c-b226a482c677"
7
+ const reference = { kind: "id", value: id }
8
+
9
+ test("action targets the focused pane from context, not the plugin process", () => {
10
+ const env = { HERDR_ENV: "1", HERDR_PANE_ID: "w1:p9", HERDR_PLUGIN_CONTEXT_JSON: '{"focused_pane_id":"w1:p2"}' }
11
+ assert.equal(focusedPane(env), "w1:p2")
12
+ assert.throws(() => focusedPane({ ...env, HERDR_PLUGIN_CONTEXT_JSON: "{}" }), /Focus an agent pane/)
13
+ })
14
+
15
+ test("conversation routing prefers Herdr identity and refuses ambiguous foreground locks", () => {
16
+ const exact = resolveHerdrConversation({ agent_session: reference })
17
+ assert.deepEqual(exact, { conversationId: id, reported: true })
18
+ const path = `/home/.gemini/antigravity-cli/brain/${id}/.system_generated/logs/transcript.jsonl`
19
+ assert.deepEqual(resolveHerdrConversation({ agent_session: { kind: "path", value: path } }), exact)
20
+ assert.throws(() => resolveHerdrConversation({ agent_session: { kind: "id", value: "../unsafe" } }), /valid AGY/)
21
+ const processes = [{ pid: 14 }]
22
+ const session = { pid: 14, conversationId: id }
23
+ assert.deepEqual(resolveHerdrConversation({}, processes, [session, { pid: 15, conversationId: other }]),
24
+ { conversationId: id, reported: false, pid: 14 })
25
+ for (const sessions of [[], [session, { ...session, conversationId: other }]]) {
26
+ assert.throws(() => resolveHerdrConversation({}, processes, sessions), /Cannot identify one/)
27
+ }
28
+ })
29
+
30
+ test("delivery chooses exactly one route and refuses an unavailable or changed destination", async () => {
31
+ const captured = { bin: "herdr", pane: "w1:p2", terminalId: "term-a", conversationId: id, reported: true }
32
+ const batch = { markdown: "Feedback" }
33
+ const calls = []
34
+ const send = (agent_status, overrides = {}, promptError) => deliverHerdrReview(captured, batch, {
35
+ getAgent: async () => ({ agent: "agy", agent_status, terminal_id: "term-a", agent_session: reference, ...overrides }),
36
+ getConversation: async (_bin, _pane, agent) => resolveHerdrConversation(agent),
37
+ prompt: async (...args) => { calls.push(["prompt", ...args]); if (promptError) throw promptError },
38
+ enqueue: async (...args) => { calls.push(["inbox", ...args]) },
39
+ })
40
+ for (const status of ["idle", "done"]) {
41
+ assert.match(await send(status), /submitted/)
42
+ assert.deepEqual(calls.splice(0), [["prompt", "herdr", "w1:p2", "Feedback"]])
43
+ }
44
+ assert.match(await send("working"), /queued/)
45
+ assert.deepEqual(calls.splice(0), [["inbox", id, batch]])
46
+ await assert.rejects(send("blocked"), /blocked/)
47
+ await assert.rejects(send("unknown"), /not ready/)
48
+ await assert.rejects(send("working", { terminal_id: "term-b" }), /no longer matches/)
49
+ await assert.rejects(send("idle", { agent_session: { ...reference, value: other } }), /no longer matches/)
50
+ await assert.rejects(send("idle", { agent: "shell" }), /no longer contains AGY/)
51
+ assert.deepEqual(calls, [])
52
+ await assert.rejects(send("idle", {}, new Error("timeout")), /timeout/)
53
+ assert.deepEqual(calls, [["prompt", "herdr", "w1:p2", "Feedback"]])
54
+ })
package/agy/hooks.mjs CHANGED
@@ -3,6 +3,7 @@ import { fileURLToPath } from "node:url"
3
3
  import path from "node:path"
4
4
  import { dequeueAnnotations, defaultInboxRoot } from "./inbox.mjs"
5
5
  import { listTargets, registryRoot } from "../bridge/receiver.mjs"
6
+ import { annotateSlash, interceptAnnotateSlash } from "./slash.mjs"
6
7
 
7
8
  const __dirname = path.dirname(fileURLToPath(import.meta.url))
8
9
 
@@ -43,9 +44,10 @@ export async function handleSessionStart(payload, { root = registryRoot(), inbox
43
44
  return {}
44
45
  }
45
46
 
46
- export async function handlePreInvocation(payload, { inboxRoot = defaultInboxRoot() } = {}) {
47
+ export async function handlePreInvocation(payload, { inboxRoot = defaultInboxRoot(), intercept = interceptAnnotateSlash } = {}) {
47
48
  const conversationId = payload.conversationId
48
49
  if (!conversationId) return {}
50
+ if (await intercept(payload, { inboxRoot })) return { terminationBehavior: "terminate" }
49
51
 
50
52
  const dequeued = await dequeueAnnotations(conversationId, inboxRoot)
51
53
  if (!dequeued || !dequeued.combinedMarkdown.trim()) {
@@ -61,9 +63,14 @@ export async function handlePreInvocation(payload, { inboxRoot = defaultInboxRoo
61
63
  }
62
64
  }
63
65
 
64
- export async function handleStop(payload, { inboxRoot = defaultInboxRoot() } = {}) {
66
+ export async function handleStop(payload, { inboxRoot = defaultInboxRoot(), env = process.env } = {}) {
65
67
  const conversationId = payload.conversationId
66
68
  if (!conversationId) return {}
69
+ // Draining here would restart the model immediately after slash interception.
70
+ if (env.HERDR_ENV === "1" && env.HERDR_PANE_ID && payload.terminationReason === "TERMINAL_CUSTOM_HOOK" &&
71
+ annotateSlash(payload.lastUserInput) !== undefined) {
72
+ return {}
73
+ }
67
74
 
68
75
  const dequeued = await dequeueAnnotations(conversationId, inboxRoot)
69
76
  if (!dequeued || !dequeued.combinedMarkdown.trim()) {
package/agy/inbox.mjs CHANGED
@@ -1,4 +1,5 @@
1
- import { mkdir, readdir, readFile, rm, writeFile, chmod } from "node:fs/promises"
1
+ import { mkdir, readdir, readFile, rename, rm, writeFile, chmod } from "node:fs/promises"
2
+ import { randomUUID } from "node:crypto"
2
3
  import path from "node:path"
3
4
  import os from "node:os"
4
5
 
@@ -20,7 +21,13 @@ export async function enqueueAnnotations(conversationId, payload, inboxRoot = de
20
21
  review: payload.review,
21
22
  }
22
23
 
23
- await writeFile(file, JSON.stringify(record, null, 2), { mode: 0o600 })
24
+ const draft = path.join(sessionInbox, `.${randomUUID()}.tmp`)
25
+ try {
26
+ await writeFile(draft, JSON.stringify(record, null, 2), { mode: 0o600 })
27
+ await rename(draft, file)
28
+ } finally {
29
+ await rm(draft, { force: true })
30
+ }
24
31
  return { file, batchID }
25
32
  }
26
33
 
@@ -55,18 +62,25 @@ export async function dequeueAnnotations(conversationId, inboxRoot = defaultInbo
55
62
  const batchIDs = []
56
63
 
57
64
  for (const batch of batches) {
58
- if (batch.markdown) markdowns.push(batch.markdown)
59
- batchIDs.push(batch.batchID)
65
+ const claim = `${batch.filePath}.${randomUUID()}.claim`
60
66
  try {
61
- await rm(batch.filePath, { force: true })
62
- } catch {
63
- // Ignore cleanup error
67
+ // Read from the claimed path, never the listing: concurrent hooks
68
+ // cannot both read the moved batch from their unique claim paths.
69
+ await rename(batch.filePath, claim)
70
+ const claimed = JSON.parse(await readFile(claim, "utf8"))
71
+ if (claimed.markdown) markdowns.push(claimed.markdown)
72
+ batchIDs.push(claimed.batchID)
73
+ } catch (err) {
74
+ if (err.code !== "ENOENT") throw err
75
+ } finally {
76
+ await rm(claim, { force: true })
64
77
  }
65
78
  }
66
79
 
80
+ if (!batchIDs.length) return null
67
81
  return {
68
82
  batchIDs,
69
83
  combinedMarkdown: markdowns.join("\n\n---\n\n"),
70
- count: batches.length,
84
+ count: batchIDs.length,
71
85
  }
72
86
  }
package/agy/session.mjs CHANGED
@@ -1,9 +1,7 @@
1
1
  import { spawnSync } from "node:child_process"
2
- import { DatabaseSync } from "node:sqlite"
3
2
  import { fileURLToPath } from "node:url"
4
3
  import path from "node:path"
5
4
  import os from "node:os"
6
- import { getAgySessionTitle } from "./receiver.mjs"
7
5
 
8
6
  export const agyConfigDir = () => path.join(os.homedir(), ".gemini/antigravity-cli")
9
7
 
@@ -31,6 +29,7 @@ export function getActiveAgySessions(baseDir = agyConfigDir()) {
31
29
 
32
30
  let db
33
31
  try {
32
+ const { DatabaseSync } = process.getBuiltinModule("node:sqlite")
34
33
  db = new DatabaseSync(dbPath, { open: true, readOnly: true })
35
34
  } catch {
36
35
  // Database might be temporarily locked or not exist
@@ -7,24 +7,28 @@ description: Review assistant replies or local documents in the bundled Annotate
7
7
 
8
8
  Use this skill when the user runs `/annotate` or asks to annotate assistant responses, documents, or webpages.
9
9
 
10
- ## Execution Guide for the Agent:
10
+ In a configured Herdr AGY pane, `/annotate` and `/annotate <local-document>` can be handled directly by the PreInvocation hook before the model runs. The Herdr shortcut `prefix+a` opens the latest reply the same way. These direct actions do not need the skill.
11
+
12
+ ## Execution Guide for the Agent
13
+
14
+ If the request reaches this skill, run the matching command immediately. Use `agy-annotate` from the same installation as the AGY hooks. For a linked skill with no `agy-annotate` on PATH, run `node` with the absolute `agy/cli.mjs` path from that installation (`cli.mjs` is two directories above the linked skill's real directory).
11
15
 
12
16
  ### 1. When the user types `/annotate` (or asks to review the last reply):
13
17
  Run the command:
14
18
  ```bash
15
- npx --yes --package @nxxxsooo/opencode-annotate@latest agy-annotate tui
19
+ agy-annotate tui
16
20
  ```
17
- This opens the bundled reviewer in an interactive window (via Ghostty or Terminal). When the user finishes adding annotations and presses `q` (or `Ctrl+S`), the window closes, the command outputs the feedback, and you proceed to apply the requested changes.
21
+ This opens the bundled reviewer in the configured Herdr overlay or in Ghostty/Terminal outside Herdr. Keep the command running until the user finishes. Only **Send** (`Ctrl+S` or the Send button) delivers feedback to the captured conversation; `q` and `Ctrl+C` close without sending. The command returns status only. Wait for delivered annotations before acting on them.
18
22
 
19
23
  ### 2. When the user specifies a document (e.g., `/annotate path/to/doc.md`):
20
24
  Run the command:
21
25
  ```bash
22
- npx --yes --package @nxxxsooo/opencode-annotate@latest agy-annotate tui "<path/to/doc.md>"
26
+ agy-annotate tui "<path/to/doc.md>"
23
27
  ```
24
28
 
25
29
  ### 3. When the user provides a URL/HTML file (e.g., `/annotate page.html`) or asks for webpage review:
26
30
  Run the command:
27
31
  ```bash
28
- npx --yes --package @nxxxsooo/opencode-annotate@latest agy-annotate web [url-or-html-path]
32
+ agy-annotate web [url-or-html-path]
29
33
  ```
30
34
  Inform the user that the session is paired with Chrome and ready in the Annotate side panel (`Alt+Shift+A`). When the user sends notes from Chrome, they are delivered directly to this session.
package/agy/slash.mjs ADDED
@@ -0,0 +1,90 @@
1
+ import { spawn } from "node:child_process"
2
+ import { mkdir, rm, stat } from "node:fs/promises"
3
+ import path from "node:path"
4
+ import { fileURLToPath } from "node:url"
5
+ import { herdrCommand, readHerdrAgent, resolveHerdrConversation } from "./herdr.mjs"
6
+ import { defaultInboxRoot } from "./inbox.mjs"
7
+
8
+ export function annotateSlash(text) {
9
+ if (typeof text !== "string" || /[\r\n\0]/.test(text)) return undefined
10
+ const match = /^\/annotate(?:[ \t]+(.+))?$/.exec(text.trim())
11
+ if (!match) return undefined
12
+ let argument = match[1]
13
+ if (!argument) return null
14
+ const quote = argument[0]
15
+ if (quote === '"' || quote === "'") {
16
+ if (argument.length < 3 || !argument.endsWith(quote)) return undefined
17
+ argument = argument.slice(1, -1)
18
+ }
19
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(argument) || /\.html?$/i.test(argument)) return undefined
20
+ return argument
21
+ }
22
+
23
+ function start({ pane, conversationId, document, binary, env }) {
24
+ const cli = fileURLToPath(new URL("./cli.mjs", import.meta.url))
25
+ const args = [cli, "herdr-slash", pane, conversationId, binary ?? ""]
26
+ if (document) args.push(document)
27
+ const child = spawn(process.execPath, args, { detached: true, stdio: "ignore", env })
28
+ return new Promise(resolve => {
29
+ child.once("error", () => resolve(false))
30
+ child.once("spawn", () => { child.unref(); resolve(true) })
31
+ })
32
+ }
33
+
34
+ async function claimTurn(inboxRoot, conversationId, count) {
35
+ const inbox = path.join(inboxRoot, conversationId)
36
+ await mkdir(inbox, { recursive: true, mode: 0o700 })
37
+ // AGY can replay invocation zero after a custom termination. The step
38
+ // count stays fixed on replay and advances on a newly submitted command.
39
+ const claim = path.join(inbox, `.slash-${count}`)
40
+ try {
41
+ await mkdir(claim, { mode: 0o700 })
42
+ return () => rm(claim, { force: true, recursive: true })
43
+ } catch (err) {
44
+ if (err.code !== "EEXIST") throw err
45
+ return null
46
+ }
47
+ }
48
+
49
+ export async function interceptAnnotateSlash(payload, {
50
+ env = process.env, readAgent = readHerdrAgent, command = herdrCommand, launch = start,
51
+ inboxRoot = defaultInboxRoot(),
52
+ } = {}) {
53
+ const argument = annotateSlash(payload.lastUserInput)
54
+ const { HERDR_ENV, HERDR_PANE_ID: pane, HERDR_SOCKET_PATH: socket, HERDR_BIN_PATH: bin = "herdr" } = env
55
+ if (argument === undefined || payload.invocationNum !== 0 || !Number.isSafeInteger(payload.initialNumSteps) ||
56
+ payload.initialNumSteps < 1 || !payload.conversationId ||
57
+ HERDR_ENV !== "1" || !pane || !socket) return false
58
+
59
+ try {
60
+ const [agent, pluginList] = await Promise.all([
61
+ readAgent(bin, pane, 200),
62
+ command(bin, ["plugin", "list", "--json"], 200),
63
+ ])
64
+ if (agent.agent !== "agy" || !agent.focused || !agent.agent_session ||
65
+ resolveHerdrConversation(agent).conversationId !== payload.conversationId) return false
66
+ const plugin = pluginList?.plugins?.find(plugin => plugin.plugin_id === "annotate" && plugin.enabled)
67
+ const popup = plugin?.panes?.find(pane => pane.id === "agy-popup" && pane.placement === "popup")
68
+ if (!popup) return false
69
+ const [executable, namespace, entrypoint] = popup.command ?? []
70
+ const binary = namespace === "herdr" && entrypoint === "hosted-pane" && path.isAbsolute(executable)
71
+ ? executable : undefined
72
+ let document
73
+ if (argument !== null) {
74
+ if (!path.isAbsolute(payload.cwd ?? "")) return false
75
+ document = path.resolve(payload.cwd, argument)
76
+ if (!(await stat(document)).isFile()) return false
77
+ }
78
+ const release = await claimTurn(inboxRoot, payload.conversationId, payload.initialNumSteps)
79
+ if (!release) return true
80
+ let launched = false
81
+ try {
82
+ launched = await launch({ pane, conversationId: payload.conversationId, document, binary, env })
83
+ return launched
84
+ } finally {
85
+ if (!launched) await release()
86
+ }
87
+ } catch {
88
+ return false
89
+ }
90
+ }
@@ -0,0 +1,62 @@
1
+ import { test } from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import { fileURLToPath } from "node:url"
4
+ import { mkdtemp, rm } from "node:fs/promises"
5
+ import path from "node:path"
6
+ import os from "node:os"
7
+ import { annotateSlash, interceptAnnotateSlash } from "./slash.mjs"
8
+ import { handlePreInvocation, handleStop } from "./hooks.mjs"
9
+ import { enqueueAnnotations } from "./inbox.mjs"
10
+
11
+ const conversationId = "605c8a34-bd80-4007-9164-345de6a351bd"
12
+ const pane = "w1:p1"
13
+ const env = { HERDR_ENV: "1", HERDR_PANE_ID: pane, HERDR_SOCKET_PATH: "/fixture/socket" }
14
+ const plugin = { plugin_id: "annotate", enabled: true, panes: [{ id: "agy-popup", placement: "popup" }] }
15
+ const agent = { agent: "agy", focused: true, agent_session: { kind: "id", value: conversationId } }
16
+ const payload = { conversationId, invocationNum: 0, initialNumSteps: 1, lastUserInput: "/annotate" }
17
+
18
+ test("recognizes standalone text and local document commands, not web or mixed input", () => {
19
+ assert.equal(annotateSlash("/annotate"), null)
20
+ assert.equal(annotateSlash('/annotate "file name.md"'), "file name.md")
21
+ for (const text of ["look at /annotate", "/annotated", "/annotate\nthen run it", "/annotate https://example.com", "/annotate note.html", '/annotate "unterminated']) {
22
+ assert.equal(annotateSlash(text), undefined)
23
+ }
24
+ })
25
+
26
+ test("only terminates the initial invocation after handing off the verified pane and conversation", async t => {
27
+ const inboxRoot = await mkdtemp(path.join(os.tmpdir(), "annotate-slash-test-"))
28
+ t.after(() => rm(inboxRoot, { force: true, recursive: true }))
29
+ const calls = []
30
+ const options = { env, inboxRoot, readAgent: async () => agent, command: async () => ({ plugins: [plugin] }),
31
+ launch: async captured => { calls.push(captured); return true } }
32
+ const intercept = p => interceptAnnotateSlash(p, options)
33
+ assert.deepEqual(await handlePreInvocation(payload, { intercept }), { terminationBehavior: "terminate" })
34
+ assert.deepEqual(calls.shift(), { pane, conversationId, document: undefined, binary: undefined, env })
35
+ assert.equal(await intercept(payload), true)
36
+ assert.deepEqual(calls, [], "a repeated hook must not open the same turn again")
37
+ const cwd = fileURLToPath(new URL("../", import.meta.url))
38
+ assert.equal(await intercept({ ...payload, initialNumSteps: 2, cwd, lastUserInput: '/annotate "README.md"' }), true)
39
+ assert.equal(calls.shift().document, fileURLToPath(new URL("../README.md", import.meta.url)))
40
+ assert.equal(await intercept({ ...payload, invocationNum: 1 }), false)
41
+ assert.equal(await intercept({ ...payload, cwd, lastUserInput: "/annotate missing.md" }), false)
42
+ assert.equal(await interceptAnnotateSlash(payload, { ...options, env: {} }), false)
43
+ assert.equal(await interceptAnnotateSlash(payload, { ...options, readAgent: async () => ({ ...agent, focused: false }) }), false)
44
+ assert.equal(await interceptAnnotateSlash({ ...payload, conversationId: "different" }, options), false)
45
+ assert.equal(await interceptAnnotateSlash(payload, { ...options, command: async () => ({ plugins: [] }) }), false)
46
+ assert.deepEqual(calls, [])
47
+ const failed = { ...payload, initialNumSteps: 3 }
48
+ assert.equal(await interceptAnnotateSlash(failed, { ...options, launch: async () => false }), false)
49
+ assert.equal(await intercept(failed), true, "failed spawn releases the claim")
50
+ })
51
+
52
+ test("a terminated local slash turn does not restart the model or consume queued notes", async t => {
53
+ const inboxRoot = await mkdtemp(path.join(os.tmpdir(), "annotate-slash-test-"))
54
+ t.after(() => rm(inboxRoot, { force: true, recursive: true }))
55
+ const note = "Previously queued note"
56
+ await enqueueAnnotations(conversationId, { batchID: "kept-note", markdown: note }, inboxRoot)
57
+ const intercepted = { ...payload, terminationReason: "TERMINAL_CUSTOM_HOOK" }
58
+ assert.deepEqual(await handleStop(intercepted, { env, inboxRoot }), {})
59
+ const next = await handlePreInvocation({ ...payload, lastUserInput: "Continue" }, { env, inboxRoot })
60
+ assert.match(next.injectSteps[0].userMessage, /Previously queued note/)
61
+ assert.deepEqual(await handleStop({ conversationId }, { env, inboxRoot }), {})
62
+ })
@@ -35,7 +35,7 @@ export async function readFullStep(brainDir, stepIndex) {
35
35
  return null
36
36
  }
37
37
 
38
- export async function extractAgyReplies(brainDir, { signal } = {}) {
38
+ export async function extractAgyReplies(brainDir, { signal, latestOnly = false } = {}) {
39
39
  const logPath = path.join(brainDir, ".system_generated/logs/transcript.jsonl")
40
40
  let text
41
41
  try {
@@ -54,6 +54,8 @@ export async function extractAgyReplies(brainDir, { signal } = {}) {
54
54
  if (!step) continue
55
55
  if (step.source !== "MODEL" || step.type !== "PLANNER_RESPONSE" || step.status !== "DONE") continue
56
56
 
57
+ const hasToolCalls = Array.isArray(step.tool_calls) && step.tool_calls.length > 0
58
+ if (latestOnly && hasToolCalls) continue
57
59
  let content = step.content || ""
58
60
  if (step.truncated_fields && step.truncated_fields.includes("content")) {
59
61
  const full = await readFullStep(brainDir, step.step_index)
@@ -61,8 +63,8 @@ export async function extractAgyReplies(brainDir, { signal } = {}) {
61
63
  }
62
64
 
63
65
  const cleaned = cleanModelContent(content)
64
- const hasToolCalls = Array.isArray(step.tool_calls) && step.tool_calls.length > 0
65
66
  if (!cleaned && hasToolCalls) continue
67
+ if (latestOnly && !cleaned) continue
66
68
 
67
69
  replies.push({
68
70
  id: String(step.step_index),
@@ -71,6 +73,7 @@ export async function extractAgyReplies(brainDir, { signal } = {}) {
71
73
  created: Date.parse(step.created_at) || Date.now(),
72
74
  toolCalls: step.tool_calls?.map(t => t.name) || [],
73
75
  })
76
+ if (latestOnly) break
74
77
  }
75
78
 
76
79
  return replies
@@ -68,6 +68,7 @@ test("extractAgyReplies extracts completed and in-progress replies, handling tru
68
68
  const latest = latestCompletedReply(replies)
69
69
  assert.ok(latest)
70
70
  assert.equal(latest.id, "2")
71
+ assert.deepEqual(await extractAgyReplies(root, { latestOnly: true }), [latest])
71
72
  })
72
73
 
73
74
  test("extractAgyReplies returns empty array when transcript does not exist", async () => {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "OpenCode Annotate",
4
- "version": "0.18.0",
4
+ "version": "0.20.0",
5
5
  "description": "Annotate HTML-based page feedback, private drafts, and paired OpenCode delivery.",
6
6
  "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp7TG2yzekNKpQvHBtj4jqkOxtoeDIBhNIjPi37Os/ksuhzPp1pHnrJPV4WV2ToatUaD5x5/SpLP8qZKLBD+wuraEE/TeclEZ8HvEs1yhlnx/S7piTG/s0eV5umuTEx2w66Hi0w3dhTC7ZZfJXCLyqs1feBtWzQx6ClgaHNYly4iJ03pV7RfguqpIaG9LV8Oa8ELA+7Ubr0BAujXrSlvqLF5oAKGoXXcpvTL5rgMRIH4Q/85tnvrk0pRVg+1z9IGNzSfjN82iveC/JAriyWABp8YuswtvKfI2Wb+KspaisBh39Y3BRqlyo8I2Cr+01uE6G5pWiJIWMLhe0glrMr5I2wIDAQAB",
7
7
  "permissions": ["activeTab", "scripting", "storage", "sidePanel", "nativeMessaging", "clipboardWrite"],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nxxxsooo/opencode-annotate",
3
- "version": "0.18.0",
3
+ "version": "0.20.0",
4
4
  "description": "Unofficial OpenCode annotation plugin: review AI replies and Markdown with a bundled terminal reviewer; annotate webpages with the browser companion.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/review.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawn, execFile } from "node:child_process"
2
2
  import { createHash, randomUUID } from "node:crypto"
3
- import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"
3
+ import { mkdtemp, mkdir, readFile, readdir, realpath, rm, stat, writeFile } from "node:fs/promises"
4
4
  import os from "node:os"
5
5
  import path from "node:path"
6
6
  import { promisify } from "node:util"
@@ -12,23 +12,61 @@ import { createInputSource } from "./input-source.mjs"
12
12
  import { resolveTuiBinary } from "./tui/binary.mjs"
13
13
 
14
14
  const execute = promisify(execFile)
15
- const documentExtensions = new Set([".md", ".mdx", ".markdown", ".txt"])
15
+ const markdownExtensions = new Set(["md", "mdx", "markdown"])
16
+ const documentLanguages = new Set([
17
+ "txt", "rst", "adoc", "org", "tex", "csv", "tsv", "log",
18
+ "json", "jsonc", "json5", "yaml", "yml", "toml", "ini", "cfg", "conf", "properties", "xml", "plist",
19
+ ])
20
+ const documentNames = new Map([
21
+ [".editorconfig", "ini"], [".gitignore", "text"], [".gitattributes", "text"],
22
+ [".dockerignore", "text"], ["dockerfile", "dockerfile"], ["makefile", "makefile"],
23
+ ])
24
+ const languageAliases = { txt: "text", log: "text", yml: "yaml", plist: "xml" }
16
25
  const maxDocumentBytes = 2 * 1024 * 1024
17
26
 
27
+ function documentLanguage(file) {
28
+ const name = path.basename(file).toLowerCase()
29
+ if (name.startsWith(".env") ||
30
+ /(?:^|[._-])(?:credentials?|secrets?|passwords?|private[._-]?keys?|id_(?:rsa|dsa|ecdsa|ed25519)|pem|key|p12|pfx|ppk)(?:[._-]|$)/.test(name)) return
31
+ const extension = path.extname(name).slice(1)
32
+ if (markdownExtensions.has(extension)) return "markdown"
33
+ if (documentLanguages.has(extension)) return languageAliases[extension] ?? extension
34
+ return documentNames.get(name)
35
+ }
36
+
37
+ async function sessionDirectory(client, sessionID, signal) {
38
+ const session = await client.session.get({ sessionID }, { signal })
39
+ const directory = session.location?.directory
40
+ if (!directory) throw new Error("Can't determine the current session's working directory.")
41
+ return directory
42
+ }
43
+
44
+ function documentSnapshot(text, language) {
45
+ if (language === "markdown") return text
46
+ // Let the Markdown reviewer display the source literally, even if it contains fences.
47
+ let length = 3
48
+ for (const run of text.matchAll(/`{3,}/g)) length = Math.max(length, run[0].length + 1)
49
+ const fence = "`".repeat(length)
50
+ return `${fence}${language}\n${text}${text.endsWith("\n") ? "" : "\n"}${fence}\n`
51
+ }
52
+
53
+ function withinDirectory(directory, file) {
54
+ const relative = path.relative(directory, file)
55
+ return relative && !path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`)
56
+ }
57
+
18
58
  async function documentSource(input, client, sessionID, signal) {
19
59
  let target = input.trim()
20
60
  if ((target.startsWith('"') && target.endsWith('"')) || (target.startsWith("'") && target.endsWith("'"))) {
21
61
  target = target.slice(1, -1)
22
62
  }
23
- if (!target || !documentExtensions.has(path.extname(target).toLowerCase())) {
24
- throw new Error("Choose a Markdown or plain-text file (.md, .mdx, .markdown, .txt).")
25
- }
63
+ const language = documentLanguage(target)
64
+ if (!language) throw new Error("Choose a supported text or config file. Credential files are excluded.")
26
65
  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(target)) throw new Error("Use a local file path.")
27
66
  if (target.startsWith("~/")) target = path.join(os.homedir(), target.slice(2))
28
- const session = await client.session.get({ sessionID }, { signal })
29
- const directory = session.location?.directory
30
- if (!path.isAbsolute(target) && !directory) throw new Error("Can't determine the current session's working directory.")
31
- const filePath = path.isAbsolute(target) ? path.normalize(target) : path.resolve(directory, target)
67
+ const filePath = path.isAbsolute(target)
68
+ ? path.normalize(target)
69
+ : path.resolve(await sessionDirectory(client, sessionID, signal), target)
32
70
  try {
33
71
  const info = await stat(filePath)
34
72
  if (!info.isFile()) throw new Error("The target is not a file.")
@@ -43,7 +81,7 @@ async function documentSource(input, client, sessionID, signal) {
43
81
  throw new Error("Use a UTF-8 text file.")
44
82
  }
45
83
  return {
46
- text, filePath,
84
+ text: documentSnapshot(text, language), filePath,
47
85
  sourceHash: createHash("sha256").update(bytes).digest("hex"),
48
86
  snapshot: path.join("source", path.basename(filePath)),
49
87
  }
@@ -373,6 +411,32 @@ export function createReviewCommand(context, options = {}) {
373
411
  return texts.find(text => text.id === chosen)
374
412
  })
375
413
 
414
+ const file = (query = "") => start(async ({ sessionID, signal }) => {
415
+ const directory = await sessionDirectory(context.client, sessionID, signal)
416
+ const { location, data } = await context.client.file.find(
417
+ { query: query.trim(), type: "file", limit: 200, location: { directory } }, { signal },
418
+ )
419
+ if (signal.aborted) return
420
+ const options = data.flatMap(entry => {
421
+ if (entry.type !== "file" || path.isAbsolute(entry.path) || !documentLanguage(entry.path)) return []
422
+ const value = path.resolve(location.directory, entry.path)
423
+ if (!withinDirectory(directory, value)) return []
424
+ return [{ title: entry.path, value, description: path.dirname(entry.path) }]
425
+ })
426
+ if (!options.length) {
427
+ notice("No eligible text or config files found in this session's directory.")
428
+ return
429
+ }
430
+ const chosen = await context.ui.dialog.select({ title: "Annotate file", options })
431
+ if (chosen === undefined || signal.aborted) return
432
+ // The search result is a relative name, but a symlink can still leave the tree.
433
+ const [root, resolved] = await Promise.all([realpath(directory), realpath(chosen)])
434
+ if (!withinDirectory(root, resolved) || !documentLanguage(resolved)) {
435
+ throw new Error("Choose a supported text or config file inside this session's directory.")
436
+ }
437
+ return documentSource(chosen, context.client, sessionID, signal)
438
+ })
439
+
376
440
  const annotateSelection = () => start(async ({ sessionID, signal }) => {
377
441
  const selected = selection?.sessionID === sessionID ? selection.text : ""
378
442
  const needle = compact(selected)
@@ -385,7 +449,7 @@ export function createReviewCommand(context, options = {}) {
385
449
  })
386
450
 
387
451
  return {
388
- run, auto, pick, selection: annotateSelection, webReady: web.ready,
452
+ run, auto, pick, file, selection: annotateSelection, webReady: web.ready,
389
453
  dispose() {
390
454
  context.renderer.off("selection", remember)
391
455
  disposed = true