@nxxxsooo/opencode-annotate 0.6.0 → 0.8.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,48 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.8.1 — Antigravity (AGY) support and uncompressed history
4
+
5
+ - Antigravity CLI (AGY) support via `agy-annotate`:
6
+ - New binary `agy-annotate` providing `status`, `tui`, `web`, and `queue` subcommands.
7
+ - Native hooks integration (`SessionStart`, `PreInvocation`, `Stop`) delivering annotations directly into active AGY turns without external network services.
8
+ - Decoupled bridge receiver to register and route between both `opencode` and `agy` session providers.
9
+ - Browser companion panel badges (`[AGY]` / `[OPENCODE]`) and session chooser hints.
10
+ - Adapted TUI launcher for AGY with automatic resolution of the local fork (`plannotator-tui-annotate`), full Dracula theme inheritance via `prepareTheme()`, 120-column measure layout, and one-key send (`PLANNOTATOR_TUI_SEND_INTENT`).
11
+ - Request session history uncompressed. OpenCode 2.2.0 compresses API responses at about
12
+ 80 KB/s, so `/annotate`, `/annotate-pick` and `/annotate-selection` waited 10–40 s on a
13
+ page of long replies before the review opened; the same page now loads in milliseconds.
14
+
15
+ ## 0.7.0 — one-key send and browser review rounds
16
+
17
+ ### Text review
18
+
19
+ - Pass `PLANNOTATOR_TUI_SEND_INTENT` to the TUI. With the fork's `local/opencode` branch
20
+ (proposed upstream as plannotator/plannotator-tui#109), `q` with notes returns and sends
21
+ without the OpenCode confirmation; `Ctrl+S`, `E` and `S` send too, following `[keys]`,
22
+ and `Ctrl+S` saves an open comment first. `Ctrl+C` returns so OpenCode asks. The header
23
+ shows one **Send N back (q)** button; the clipboard copy and Review menu are hidden.
24
+ Upstream binaries are unaffected.
25
+
26
+ ### Browser review rounds
27
+
28
+ - Sending closes a review round: delivered notes leave the list, page markers renumber,
29
+ and the panel is ready for the next round. **Restore last round** brings the latest
30
+ delivered notes back; the last ten rounds per page are kept.
31
+ - Without a live session, the primary action is **Copy N notes & continue**; a copy icon
32
+ beside Send offers the same when connected. Copying closes the round and supersedes a
33
+ failed batch; a blocked clipboard keeps the round open.
34
+ - Copy writes the clipboard within the click, before saving an open draft, and falls back
35
+ to the new `clipboardWrite` permission, so Chrome no longer refuses it on slow pages.
36
+ - Separate the two delivery modes: a **Live**/**Offline** marker beside the destination,
37
+ **Send N notes** only with a live session, **Copy N notes** otherwise. A session that
38
+ drops during Send keeps the notes and switches to Copy instead of showing an error.
39
+ - Detect a stale background worker after an update and offer **Reload Annotate**
40
+ instead of `Unknown annotation action`.
41
+ - Strip invisible format characters from page titles, such as Feishu's title watermark.
42
+ - Reconnect page tools automatically after a reload or same-site navigation, fixing
43
+ `Could not establish connection. Receiving end does not exist.` on Pick, Show on page
44
+ and markers. When Chrome has withdrawn access, the panel asks for one icon click.
45
+
3
46
  ## 0.6.0 — annotate any session text
4
47
 
5
48
  ### Text review
package/README.md CHANGED
@@ -69,13 +69,29 @@ Manual configuration, preserving other entries:
69
69
  }
70
70
  ```
71
71
 
72
+ ## Antigravity (AGY) support
73
+
74
+ `opencode-annotate` provides companion support for Google Antigravity CLI (`agy`) via `agy-annotate`:
75
+
76
+ - **Slash commands `/annotate` & `/annotate-web`**: Built-in AGY skill at `agy/skills/annotate/` handles review directly within active AGY sessions.
77
+ - **Interactive TUI**: Resolves the OpenCode-adapted Plannotator fork with Dracula theme inheritance, 120-column measure layout, and one-key send.
78
+ - **Native Delivery**: Hooks into AGY lifecycle (`SessionStart`, `PreInvocation`, `Stop`) to deliver feedback directly into the conversation turn without network listeners.
79
+ - **CLI Commands**:
80
+ ```sh
81
+ npx agy-annotate status # View active AGY sessions and annotation pairing
82
+ npx agy-annotate tui # Review latest assistant reply or markdown file
83
+ npx agy-annotate web # Pair browser companion with active AGY session
84
+ npx agy-annotate queue # Inspect pending delivered annotations
85
+ ```
86
+
72
87
  ### Match OpenCode's colors (fork required)
73
88
 
74
89
  Set `"inheritTheme": true` in the plugin's `options`, alongside `binary`. It requires
75
90
  the extended color-capable Plannotator fork
76
91
  ([nxxxsooo/plannotator-tui](https://github.com/nxxxsooo/plannotator-tui), branch
77
- `feat/layout`); upstream 0.9.4 does not support it. The same fork adds `[ui].doc_width`
78
- to cap the text column on wide terminals. See [TUI theme integration](docs/tui-theme.md).
92
+ `local/opencode`); upstream 0.9.4 does not support it. The same branch adds `[ui].doc_width`
93
+ to cap the text column on wide terminals (proposed upstream in
94
+ [plannotator/plannotator-tui#108](https://github.com/plannotator/plannotator-tui/pull/108)). See [TUI theme integration](docs/tui-theme.md).
79
95
 
80
96
  Each review uses OpenCode's current resolved colors for the canvas, text, Markdown,
81
97
  borders, highlights, cursor and selection. The plugin asks the chosen binary for its
@@ -110,9 +126,24 @@ Switching terminal tabs never changes the paired target. Revoke with `/annotate-
110
126
 
111
127
  The numbered queue matches the page markers. Click a note's quoted target to show it
112
128
  on the page without activating the element; **Edit** changes the feedback, and **Undo**
113
- restores a deleted note. The delivery bar shows the pending count, destination, and sent
114
- state. **More review options** contains Markdown copy, JSON export, and a preview of
115
- all saved notes.
129
+ restores a deleted note. The delivery bar shows the round's note count and destination.
130
+
131
+ Each send closes a review round: delivered notes leave the list and the panel is ready
132
+ for the next round. **Restore last round** returns the most recent delivered notes to the
133
+ list; the last ten rounds per page are kept.
134
+
135
+ Delivery has two modes, shown beside the destination. With a **Live** session the primary
136
+ button is **Send N notes**, and the copy icon beside it copies the round instead. When the
137
+ session is **Offline**, or none is connected, the button is **Copy N notes**: it copies the
138
+ round as Markdown for any agent and closes it the same way. Run `/annotate-web` in a
139
+ session to switch back to Send. If a session drops during Send, the notes are kept and the
140
+ panel switches to Copy.
141
+ **More review options** contains a non-closing Markdown copy, JSON export, and a preview
142
+ of the current round.
143
+
144
+ After a page reload or same-site navigation, the panel reconnects its page tools
145
+ automatically. If Chrome has withdrawn access (for example after moving to another site),
146
+ the panel asks you to click the extension icon once; saved notes are kept.
116
147
 
117
148
  ### Explicit routing
118
149
 
@@ -137,8 +168,8 @@ Native delivery requires an open, paired local TUI. If the receiver closes, feed
137
168
  pending. A failed batch retains its original target and ID for safe retry; if that target
138
169
  is permanently gone, export the notes before starting a new review. **Retry N notes &
139
170
  continue** retries that original batch; newly composed feedback stays local for the next
140
- send. Changed sent notes become new pending revisions; unchanged edits send nothing new.
141
- Clipboard failures expose a selectable preview. Browser-internal pages, PDF,
171
+ send. Copying a round instead supersedes a failed batch.
172
+ Clipboard failures expose a selectable preview and keep the round open. Browser-internal pages, PDF,
142
173
  cross-origin iframes, Canvas and remote SSH TUI clients are outside this version's scope.
143
174
  Page Context is retired only after exporting its drafts and verifying this replacement.
144
175
 
@@ -155,10 +186,8 @@ After updating the unpacked `browser/` files, open `chrome://extensions` and cli
155
186
  using its extension icon or **Alt+Shift+A**.
156
187
 
157
188
  A newly opened sidebar can load the updated `panel.mjs` while Chrome still runs an
158
- older `worker.mjs`. With the compact workspace, that mismatch produces
159
- `Cannot read properties of undefined (reading 'value')`: the sidebar expects a
160
- `draft` record that the older worker does not return. Reload the whole extension;
161
- reopening only the sidebar does not ensure the background code is refreshed.
189
+ older `worker.mjs`. The panel detects this protocol mismatch and shows **Annotate was
190
+ updated** with a **Reload Annotate** button; reopen the panel afterwards.
162
191
  Saved extension-local data survives an extension reload.
163
192
 
164
193
  For diagnosis, compare the running worker's source (DevTools/CDP
@@ -178,6 +207,16 @@ The manifest version alone cannot identify edits to an unpacked extension.
178
207
  The upstream **`E`** action copies to the clipboard. This adapter's automatic
179
208
  delivery path is **q → confirm** and does not need clipboard access.
180
209
 
210
+ With the [fork](#match-opencodes-colors-fork-required) (branch `local/opencode`; proposed
211
+ upstream in [plannotator/plannotator-tui#109](https://github.com/plannotator/plannotator-tui/pull/109)),
212
+ **`q`** with notes returns and submits them without the OpenCode dialog. **`Ctrl+S`**
213
+ does the same mid-comment, saving the comment first, and also works while a Chinese
214
+ input method is active. The header's **Send N back (q)** button does the same.
215
+ **`Ctrl+C`** returns without sending, and OpenCode asks whether to send. `E` and `S` send as well,
216
+ following any `[keys]` rebinding, and the clipboard copy and Review menu (resend, finish, archive) are hidden
217
+ because OpenCode owns delivery. Upstream binaries ignore the handoff and keep
218
+ **q → confirm**.
219
+
181
220
  Opening a review makes no model call. Confirming sends a normal user prompt and
182
221
  resumes the **original session**, even if the active tab changes. Empty and
183
222
  cancelled reviews submit nothing.
@@ -293,6 +332,7 @@ See [release instructions](docs/releasing.md) and [changelog](CHANGELOG.md).
293
332
  - `/annotate-last`:固定批注最新一条完整回复,忽略附带参数。
294
333
  - `/annotate-web`:配对 Chrome;`/annotate-web 页面.html`、`/annotate-web https://…` 批注网页;`/annotate-web off` 撤销配对。
295
334
  - 选中文字 → `c` 写批注 → Enter 保存 → `q` 返回 →「Send and continue」。
335
+ - 用 fork 时:有批注时按 `q` 直接返回并发送;写批注中途按 `Ctrl+S`,一步保存、返回并发送(中文输入法开着也有效);`Ctrl+C` 不发送,返回后由 OpenCode 询问。
296
336
  - 文档采用独立快照,反馈附原文件路径,确认后发回发起批注的会话。
297
337
  - 更新:`opencode plugin update @nxxxsooo/opencode-annotate@latest`,然后重新打开终端客户端。
298
338
 
package/agy/cli.mjs ADDED
@@ -0,0 +1,366 @@
1
+ #!/usr/bin/env node
2
+ import { spawn, execFile } from "node:child_process"
3
+ import { promisify } from "node:util"
4
+ import { mkdtemp, mkdir, rm, readFile, writeFile } from "node:fs/promises"
5
+ import { statSync } from "node:fs"
6
+ import path from "node:path"
7
+ import os from "node:os"
8
+ import { fileURLToPath } from "node:url"
9
+ import { randomUUID, createHash } from "node:crypto"
10
+ import { findSessionForDirectory, getActiveAgySessions } from "./session.mjs"
11
+ import { extractAgyReplies, latestCompletedReply, defaultBrainDir } from "./transcript.mjs"
12
+ import { enqueueAnnotations, listPendingBatches, defaultInboxRoot } from "./inbox.mjs"
13
+ import { startAgyDaemon } from "./daemon.mjs"
14
+ import { listTargets, registryRoot } from "../bridge/receiver.mjs"
15
+ import { browserTarget } from "../targets.mjs"
16
+ import { prepareTheme } from "../theme.mjs"
17
+
18
+ const execute = promisify(execFile)
19
+
20
+ export function resolveAdaptedBinary(customBinary) {
21
+ if (customBinary) return customBinary
22
+ const localAnnotate = path.join(os.homedir(), ".local/bin/plannotator-tui-annotate")
23
+ try {
24
+ if (statSync(localAnnotate).isFile()) return localAnnotate
25
+ } catch {}
26
+ return "plannotator-tui"
27
+ }
28
+
29
+ export function getAdaptedThemeTokens() {
30
+ const rgba = (r, g, b, a = 1) => ({ r: r / 255, g: g / 255, b: b / 255, a })
31
+ const text = rgba(248, 248, 242), bg = rgba(40, 42, 54), accent = rgba(189, 147, 249)
32
+ return {
33
+ text: { base: text, muted: rgba(98, 114, 164), action: { primary: { selected: accent, focused: bg } },
34
+ feedback: { warning: { base: rgba(241, 250, 140) }, success: { base: rgba(80, 250, 123) }, error: { base: rgba(255, 85, 85) } } },
35
+ background: { base: bg, raised: { base: rgba(33, 34, 44), high: rgba(68, 71, 90) },
36
+ action: { primary: { base: rgba(98, 114, 164), focused: accent } },
37
+ feedback: { success: { base: rgba(80, 250, 123) }, warning: { base: rgba(241, 250, 140) } } },
38
+ border: { base: rgba(68, 71, 90) },
39
+ markdown: { heading: accent, code: rgba(80, 250, 123), link: rgba(139, 233, 253), blockQuote: rgba(98, 114, 164),
40
+ strong: rgba(255, 184, 108), emphasis: rgba(241, 250, 140), listItem: rgba(139, 233, 253),
41
+ linkText: rgba(255, 121, 198), listEnumeration: rgba(80, 250, 123), horizontalRule: rgba(68, 71, 90) },
42
+ diff: { background: { added: rgba(26, 58, 26) } },
43
+ }
44
+ }
45
+
46
+ function usage() {
47
+ console.log(`Usage: agy-annotate <command> [options]
48
+
49
+ Commands:
50
+ status Show active AGY sessions and annotation pairing state
51
+ web [target] Pair browser companion with current AGY session (or open URL/HTML)
52
+ tui [path] Review latest AGY reply or markdown document in Plannotator TUI
53
+ queue List pending annotations queued for current AGY session
54
+
55
+ Options:
56
+ --session <id> Explicit AGY conversation ID (defaults to cwd-matched active session)
57
+ --binary <path> Path to plannotator-tui binary (default: 'plannotator-tui')
58
+ `)
59
+ }
60
+
61
+ async function resolveSession(targetId) {
62
+ if (targetId) {
63
+ const sessions = getActiveAgySessions()
64
+ const found = sessions.find(s => s.conversationId === targetId || s.conversationId.startsWith(targetId))
65
+ if (!found) throw new Error(`No active AGY session found with ID "${targetId}"`)
66
+ return found
67
+ }
68
+
69
+ const current = findSessionForDirectory(process.cwd())
70
+ if (!current) {
71
+ const active = getActiveAgySessions()
72
+ if (active.length === 0) throw new Error("No active AGY sessions found. Launch 'agy' first.")
73
+ if (active.length === 1) return active[0]
74
+ throw new Error(`Multiple active AGY sessions found (${active.length}). Specify --session <id>.`)
75
+ }
76
+ return current
77
+ }
78
+
79
+ async function cmdStatus() {
80
+ const sessions = getActiveAgySessions()
81
+ const targets = await listTargets()
82
+
83
+ if (sessions.length === 0) {
84
+ console.log("No active AGY sessions currently running.")
85
+ return
86
+ }
87
+
88
+ console.log(`Active AGY Sessions (${sessions.length}):\n`)
89
+ for (const session of sessions) {
90
+ const paired = targets.find(t => t.sessionID === session.conversationId)
91
+ const inbox = await listPendingBatches(session.conversationId)
92
+ const pairedStatus = paired ? `paired (target ${paired.id.slice(0, 8)})` : "not paired"
93
+ const inboxStatus = inbox.length ? `[${inbox.length} pending annotations]` : "[inbox clear]"
94
+
95
+ console.log(` • [${session.conversationId.slice(0, 8)}] ${session.title}`)
96
+ console.log(` PID: ${session.pid} | Directory: ${session.directory}`)
97
+ console.log(` Status: ${pairedStatus} | ${inboxStatus}\n`)
98
+ }
99
+ }
100
+
101
+ async function cmdWeb(targetArg, options) {
102
+ const session = await resolveSession(options.session)
103
+ const targets = await listTargets()
104
+ let paired = targets.find(t => t.sessionID === session.conversationId)
105
+
106
+ if (!paired) {
107
+ const daemonScript = path.join(path.dirname(new URL(import.meta.url).pathname), "daemon.mjs")
108
+ const args = ["--session", session.conversationId, "--dir", session.directory, "--title", session.title]
109
+ if (session.pid) args.push("--pid", String(session.pid))
110
+
111
+ const child = spawn(process.execPath, [daemonScript, ...args], {
112
+ detached: true,
113
+ stdio: "ignore",
114
+ })
115
+ child.unref()
116
+
117
+ // Wait briefly for socket registration
118
+ for (let i = 0; i < 20; i++) {
119
+ await new Promise(r => setTimeout(r, 50))
120
+ const fresh = await listTargets()
121
+ paired = fresh.find(t => t.sessionID === session.conversationId)
122
+ if (paired) break
123
+ }
124
+ }
125
+
126
+ console.log(`✓ Session paired for browser review: "${session.title}" (${session.conversationId.slice(0, 8)})`)
127
+ console.log(` Open Chrome extension "Annotate" and choose this session.`)
128
+
129
+ if (targetArg && targetArg.trim()) {
130
+ const target = await browserTarget(targetArg, session.directory)
131
+ if (target?.url) {
132
+ console.log(` Opening Chrome target: ${target.url}`)
133
+ if (process.platform === "darwin") {
134
+ await execute("open", ["-a", "Google Chrome", target.url])
135
+ }
136
+ }
137
+ }
138
+ }
139
+
140
+ async function cmdQueue(options) {
141
+ const session = await resolveSession(options.session)
142
+ const batches = await listPendingBatches(session.conversationId)
143
+
144
+ if (batches.length === 0) {
145
+ console.log(`Inbox is clear for session "${session.title}".`)
146
+ return
147
+ }
148
+
149
+ console.log(`Queued Annotations for "${session.title}" (${batches.length} batches):\n`)
150
+ for (const [index, batch] of batches.entries()) {
151
+ console.log(`Batch ${index + 1} (${batch.batchID}) - Created ${batch.createdAt}:`)
152
+ console.log(batch.markdown)
153
+ console.log("\n--------------------------------------------------\n")
154
+ }
155
+ }
156
+
157
+ async function cmdTui(targetPath, options) {
158
+ const session = await resolveSession(options.session)
159
+ const binary = resolveAdaptedBinary(options.binary)
160
+ const brainDir = defaultBrainDir(session.conversationId)
161
+ const calledByAgent = Boolean(process.env.ANTIGRAVITY_AGENT || process.env.AGENT_TOOL_CALL)
162
+ const isInteractiveTTY = Boolean(options.interactiveTty) || (!calledByAgent && Boolean(process.stdin.isTTY) && !options.spawnWindow)
163
+
164
+ if (!isInteractiveTTY) {
165
+ const launcherScript = path.join(os.tmpdir(), `agy-annotate-launch-${Date.now()}.sh`)
166
+ const doneMarker = path.join(os.tmpdir(), `agy-annotate-done-${Date.now()}.txt`)
167
+ const cliScript = path.resolve(new URL(import.meta.url).pathname)
168
+ const tuiArgs = [cliScript, "tui", "--interactive-tty", "--session", session.conversationId]
169
+ if (targetPath) tuiArgs.push(targetPath)
170
+ if (options.binary) tuiArgs.push("--binary", options.binary)
171
+
172
+ const escapedTitle = (session.title || "Review").replace(/'/g, "'\\''")
173
+ const shellCmd = `printf '\\033]0;Annotate: %s\\007' '${escapedTitle}'\n${process.execPath} ${tuiArgs.map(a => `'${a.replace(/'/g, "'\\''")}'`).join(" ")}; echo done > '${doneMarker}'`
174
+ await writeFile(launcherScript, `#!/bin/sh\n${shellCmd}\n`, { mode: 0o755 })
175
+
176
+ const beforeBatches = await listPendingBatches(session.conversationId)
177
+
178
+ let launched = false
179
+ try {
180
+ const windowTitle = `Annotate: ${session.title}`
181
+ await execute("open", ["-na", "Ghostty", "--args", "--window-width=172", "--window-height=48", `--title=${windowTitle}`, "-e", launcherScript])
182
+ launched = true
183
+ } catch {
184
+ try {
185
+ await execute("osascript", ["-e", `tell application "Terminal" to do script "${launcherScript}"`, "-e", 'tell application "Terminal" to activate'])
186
+ launched = true
187
+ } catch (err) {
188
+ throw new Error(`Failed to spawn interactive review window: ${err.message}`)
189
+ }
190
+ }
191
+
192
+ console.log(`Opened interactive Plannotator TUI window for "${session.title}".`)
193
+ console.log("Waiting for user to complete annotations (press 'q' or Ctrl+S to finish)...")
194
+
195
+ for (let i = 0; i < 300; i++) {
196
+ await new Promise(r => setTimeout(r, 1000))
197
+ const currentBatches = await listPendingBatches(session.conversationId)
198
+ if (currentBatches.length > beforeBatches.length) {
199
+ const newest = currentBatches[currentBatches.length - 1]
200
+ console.log(`\n✓ Annotations received from review window:\n\n${newest.markdown}`)
201
+ try { await rm(launcherScript, { force: true }); await rm(doneMarker, { force: true }) } catch {}
202
+ return
203
+ }
204
+ try {
205
+ await readFile(doneMarker)
206
+ await new Promise(r => setTimeout(r, 500))
207
+ const finalBatches = await listPendingBatches(session.conversationId)
208
+ if (finalBatches.length > beforeBatches.length) {
209
+ const newest = finalBatches[finalBatches.length - 1]
210
+ console.log(`\n✓ Annotations received from review window:\n\n${newest.markdown}`)
211
+ } else {
212
+ console.log("Interactive review window closed without annotations.")
213
+ }
214
+ try { await rm(launcherScript, { force: true }); await rm(doneMarker, { force: true }) } catch {}
215
+ return
216
+ } catch {
217
+ // Still waiting
218
+ }
219
+ }
220
+ return
221
+ }
222
+
223
+ let sourceText = ""
224
+ let snapshotName = "last-reply.md"
225
+ let filePath = null
226
+ let sourceHash = null
227
+
228
+ if (targetPath) {
229
+ const resolvedPath = path.resolve(session.directory, targetPath)
230
+ sourceText = await readFile(resolvedPath, "utf8")
231
+ filePath = resolvedPath
232
+ snapshotName = path.basename(resolvedPath)
233
+ sourceHash = createHash("sha256").update(Buffer.from(sourceText)).digest("hex")
234
+ } else {
235
+ const replies = await extractAgyReplies(brainDir)
236
+ const latest = latestCompletedReply(replies)
237
+ if (!latest || !latest.text.trim()) {
238
+ throw new Error(`No completed assistant replies found in session "${session.title}".`)
239
+ }
240
+ sourceText = latest.text
241
+ snapshotName = `reply-${latest.id}.md`
242
+ }
243
+
244
+ const tempDir = await mkdtemp(path.join(os.tmpdir(), "agy-annotate-"))
245
+ const snapshotFile = path.join(tempDir, snapshotName)
246
+ const dataDir = path.join(tempDir, "data")
247
+ const intentPath = path.join(tempDir, "send-intent")
248
+
249
+ await mkdir(dataDir, { recursive: true, mode: 0o700 })
250
+ await writeFile(snapshotFile, sourceText, { mode: 0o600 })
251
+
252
+ let env = {
253
+ ...process.env,
254
+ PLANNOTATOR_DATA_DIR: dataDir,
255
+ PLANNOTATOR_FEEDBACK_HISTORY: "0",
256
+ PLANNOTATOR_TUI_SEND_INTENT: intentPath,
257
+ }
258
+
259
+ try {
260
+ env = await prepareTheme({
261
+ binary,
262
+ theme: getAdaptedThemeTokens(),
263
+ directory: tempDir,
264
+ env,
265
+ })
266
+ } catch {
267
+ // If binary does not support theme command, fallback to base env
268
+ }
269
+
270
+ try {
271
+ // Run Plannotator interactively
272
+ const child = spawn(binary, [snapshotFile], {
273
+ cwd: tempDir,
274
+ env,
275
+ stdio: "inherit",
276
+ })
277
+
278
+ await new Promise((resolve, reject) => {
279
+ child.on("exit", (code, signal) => {
280
+ if (signal) reject(new Error(`TUI killed by signal ${signal}`))
281
+ else resolve(code)
282
+ })
283
+ child.on("error", reject)
284
+ })
285
+
286
+ // Export annotations
287
+ const { stdout } = await execute(binary, ["--export", snapshotFile], {
288
+ cwd: tempDir,
289
+ env,
290
+ timeout: 15000,
291
+ })
292
+ const feedback = stdout.trim()
293
+
294
+ if (!feedback || feedback === "No annotations.") {
295
+ console.log("No annotations created. Returned to terminal.")
296
+ return
297
+ }
298
+
299
+ const header = filePath
300
+ ? `Annotations on document \`${filePath}\` (SHA-256: ${sourceHash}):`
301
+ : `Annotations on latest assistant response in session "${session.title}":`
302
+ const combined = `${header}\n\n${feedback}`
303
+
304
+ await enqueueAnnotations(session.conversationId, {
305
+ batchID: `tui-${Date.now()}`,
306
+ markdown: combined,
307
+ promptID: `msg_${randomUUID()}`,
308
+ })
309
+
310
+ console.log(`\n✓ Enqueued annotations for AGY session: "${session.title}"`)
311
+ console.log(` The next AGY turn or invocation will ingest this feedback.`)
312
+ } finally {
313
+ await rm(tempDir, { recursive: true, force: true })
314
+ }
315
+ }
316
+
317
+ async function main() {
318
+ const args = process.argv.slice(2)
319
+ if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
320
+ usage()
321
+ return
322
+ }
323
+
324
+ const command = args[0]
325
+ const options = {}
326
+ let posArg = null
327
+
328
+ for (let i = 1; i < args.length; i++) {
329
+ if (args[i] === "--session") {
330
+ options.session = args[++i]
331
+ } else if (args[i] === "--binary") {
332
+ options.binary = args[++i]
333
+ } else if (args[i] === "--interactive-tty") {
334
+ options.interactiveTty = true
335
+ } else if (!args[i].startsWith("-") && !posArg) {
336
+ posArg = args[i]
337
+ }
338
+ }
339
+
340
+ switch (command) {
341
+ case "status":
342
+ await cmdStatus()
343
+ break
344
+ case "web":
345
+ await cmdWeb(posArg, options)
346
+ break
347
+ case "tui":
348
+ await cmdTui(posArg, options)
349
+ break
350
+ case "queue":
351
+ await cmdQueue(options)
352
+ break
353
+ default:
354
+ console.error(`Unknown command: "${command}"`)
355
+ usage()
356
+ process.exit(1)
357
+ }
358
+ }
359
+
360
+ const isDirectExecution = process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])
361
+ if (isDirectExecution) {
362
+ main().catch(err => {
363
+ console.error(`Error: ${err.message}`)
364
+ process.exit(1)
365
+ })
366
+ }
@@ -0,0 +1,51 @@
1
+ import { test } from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import path from "node:path"
4
+ import os from "node:os"
5
+ import { mkdir, rm } from "node:fs/promises"
6
+ import { resolveAdaptedBinary, getAdaptedThemeTokens } from "./cli.mjs"
7
+ import { prepareTheme } from "../theme.mjs"
8
+
9
+ test("resolveAdaptedBinary honors custom binary or finds local annotate fork", () => {
10
+ const custom = "/custom/bin/plannotator-tui"
11
+ assert.equal(resolveAdaptedBinary(custom), custom)
12
+
13
+ const resolved = resolveAdaptedBinary()
14
+ // On this system, ~/.local/bin/plannotator-tui-annotate exists
15
+ assert.match(resolved, /(plannotator-tui-annotate|plannotator-tui)$/)
16
+ })
17
+
18
+ test("getAdaptedThemeTokens returns valid RGBA palette tokens", () => {
19
+ const tokens = getAdaptedThemeTokens()
20
+ assert.ok(tokens.text.base)
21
+ assert.ok(tokens.background.base)
22
+ assert.ok(tokens.markdown.heading)
23
+ assert.equal(typeof tokens.text.base.r, "number")
24
+ assert.equal(typeof tokens.text.base.g, "number")
25
+ assert.equal(typeof tokens.text.base.b, "number")
26
+ assert.equal(typeof tokens.text.base.a, "number")
27
+ })
28
+
29
+ test("prepareTheme succeeds with getAdaptedThemeTokens when fork is available", async t => {
30
+ const binary = resolveAdaptedBinary()
31
+ const tempDir = path.join(os.tmpdir(), `agy-cli-test-${Date.now()}`)
32
+ await mkdir(tempDir, { recursive: true })
33
+ try {
34
+ const env = await prepareTheme({
35
+ binary,
36
+ theme: getAdaptedThemeTokens(),
37
+ directory: tempDir,
38
+ env: process.env,
39
+ })
40
+ assert.ok(env.PLANNOTATOR_TUI_CONFIG)
41
+ assert.ok(env.PLANNOTATOR_TUI_CONFIG.endsWith("theme.toml"))
42
+ } catch (err) {
43
+ if (/color-capable Plannotator fork/i.test(err.message)) {
44
+ t.skip("Upstream plannotator-tui does not support theme command")
45
+ return
46
+ }
47
+ throw err
48
+ } finally {
49
+ await rm(tempDir, { recursive: true, force: true })
50
+ }
51
+ })
package/agy/daemon.mjs ADDED
@@ -0,0 +1,64 @@
1
+ import { createAgyReceiver, getAgySessionTitle } from "./receiver.mjs"
2
+ import { parseArgs } from "node:util"
3
+ import path from "node:path"
4
+
5
+ export async function startAgyDaemon({ conversationId, pid, directory, title, root, inboxRoot }) {
6
+ if (!conversationId) throw new Error("conversationId is required")
7
+
8
+ const receiver = await createAgyReceiver({
9
+ conversationId,
10
+ title,
11
+ directory: directory || process.cwd(),
12
+ root,
13
+ inboxRoot,
14
+ })
15
+
16
+ // Watch parent AGY process PID; auto-exit when AGY exits
17
+ if (pid && Number.isInteger(pid) && pid > 0) {
18
+ const timer = setInterval(() => {
19
+ try {
20
+ process.kill(pid, 0)
21
+ } catch {
22
+ clearInterval(timer)
23
+ receiver.close().finally(() => process.exit(0))
24
+ }
25
+ }, 2000)
26
+ timer.unref()
27
+ }
28
+
29
+ const cleanup = async () => {
30
+ await receiver.close()
31
+ process.exit(0)
32
+ }
33
+
34
+ process.once("SIGINT", cleanup)
35
+ process.once("SIGTERM", cleanup)
36
+
37
+ return receiver
38
+ }
39
+
40
+ if (process.argv[1] && process.argv[1].endsWith("daemon.mjs")) {
41
+ const { values } = parseArgs({
42
+ options: {
43
+ session: { type: "string" },
44
+ pid: { type: "string" },
45
+ dir: { type: "string" },
46
+ title: { type: "string" },
47
+ },
48
+ })
49
+
50
+ if (!values.session) {
51
+ console.error("Usage: node daemon.mjs --session <conversationId> [--pid <pid>] [--dir <dir>] [--title <title>]")
52
+ process.exit(1)
53
+ }
54
+
55
+ await startAgyDaemon({
56
+ conversationId: values.session,
57
+ pid: values.pid ? parseInt(values.pid, 10) : undefined,
58
+ directory: values.dir,
59
+ title: values.title,
60
+ })
61
+
62
+ // Keep daemon alive until killed or parent PID exits
63
+ await new Promise(() => {})
64
+ }
package/agy/hooks.json ADDED
@@ -0,0 +1,22 @@
1
+ {
2
+ "agy-annotate": {
3
+ "SessionStart": [
4
+ {
5
+ "command": "node ./hooks.mjs SessionStart",
6
+ "timeout": 15
7
+ }
8
+ ],
9
+ "PreInvocation": [
10
+ {
11
+ "command": "node ./hooks.mjs PreInvocation",
12
+ "timeout": 15
13
+ }
14
+ ],
15
+ "Stop": [
16
+ {
17
+ "command": "node ./hooks.mjs Stop",
18
+ "timeout": 15
19
+ }
20
+ ]
21
+ }
22
+ }