@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 +19 -0
- package/README.md +28 -4
- package/agy/cli.mjs +253 -124
- package/agy/cli.test.mjs +57 -2
- package/agy/herdr.mjs +115 -0
- package/agy/herdr.test.mjs +54 -0
- package/agy/hooks.mjs +20 -2
- package/agy/inbox.mjs +22 -8
- package/agy/session.mjs +1 -2
- package/agy/skills/annotate/SKILL.md +9 -5
- package/agy/slash.mjs +101 -0
- package/agy/slash.test.mjs +72 -0
- package/agy/transcript.mjs +5 -2
- package/agy/transcript.test.mjs +1 -0
- package/browser/manifest.json +1 -1
- package/package.json +1 -1
- package/tui/README.md +58 -5
- package/tui/bin/darwin-arm64/annotate-tui +0 -0
- package/tui/bin/darwin-x64/annotate-tui +0 -0
- package/tui/bin/linux-arm64/annotate-tui +0 -0
- package/tui/bin/linux-x64/annotate-tui +0 -0
- package/tui/bin/win32-x64/annotate-tui.exe +0 -0
package/agy/herdr.mjs
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { execFile } from "node:child_process"
|
|
2
|
+
import { appendFile, mkdir } from "node:fs/promises"
|
|
3
|
+
import os from "node:os"
|
|
4
|
+
import path from "node:path"
|
|
5
|
+
import { promisify } from "node:util"
|
|
6
|
+
import { getActiveAgySessions } from "./session.mjs"
|
|
7
|
+
import { enqueueAnnotations } from "./inbox.mjs"
|
|
8
|
+
|
|
9
|
+
const execute = promisify(execFile)
|
|
10
|
+
const uuid = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i
|
|
11
|
+
|
|
12
|
+
export function focusedPane(env) {
|
|
13
|
+
if (env.HERDR_ENV !== "1") throw new Error("Run Annotate from a Herdr plugin action.")
|
|
14
|
+
const context = JSON.parse(env.HERDR_PLUGIN_CONTEXT_JSON || "{}")
|
|
15
|
+
if (!context.focused_pane_id) throw new Error("Focus an agent pane before opening Annotate.")
|
|
16
|
+
return context.focused_pane_id
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Herdr notifications vanish; keep each popup outcome and declined slash
|
|
20
|
+
// interception so a lost review can be traced afterwards.
|
|
21
|
+
export async function recordHerdrOutcome(conversationId, status) {
|
|
22
|
+
const log = path.join(os.homedir(), ".local/share/opencode-annotate/agy-review.log")
|
|
23
|
+
const line = `${new Date().toISOString()}\t${conversationId ?? "-"}\t${String(status).replace(/\s+/g, " ")}\n`
|
|
24
|
+
await mkdir(path.dirname(log), { recursive: true, mode: 0o700 })
|
|
25
|
+
.then(() => appendFile(log, line, { mode: 0o600 })).catch(() => {})
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function herdrCommand(bin, args, timeout = 5000) {
|
|
29
|
+
const { stdout } = await execute(bin, args, { timeout })
|
|
30
|
+
return JSON.parse(stdout).result
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function readHerdrAgent(bin, pane, timeout) {
|
|
34
|
+
const agent = (await herdrCommand(bin, ["agent", "get", pane], timeout)).agent
|
|
35
|
+
if (!agent?.terminal_id) throw new Error("Herdr did not identify the focused agent terminal.")
|
|
36
|
+
return agent
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
async function promptHerdrAgent(bin, pane, markdown) {
|
|
40
|
+
try {
|
|
41
|
+
await herdrCommand(bin, ["agent", "prompt", pane, markdown])
|
|
42
|
+
} catch (err) {
|
|
43
|
+
let code
|
|
44
|
+
try { code = JSON.parse(err.stderr).error?.code } catch {}
|
|
45
|
+
if (code === "agent_blocked") throw new Error("AGY is blocked and needs input. Nothing was sent.")
|
|
46
|
+
if (code === "pane_not_found" || code === "agent_not_found" || code === "agent_not_ready") {
|
|
47
|
+
throw new Error("The AGY pane is no longer ready. Nothing was sent.")
|
|
48
|
+
}
|
|
49
|
+
throw new Error("Herdr did not confirm submission. Check the AGY conversation before retrying.")
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function resolveHerdrConversation(agent, processes = [], sessions = []) {
|
|
54
|
+
const ref = agent.agent_session
|
|
55
|
+
if (ref) {
|
|
56
|
+
const id = ref.kind === "id" ? ref.value
|
|
57
|
+
: ref.kind === "path" ? /(?:^|[/\\])brain[/\\]([^/\\]+)[/\\]\.system_generated[/\\]logs[/\\]transcript(?:_full)?\.jsonl$/.exec(ref.value)?.[1]
|
|
58
|
+
: undefined
|
|
59
|
+
if (!uuid.test(id ?? "")) throw new Error("Herdr did not report a valid AGY conversation ID.")
|
|
60
|
+
return { conversationId: id, reported: true }
|
|
61
|
+
}
|
|
62
|
+
// A cwd can be shared by multiple AGY panes. Match the live presence lock
|
|
63
|
+
// to the foreground AGY process instead of picking a directory match.
|
|
64
|
+
const pids = new Set(processes.map(p => p.pid))
|
|
65
|
+
const matches = sessions.filter(session => pids.has(session.pid))
|
|
66
|
+
if (matches.length !== 1 || !uuid.test(matches[0].conversationId)) {
|
|
67
|
+
throw new Error("Cannot identify one AGY conversation in this pane. Enable Herdr's Antigravity CLI session integration.")
|
|
68
|
+
}
|
|
69
|
+
return { conversationId: matches[0].conversationId, reported: false, pid: matches[0].pid }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function captureHerdrConversation(bin, pane, agent) {
|
|
73
|
+
if (agent.agent_session) return resolveHerdrConversation(agent)
|
|
74
|
+
const { process_info } = await herdrCommand(bin, ["pane", "process-info", "--pane", pane])
|
|
75
|
+
return resolveHerdrConversation(agent, process_info.foreground_processes, getActiveAgySessions())
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function herdrDeliveryRoute(captured, agent, current) {
|
|
79
|
+
if (agent.agent !== "agy" || agent.terminal_id !== captured.terminalId ||
|
|
80
|
+
current.conversationId !== captured.conversationId ||
|
|
81
|
+
(captured.reported && !current.reported) ||
|
|
82
|
+
(!captured.reported && !current.reported && captured.pid !== current.pid)) {
|
|
83
|
+
throw new Error("The pane no longer matches the captured AGY conversation. Nothing was sent.")
|
|
84
|
+
}
|
|
85
|
+
switch (agent.agent_status) {
|
|
86
|
+
case "idle":
|
|
87
|
+
case "done":
|
|
88
|
+
return "prompt"
|
|
89
|
+
case "working":
|
|
90
|
+
return "inbox"
|
|
91
|
+
case "blocked":
|
|
92
|
+
throw new Error("AGY is blocked and needs input. Nothing was sent.")
|
|
93
|
+
default:
|
|
94
|
+
throw new Error("AGY is not ready to receive feedback: Herdr could not determine its state. Nothing was sent.")
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function deliverHerdrReview(captured, batch, {
|
|
99
|
+
getAgent = readHerdrAgent, getConversation = captureHerdrConversation,
|
|
100
|
+
prompt = promptHerdrAgent,
|
|
101
|
+
enqueue = enqueueAnnotations,
|
|
102
|
+
} = {}) {
|
|
103
|
+
const { bin, pane, conversationId } = captured
|
|
104
|
+
const agent = await getAgent(bin, pane)
|
|
105
|
+
if (agent.agent !== "agy") throw new Error("The pane no longer contains AGY. Nothing was sent.")
|
|
106
|
+
const current = await getConversation(bin, pane, agent)
|
|
107
|
+
if (herdrDeliveryRoute(captured, agent, current) === "inbox") {
|
|
108
|
+
await enqueue(conversationId, batch)
|
|
109
|
+
return "Annotations queued for the captured AGY conversation."
|
|
110
|
+
}
|
|
111
|
+
// Herdr blocks a prompt if the pane needs input. Never retry or enqueue
|
|
112
|
+
// after an attempted prompt: a transport error may have followed admission.
|
|
113
|
+
await prompt(bin, pane, batch.markdown)
|
|
114
|
+
return "Annotations submitted to AGY."
|
|
115
|
+
}
|
|
@@ -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,21 @@ export async function handleSessionStart(payload, { root = registryRoot(), inbox
|
|
|
43
44
|
return {}
|
|
44
45
|
}
|
|
45
46
|
|
|
46
|
-
|
|
47
|
+
const openedStep = {
|
|
48
|
+
systemMessage: {
|
|
49
|
+
systemMessage: "",
|
|
50
|
+
metadata: { user_markdown: "Annotate opened. `q` sends notes; `Ctrl+C` discards them." },
|
|
51
|
+
},
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function handlePreInvocation(payload, { inboxRoot = defaultInboxRoot(), intercept = interceptAnnotateSlash } = {}) {
|
|
47
55
|
const conversationId = payload.conversationId
|
|
48
56
|
if (!conversationId) return {}
|
|
57
|
+
const intercepted = await intercept(payload, { inboxRoot })
|
|
58
|
+
// AGY's prompt ignores an idle update that adds no step after the user's
|
|
59
|
+
// input and keeps spinning, so the first termination shows one UI-only step.
|
|
60
|
+
if (intercepted === "opened") return { injectSteps: [openedStep], terminationBehavior: "terminate" }
|
|
61
|
+
if (intercepted) return { terminationBehavior: "terminate" }
|
|
49
62
|
|
|
50
63
|
const dequeued = await dequeueAnnotations(conversationId, inboxRoot)
|
|
51
64
|
if (!dequeued || !dequeued.combinedMarkdown.trim()) {
|
|
@@ -61,9 +74,14 @@ export async function handlePreInvocation(payload, { inboxRoot = defaultInboxRoo
|
|
|
61
74
|
}
|
|
62
75
|
}
|
|
63
76
|
|
|
64
|
-
export async function handleStop(payload, { inboxRoot = defaultInboxRoot() } = {}) {
|
|
77
|
+
export async function handleStop(payload, { inboxRoot = defaultInboxRoot(), env = process.env } = {}) {
|
|
65
78
|
const conversationId = payload.conversationId
|
|
66
79
|
if (!conversationId) return {}
|
|
80
|
+
// Draining here would restart the model immediately after slash interception.
|
|
81
|
+
if (env.HERDR_ENV === "1" && env.HERDR_PANE_ID && payload.terminationReason === "TERMINAL_CUSTOM_HOOK" &&
|
|
82
|
+
annotateSlash(payload.lastUserInput) !== undefined) {
|
|
83
|
+
return {}
|
|
84
|
+
}
|
|
67
85
|
|
|
68
86
|
const dequeued = await dequeueAnnotations(conversationId, inboxRoot)
|
|
69
87
|
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
|
-
|
|
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
|
-
|
|
59
|
-
batchIDs.push(batch.batchID)
|
|
65
|
+
const claim = `${batch.filePath}.${randomUUID()}.claim`
|
|
60
66
|
try {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
19
|
+
agy-annotate tui
|
|
16
20
|
```
|
|
17
|
-
This opens the bundled reviewer in
|
|
21
|
+
This opens the bundled reviewer in Herdr or in Ghostty/Terminal outside Herdr. Keep the command running until the user finishes. **Send** (`Ctrl+S` or the Send button) delivers feedback to the captured conversation. `q` sends pending notes and closes; with no notes it just closes. `Ctrl+C` closes 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
|
-
|
|
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
|
-
|
|
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,101 @@
|
|
|
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, recordHerdrOutcome, 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(), record = recordHerdrOutcome,
|
|
52
|
+
} = {}) {
|
|
53
|
+
const argument = annotateSlash(payload.lastUserInput)
|
|
54
|
+
if (argument === undefined) return false
|
|
55
|
+
const decline = async reason => {
|
|
56
|
+
await record(payload.conversationId, `slash not intercepted: ${reason}`)
|
|
57
|
+
return false
|
|
58
|
+
}
|
|
59
|
+
const { HERDR_ENV, HERDR_PANE_ID: pane, HERDR_SOCKET_PATH: socket, HERDR_BIN_PATH: bin = "herdr" } = env
|
|
60
|
+
if (payload.invocationNum !== 0 || !Number.isSafeInteger(payload.initialNumSteps) ||
|
|
61
|
+
payload.initialNumSteps < 1 || !payload.conversationId) {
|
|
62
|
+
return decline(`payload invocationNum=${payload.invocationNum} initialNumSteps=${payload.initialNumSteps}`)
|
|
63
|
+
}
|
|
64
|
+
if (HERDR_ENV !== "1" || !pane || !socket) return decline("not in a Herdr pane")
|
|
65
|
+
|
|
66
|
+
try {
|
|
67
|
+
const [agent, pluginList] = await Promise.all([
|
|
68
|
+
readAgent(bin, pane, 200),
|
|
69
|
+
command(bin, ["plugin", "list", "--json"], 200),
|
|
70
|
+
])
|
|
71
|
+
if (agent.agent !== "agy") return decline(`pane agent is ${agent.agent}`)
|
|
72
|
+
if (!agent.focused) return decline("AGY pane not focused")
|
|
73
|
+
if (!agent.agent_session) return decline("Herdr reports no AGY session")
|
|
74
|
+
if (resolveHerdrConversation(agent).conversationId !== payload.conversationId) {
|
|
75
|
+
return decline("Herdr session does not match the conversation")
|
|
76
|
+
}
|
|
77
|
+
const plugin = pluginList?.plugins?.find(plugin => plugin.plugin_id === "annotate" && plugin.enabled)
|
|
78
|
+
const popup = plugin?.panes?.find(pane => pane.id === "agy-popup" && pane.placement === "popup")
|
|
79
|
+
if (!popup) return decline("annotate plugin has no agy-popup entrypoint")
|
|
80
|
+
const [executable, namespace, entrypoint] = popup.command ?? []
|
|
81
|
+
const binary = namespace === "herdr" && entrypoint === "hosted-pane" && path.isAbsolute(executable)
|
|
82
|
+
? executable : undefined
|
|
83
|
+
let document
|
|
84
|
+
if (argument !== null) {
|
|
85
|
+
if (!path.isAbsolute(payload.cwd ?? "")) return decline("relative cwd")
|
|
86
|
+
document = path.resolve(payload.cwd, argument)
|
|
87
|
+
if (!(await stat(document)).isFile()) return decline("document is not a file")
|
|
88
|
+
}
|
|
89
|
+
const release = await claimTurn(inboxRoot, payload.conversationId, payload.initialNumSteps)
|
|
90
|
+
if (!release) return "replayed"
|
|
91
|
+
let launched = false
|
|
92
|
+
try {
|
|
93
|
+
launched = await launch({ pane, conversationId: payload.conversationId, document, binary, env })
|
|
94
|
+
return launched ? "opened" : decline("popup launcher failed to start")
|
|
95
|
+
} finally {
|
|
96
|
+
if (!launched) await release()
|
|
97
|
+
}
|
|
98
|
+
} catch (err) {
|
|
99
|
+
return decline(err.message)
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
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 declined = []
|
|
31
|
+
const options = { env, inboxRoot, readAgent: async () => agent, command: async () => ({ plugins: [plugin] }),
|
|
32
|
+
launch: async captured => { calls.push(captured); return true },
|
|
33
|
+
record: async (_, reason) => { declined.push(reason) } }
|
|
34
|
+
const intercept = p => interceptAnnotateSlash(p, options)
|
|
35
|
+
const opened = await handlePreInvocation(payload, { intercept })
|
|
36
|
+
assert.equal(opened.terminationBehavior, "terminate")
|
|
37
|
+
assert.equal(opened.injectSteps.length, 1, "AGY needs a step after the input to leave Working…")
|
|
38
|
+
assert.equal(opened.injectSteps[0].systemMessage.systemMessage, "", "the model never reads the UI step")
|
|
39
|
+
assert.match(opened.injectSteps[0].systemMessage.metadata.user_markdown, /Annotate opened/)
|
|
40
|
+
assert.deepEqual(calls.shift(), { pane, conversationId, document: undefined, binary: undefined, env })
|
|
41
|
+
assert.equal(await intercept(payload), "replayed")
|
|
42
|
+
assert.deepEqual(await handlePreInvocation(payload, { intercept }), { terminationBehavior: "terminate" },
|
|
43
|
+
"a replayed invocation adds no second UI step")
|
|
44
|
+
assert.deepEqual(calls, [], "a repeated hook must not open the same turn again")
|
|
45
|
+
const cwd = fileURLToPath(new URL("../", import.meta.url))
|
|
46
|
+
assert.equal(await intercept({ ...payload, initialNumSteps: 2, cwd, lastUserInput: '/annotate "README.md"' }), "opened")
|
|
47
|
+
assert.equal(calls.shift().document, fileURLToPath(new URL("../README.md", import.meta.url)))
|
|
48
|
+
assert.equal(await intercept({ ...payload, invocationNum: 1 }), false)
|
|
49
|
+
assert.equal(await intercept({ ...payload, cwd, lastUserInput: "/annotate missing.md" }), false)
|
|
50
|
+
assert.equal(await interceptAnnotateSlash(payload, { ...options, env: {} }), false)
|
|
51
|
+
assert.equal(await interceptAnnotateSlash(payload, { ...options, readAgent: async () => ({ ...agent, focused: false }) }), false)
|
|
52
|
+
assert.equal(await interceptAnnotateSlash({ ...payload, conversationId: "different" }, options), false)
|
|
53
|
+
assert.equal(await interceptAnnotateSlash(payload, { ...options, command: async () => ({ plugins: [] }) }), false)
|
|
54
|
+
assert.deepEqual(calls, [])
|
|
55
|
+
assert.ok(declined.includes("slash not intercepted: AGY pane not focused"), "a declined slash records why")
|
|
56
|
+
assert.equal(declined.length, 6)
|
|
57
|
+
const failed = { ...payload, initialNumSteps: 3 }
|
|
58
|
+
assert.equal(await interceptAnnotateSlash(failed, { ...options, launch: async () => false }), false)
|
|
59
|
+
assert.equal(await intercept(failed), "opened", "failed spawn releases the claim")
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
test("a terminated local slash turn does not restart the model or consume queued notes", async t => {
|
|
63
|
+
const inboxRoot = await mkdtemp(path.join(os.tmpdir(), "annotate-slash-test-"))
|
|
64
|
+
t.after(() => rm(inboxRoot, { force: true, recursive: true }))
|
|
65
|
+
const note = "Previously queued note"
|
|
66
|
+
await enqueueAnnotations(conversationId, { batchID: "kept-note", markdown: note }, inboxRoot)
|
|
67
|
+
const intercepted = { ...payload, terminationReason: "TERMINAL_CUSTOM_HOOK" }
|
|
68
|
+
assert.deepEqual(await handleStop(intercepted, { env, inboxRoot }), {})
|
|
69
|
+
const next = await handlePreInvocation({ ...payload, lastUserInput: "Continue" }, { env, inboxRoot })
|
|
70
|
+
assert.match(next.injectSteps[0].userMessage, /Previously queued note/)
|
|
71
|
+
assert.deepEqual(await handleStop({ conversationId }, { env, inboxRoot }), {})
|
|
72
|
+
})
|
package/agy/transcript.mjs
CHANGED
|
@@ -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
|
package/agy/transcript.test.mjs
CHANGED
|
@@ -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 () => {
|
package/browser/manifest.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"manifest_version": 3,
|
|
3
3
|
"name": "OpenCode Annotate",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.20.1",
|
|
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.
|
|
3
|
+
"version": "0.20.1",
|
|
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/tui/README.md
CHANGED
|
@@ -73,19 +73,69 @@ id = "doc"
|
|
|
73
73
|
title = "Annotate"
|
|
74
74
|
placement = "overlay"
|
|
75
75
|
command = ["/absolute/path/to/annotate-tui", "herdr", "pane"]
|
|
76
|
+
|
|
77
|
+
# Optional: AGY overlay. Use absolute paths from the same Annotate installation.
|
|
78
|
+
[[panes]]
|
|
79
|
+
id = "agy"
|
|
80
|
+
title = "Annotate AGY"
|
|
81
|
+
placement = "overlay"
|
|
82
|
+
command = ["/absolute/path/to/agy-annotate", "tui-pane"]
|
|
83
|
+
|
|
84
|
+
[[panes]]
|
|
85
|
+
id = "agy-popup"
|
|
86
|
+
title = "Annotate AGY"
|
|
87
|
+
placement = "popup"
|
|
88
|
+
width = "90%"
|
|
89
|
+
height = "90%"
|
|
90
|
+
command = ["/absolute/path/to/annotate-tui", "herdr", "hosted-pane"]
|
|
91
|
+
|
|
92
|
+
[[actions]]
|
|
93
|
+
id = "review"
|
|
94
|
+
title = "Annotate latest reply"
|
|
95
|
+
contexts = ["pane"]
|
|
96
|
+
command = ["/absolute/path/to/agy-annotate", "herdr-review", "--binary", "/absolute/path/to/annotate-tui"]
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
For a built macOS checkout, use its executable `agy/cli.mjs` and the
|
|
100
|
+
native `tui/bin/darwin-arm64/annotate-tui` (or `darwin-x64` on Intel).
|
|
101
|
+
|
|
102
|
+
Add this to Herdr's `config.toml` and reload the server configuration:
|
|
103
|
+
|
|
104
|
+
```toml
|
|
105
|
+
[[keys.command]]
|
|
106
|
+
key = "prefix+a"
|
|
107
|
+
type = "plugin_action"
|
|
108
|
+
command = "annotate.review"
|
|
109
|
+
description = "Annotate latest reply"
|
|
76
110
|
```
|
|
77
111
|
|
|
112
|
+
Press your prefix (default `Ctrl+B`) then `a` in the agent pane. The AGY action
|
|
113
|
+
opens a 90% × 90% modal using the pane manifest's `popup` placement. Herdr 0.9.5
|
|
114
|
+
does not accept `popup` as a `--placement` CLI override. Send rechecks the AGY
|
|
115
|
+
conversation before starting a turn in an idle/done pane or queuing to the AGY
|
|
116
|
+
hooks while Herdr reports it is working. A blocked, unknown, or changed
|
|
117
|
+
destination keeps the notes and shows the recovery path. With matching AGY
|
|
118
|
+
hooks, `/annotate` and `/annotate <local-document>` also open this popup before
|
|
119
|
+
the model runs. See the [AGY setup](../README.md#antigravity-agy-support) for
|
|
120
|
+
`SessionStart`, `PreInvocation`, and `Stop`. If the pane or conversation
|
|
121
|
+
cannot be verified, the skill handles the command instead.
|
|
122
|
+
|
|
78
123
|
`herdr pane` is the plugin entrypoint: it reads the file, reply or terminal source
|
|
79
124
|
passed by the launcher. Set `--placement overlay|split|tab|zoomed` on `herdr open`,
|
|
80
|
-
`herdr last` or `herdr terminal`; the default is `overlay`.
|
|
81
|
-
`
|
|
82
|
-
|
|
125
|
+
`herdr last` or `herdr terminal`; the default is `overlay`. If your Annotate
|
|
126
|
+
`tui.toml` uses `popup_width` or `popup_height`, remove those settings and
|
|
127
|
+
replace its `placement = "popup"` with a supported value. This does not
|
|
128
|
+
affect `placement = "popup"` in the Herdr plugin manifest above.
|
|
129
|
+
Agent delivery uses `herdr agent prompt`; a blocked send
|
|
83
130
|
leaves notes pending for a manual retry and attempts an OSC 52 clipboard copy.
|
|
84
131
|
OpenCode's `/annotate` clears the inherited `HERDR_*` variables before launching
|
|
85
132
|
the reviewer, so it does not use this route.
|
|
86
133
|
|
|
87
|
-
|
|
88
|
-
|
|
134
|
+
For AGY, the `agy-popup` pane runs `herdr hosted-pane` on a private Markdown
|
|
135
|
+
snapshot. The `agy` pane runs `agy-annotate tui-pane` for the skill fallback.
|
|
136
|
+
Keep the AGY pane focused while the popup opens. `q` sends pending notes and
|
|
137
|
+
closes; with no notes it just closes. `Ctrl+C` closes without sending.
|
|
138
|
+
|
|
89
139
|
|
|
90
140
|
## Local image-toolbar trial
|
|
91
141
|
|
|
@@ -113,6 +163,9 @@ multiplexer settings. Unknown transports still require your own verification. Di
|
|
|
113
163
|
removing all three `toolbar_image*` keys if your terminal cannot display it. Restart after
|
|
114
164
|
changing font/cell pixel size. A configured cell-size override takes precedence and skips
|
|
115
165
|
the ioctl; measure at the actual display's DPI, including through any PTY proxy.
|
|
166
|
+
Cell pixels determine the artwork canvas; the Kitty virtual placement declares its
|
|
167
|
+
column count and one-row height explicitly so the placeholder grid does not depend on
|
|
168
|
+
the terminal or PTY proxy reporting the same pixel dimensions.
|
|
116
169
|
|
|
117
170
|
Artwork is approximately square, centered at 85% of one cell row's height, with a bold,
|
|
118
171
|
action-colored key beside each
|
|
Binary file
|