@nxxxsooo/opencode-annotate 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.9.0 — input-method-safe keys
4
+
5
+ - Switch to Slash Saver's ASCII input source while a TUI review is browsed (OpenCode and
6
+ `agy-annotate`) and while an OpenCode permission prompt is open, then restore the previous
7
+ source. A Chinese input method otherwise swallows single-letter keys. The fork switches
8
+ the comment and edit boxes back to the writing source and binds `Ctrl+E` to edit. New
9
+ `inputSource` option: `false` disables, a path selects another helper.
10
+
11
+ ## 0.8.1 — Antigravity (AGY) support and uncompressed history
12
+
13
+ - Antigravity CLI (AGY) support via `agy-annotate`:
14
+ - New binary `agy-annotate` providing `status`, `tui`, `web`, and `queue` subcommands.
15
+ - Native hooks integration (`SessionStart`, `PreInvocation`, `Stop`) delivering annotations directly into active AGY turns without external network services.
16
+ - Decoupled bridge receiver to register and route between both `opencode` and `agy` session providers.
17
+ - Browser companion panel badges (`[AGY]` / `[OPENCODE]`) and session chooser hints.
18
+ - 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`).
19
+ - Request session history uncompressed. OpenCode 2.2.0 compresses API responses at about
20
+ 80 KB/s, so `/annotate`, `/annotate-pick` and `/annotate-selection` waited 10–40 s on a
21
+ page of long replies before the review opened; the same page now loads in milliseconds.
22
+
3
23
  ## 0.7.0 — one-key send and browser review rounds
4
24
 
5
25
  ### Text review
package/README.md CHANGED
@@ -69,6 +69,21 @@ 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
@@ -195,13 +210,25 @@ delivery path is **q → confirm** and does not need clipboard access.
195
210
  With the [fork](#match-opencodes-colors-fork-required) (branch `local/opencode`; proposed
196
211
  upstream in [plannotator/plannotator-tui#109](https://github.com/plannotator/plannotator-tui/pull/109)),
197
212
  **`q`** with notes returns and submits them without the OpenCode dialog. **`Ctrl+S`**
198
- does the same mid-comment, saving the comment first, and also works while a Chinese
199
- input method is active. The header's **Send N back (q)** button does the same.
213
+ does the same mid-comment, saving the comment first. The header's **Send N back (q)**
214
+ button does the same as `q`.
200
215
  **`Ctrl+C`** returns without sending, and OpenCode asks whether to send. `E` and `S` send as well,
201
216
  following any `[keys]` rebinding, and the clipboard copy and Review menu (resend, finish, archive) are hidden
202
217
  because OpenCode owns delivery. Upstream binaries ignore the handoff and keep
203
218
  **q → confirm**.
204
219
 
220
+ ### Chinese and other input methods
221
+
222
+ An input method holds plain letters while it composes, so review keys such as `e`, `q`
223
+ and `s`, and OpenCode's permission shortcuts, do nothing. With
224
+ [Slash Saver](https://github.com/nxxxsooo/slash-saver) 1.1+ installed in `/Applications`,
225
+ the plugin selects its configured ASCII source while you browse a review or answer a
226
+ permission prompt, and restores your source afterwards. With the fork, the comment and edit
227
+ boxes switch back to your writing source while open. Set `"inputSource": false` in the
228
+ plugin's `options` to turn this off, or a path to another helper with the same
229
+ `input-source current|select|ascii` commands. The fork also binds **`Ctrl+E`** to edit,
230
+ which an input method passes through.
231
+
205
232
  Opening a review makes no model call. Confirming sends a normal user prompt and
206
233
  resumes the **original session**, even if the active tab changes. Empty and
207
234
  cancelled reviews submit nothing.
package/agy/cli.mjs ADDED
@@ -0,0 +1,375 @@
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
+ import { createInputSource } from "../input-source.mjs"
18
+
19
+ const execute = promisify(execFile)
20
+
21
+ export function resolveAdaptedBinary(customBinary) {
22
+ if (customBinary) return customBinary
23
+ const localAnnotate = path.join(os.homedir(), ".local/bin/plannotator-tui-annotate")
24
+ try {
25
+ if (statSync(localAnnotate).isFile()) return localAnnotate
26
+ } catch {}
27
+ return "plannotator-tui"
28
+ }
29
+
30
+ export function getAdaptedThemeTokens() {
31
+ const rgba = (r, g, b, a = 1) => ({ r: r / 255, g: g / 255, b: b / 255, a })
32
+ const text = rgba(248, 248, 242), bg = rgba(40, 42, 54), accent = rgba(189, 147, 249)
33
+ return {
34
+ text: { base: text, muted: rgba(98, 114, 164), action: { primary: { selected: accent, focused: bg } },
35
+ feedback: { warning: { base: rgba(241, 250, 140) }, success: { base: rgba(80, 250, 123) }, error: { base: rgba(255, 85, 85) } } },
36
+ background: { base: bg, raised: { base: rgba(33, 34, 44), high: rgba(68, 71, 90) },
37
+ action: { primary: { base: rgba(98, 114, 164), focused: accent } },
38
+ feedback: { success: { base: rgba(80, 250, 123) }, warning: { base: rgba(241, 250, 140) } } },
39
+ border: { base: rgba(68, 71, 90) },
40
+ markdown: { heading: accent, code: rgba(80, 250, 123), link: rgba(139, 233, 253), blockQuote: rgba(98, 114, 164),
41
+ strong: rgba(255, 184, 108), emphasis: rgba(241, 250, 140), listItem: rgba(139, 233, 253),
42
+ linkText: rgba(255, 121, 198), listEnumeration: rgba(80, 250, 123), horizontalRule: rgba(68, 71, 90) },
43
+ diff: { background: { added: rgba(26, 58, 26) } },
44
+ }
45
+ }
46
+
47
+ function usage() {
48
+ console.log(`Usage: agy-annotate <command> [options]
49
+
50
+ Commands:
51
+ status Show active AGY sessions and annotation pairing state
52
+ web [target] Pair browser companion with current AGY session (or open URL/HTML)
53
+ tui [path] Review latest AGY reply or markdown document in Plannotator TUI
54
+ queue List pending annotations queued for current AGY session
55
+
56
+ Options:
57
+ --session <id> Explicit AGY conversation ID (defaults to cwd-matched active session)
58
+ --binary <path> Path to plannotator-tui binary (default: 'plannotator-tui')
59
+ `)
60
+ }
61
+
62
+ async function resolveSession(targetId) {
63
+ if (targetId) {
64
+ const sessions = getActiveAgySessions()
65
+ const found = sessions.find(s => s.conversationId === targetId || s.conversationId.startsWith(targetId))
66
+ if (!found) throw new Error(`No active AGY session found with ID "${targetId}"`)
67
+ return found
68
+ }
69
+
70
+ const current = findSessionForDirectory(process.cwd())
71
+ if (!current) {
72
+ const active = getActiveAgySessions()
73
+ if (active.length === 0) throw new Error("No active AGY sessions found. Launch 'agy' first.")
74
+ if (active.length === 1) return active[0]
75
+ throw new Error(`Multiple active AGY sessions found (${active.length}). Specify --session <id>.`)
76
+ }
77
+ return current
78
+ }
79
+
80
+ async function cmdStatus() {
81
+ const sessions = getActiveAgySessions()
82
+ const targets = await listTargets()
83
+
84
+ if (sessions.length === 0) {
85
+ console.log("No active AGY sessions currently running.")
86
+ return
87
+ }
88
+
89
+ console.log(`Active AGY Sessions (${sessions.length}):\n`)
90
+ for (const session of sessions) {
91
+ const paired = targets.find(t => t.sessionID === session.conversationId)
92
+ const inbox = await listPendingBatches(session.conversationId)
93
+ const pairedStatus = paired ? `paired (target ${paired.id.slice(0, 8)})` : "not paired"
94
+ const inboxStatus = inbox.length ? `[${inbox.length} pending annotations]` : "[inbox clear]"
95
+
96
+ console.log(` • [${session.conversationId.slice(0, 8)}] ${session.title}`)
97
+ console.log(` PID: ${session.pid} | Directory: ${session.directory}`)
98
+ console.log(` Status: ${pairedStatus} | ${inboxStatus}\n`)
99
+ }
100
+ }
101
+
102
+ async function cmdWeb(targetArg, options) {
103
+ const session = await resolveSession(options.session)
104
+ const targets = await listTargets()
105
+ let paired = targets.find(t => t.sessionID === session.conversationId)
106
+
107
+ if (!paired) {
108
+ const daemonScript = path.join(path.dirname(new URL(import.meta.url).pathname), "daemon.mjs")
109
+ const args = ["--session", session.conversationId, "--dir", session.directory, "--title", session.title]
110
+ if (session.pid) args.push("--pid", String(session.pid))
111
+
112
+ const child = spawn(process.execPath, [daemonScript, ...args], {
113
+ detached: true,
114
+ stdio: "ignore",
115
+ })
116
+ child.unref()
117
+
118
+ // Wait briefly for socket registration
119
+ for (let i = 0; i < 20; i++) {
120
+ await new Promise(r => setTimeout(r, 50))
121
+ const fresh = await listTargets()
122
+ paired = fresh.find(t => t.sessionID === session.conversationId)
123
+ if (paired) break
124
+ }
125
+ }
126
+
127
+ console.log(`✓ Session paired for browser review: "${session.title}" (${session.conversationId.slice(0, 8)})`)
128
+ console.log(` Open Chrome extension "Annotate" and choose this session.`)
129
+
130
+ if (targetArg && targetArg.trim()) {
131
+ const target = await browserTarget(targetArg, session.directory)
132
+ if (target?.url) {
133
+ console.log(` Opening Chrome target: ${target.url}`)
134
+ if (process.platform === "darwin") {
135
+ await execute("open", ["-a", "Google Chrome", target.url])
136
+ }
137
+ }
138
+ }
139
+ }
140
+
141
+ async function cmdQueue(options) {
142
+ const session = await resolveSession(options.session)
143
+ const batches = await listPendingBatches(session.conversationId)
144
+
145
+ if (batches.length === 0) {
146
+ console.log(`Inbox is clear for session "${session.title}".`)
147
+ return
148
+ }
149
+
150
+ console.log(`Queued Annotations for "${session.title}" (${batches.length} batches):\n`)
151
+ for (const [index, batch] of batches.entries()) {
152
+ console.log(`Batch ${index + 1} (${batch.batchID}) - Created ${batch.createdAt}:`)
153
+ console.log(batch.markdown)
154
+ console.log("\n--------------------------------------------------\n")
155
+ }
156
+ }
157
+
158
+ async function cmdTui(targetPath, options) {
159
+ const session = await resolveSession(options.session)
160
+ const binary = resolveAdaptedBinary(options.binary)
161
+ const brainDir = defaultBrainDir(session.conversationId)
162
+ const calledByAgent = Boolean(process.env.ANTIGRAVITY_AGENT || process.env.AGENT_TOOL_CALL)
163
+ const isInteractiveTTY = Boolean(options.interactiveTty) || (!calledByAgent && Boolean(process.stdin.isTTY) && !options.spawnWindow)
164
+
165
+ if (!isInteractiveTTY) {
166
+ const launcherScript = path.join(os.tmpdir(), `agy-annotate-launch-${Date.now()}.sh`)
167
+ const doneMarker = path.join(os.tmpdir(), `agy-annotate-done-${Date.now()}.txt`)
168
+ const cliScript = path.resolve(new URL(import.meta.url).pathname)
169
+ const tuiArgs = [cliScript, "tui", "--interactive-tty", "--session", session.conversationId]
170
+ if (targetPath) tuiArgs.push(targetPath)
171
+ if (options.binary) tuiArgs.push("--binary", options.binary)
172
+
173
+ const escapedTitle = (session.title || "Review").replace(/'/g, "'\\''")
174
+ const shellCmd = `printf '\\033]0;Annotate: %s\\007' '${escapedTitle}'\n${process.execPath} ${tuiArgs.map(a => `'${a.replace(/'/g, "'\\''")}'`).join(" ")}; echo done > '${doneMarker}'`
175
+ await writeFile(launcherScript, `#!/bin/sh\n${shellCmd}\n`, { mode: 0o755 })
176
+
177
+ const beforeBatches = await listPendingBatches(session.conversationId)
178
+
179
+ let launched = false
180
+ try {
181
+ const windowTitle = `Annotate: ${session.title}`
182
+ await execute("open", ["-na", "Ghostty", "--args", "--window-width=172", "--window-height=48", `--title=${windowTitle}`, "-e", launcherScript])
183
+ launched = true
184
+ } catch {
185
+ try {
186
+ await execute("osascript", ["-e", `tell application "Terminal" to do script "${launcherScript}"`, "-e", 'tell application "Terminal" to activate'])
187
+ launched = true
188
+ } catch (err) {
189
+ throw new Error(`Failed to spawn interactive review window: ${err.message}`)
190
+ }
191
+ }
192
+
193
+ console.log(`Opened interactive Plannotator TUI window for "${session.title}".`)
194
+ console.log("Waiting for user to complete annotations (press 'q' or Ctrl+S to finish)...")
195
+
196
+ for (let i = 0; i < 300; i++) {
197
+ await new Promise(r => setTimeout(r, 1000))
198
+ const currentBatches = await listPendingBatches(session.conversationId)
199
+ if (currentBatches.length > beforeBatches.length) {
200
+ const newest = currentBatches[currentBatches.length - 1]
201
+ console.log(`\n✓ Annotations received from review window:\n\n${newest.markdown}`)
202
+ try { await rm(launcherScript, { force: true }); await rm(doneMarker, { force: true }) } catch {}
203
+ return
204
+ }
205
+ try {
206
+ await readFile(doneMarker)
207
+ await new Promise(r => setTimeout(r, 500))
208
+ const finalBatches = await listPendingBatches(session.conversationId)
209
+ if (finalBatches.length > beforeBatches.length) {
210
+ const newest = finalBatches[finalBatches.length - 1]
211
+ console.log(`\n✓ Annotations received from review window:\n\n${newest.markdown}`)
212
+ } else {
213
+ console.log("Interactive review window closed without annotations.")
214
+ }
215
+ try { await rm(launcherScript, { force: true }); await rm(doneMarker, { force: true }) } catch {}
216
+ return
217
+ } catch {
218
+ // Still waiting
219
+ }
220
+ }
221
+ return
222
+ }
223
+
224
+ let sourceText = ""
225
+ let snapshotName = "last-reply.md"
226
+ let filePath = null
227
+ let sourceHash = null
228
+
229
+ if (targetPath) {
230
+ const resolvedPath = path.resolve(session.directory, targetPath)
231
+ sourceText = await readFile(resolvedPath, "utf8")
232
+ filePath = resolvedPath
233
+ snapshotName = path.basename(resolvedPath)
234
+ sourceHash = createHash("sha256").update(Buffer.from(sourceText)).digest("hex")
235
+ } else {
236
+ const replies = await extractAgyReplies(brainDir)
237
+ const latest = latestCompletedReply(replies)
238
+ if (!latest || !latest.text.trim()) {
239
+ throw new Error(`No completed assistant replies found in session "${session.title}".`)
240
+ }
241
+ sourceText = latest.text
242
+ snapshotName = `reply-${latest.id}.md`
243
+ }
244
+
245
+ const tempDir = await mkdtemp(path.join(os.tmpdir(), "agy-annotate-"))
246
+ const snapshotFile = path.join(tempDir, snapshotName)
247
+ const dataDir = path.join(tempDir, "data")
248
+ const intentPath = path.join(tempDir, "send-intent")
249
+
250
+ await mkdir(dataDir, { recursive: true, mode: 0o700 })
251
+ await writeFile(snapshotFile, sourceText, { mode: 0o600 })
252
+
253
+ let env = {
254
+ ...process.env,
255
+ PLANNOTATOR_DATA_DIR: dataDir,
256
+ PLANNOTATOR_FEEDBACK_HISTORY: "0",
257
+ PLANNOTATOR_TUI_SEND_INTENT: intentPath,
258
+ }
259
+
260
+ try {
261
+ env = await prepareTheme({
262
+ binary,
263
+ theme: getAdaptedThemeTokens(),
264
+ directory: tempDir,
265
+ env,
266
+ })
267
+ } catch {
268
+ // If binary does not support theme command, fallback to base env
269
+ }
270
+
271
+ // Browse in ASCII so an input method cannot swallow review keys; see input-source.mjs.
272
+ const inputSource = createInputSource()
273
+ const textSource = await inputSource.ascii()
274
+ if (inputSource.command && textSource) {
275
+ env.PLANNOTATOR_TUI_INPUT_SOURCE = inputSource.command
276
+ env.PLANNOTATOR_TUI_TEXT_INPUT_SOURCE = textSource
277
+ }
278
+
279
+ try {
280
+ // Run Plannotator interactively
281
+ const child = spawn(binary, [snapshotFile], {
282
+ cwd: tempDir,
283
+ env,
284
+ stdio: "inherit",
285
+ })
286
+
287
+ await new Promise((resolve, reject) => {
288
+ child.on("exit", (code, signal) => {
289
+ if (signal) reject(new Error(`TUI killed by signal ${signal}`))
290
+ else resolve(code)
291
+ })
292
+ child.on("error", reject)
293
+ }).finally(() => inputSource.select(textSource))
294
+
295
+ // Export annotations
296
+ const { stdout } = await execute(binary, ["--export", snapshotFile], {
297
+ cwd: tempDir,
298
+ env,
299
+ timeout: 15000,
300
+ })
301
+ const feedback = stdout.trim()
302
+
303
+ if (!feedback || feedback === "No annotations.") {
304
+ console.log("No annotations created. Returned to terminal.")
305
+ return
306
+ }
307
+
308
+ const header = filePath
309
+ ? `Annotations on document \`${filePath}\` (SHA-256: ${sourceHash}):`
310
+ : `Annotations on latest assistant response in session "${session.title}":`
311
+ const combined = `${header}\n\n${feedback}`
312
+
313
+ await enqueueAnnotations(session.conversationId, {
314
+ batchID: `tui-${Date.now()}`,
315
+ markdown: combined,
316
+ promptID: `msg_${randomUUID()}`,
317
+ })
318
+
319
+ console.log(`\n✓ Enqueued annotations for AGY session: "${session.title}"`)
320
+ console.log(` The next AGY turn or invocation will ingest this feedback.`)
321
+ } finally {
322
+ await rm(tempDir, { recursive: true, force: true })
323
+ }
324
+ }
325
+
326
+ async function main() {
327
+ const args = process.argv.slice(2)
328
+ if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
329
+ usage()
330
+ return
331
+ }
332
+
333
+ const command = args[0]
334
+ const options = {}
335
+ let posArg = null
336
+
337
+ for (let i = 1; i < args.length; i++) {
338
+ if (args[i] === "--session") {
339
+ options.session = args[++i]
340
+ } else if (args[i] === "--binary") {
341
+ options.binary = args[++i]
342
+ } else if (args[i] === "--interactive-tty") {
343
+ options.interactiveTty = true
344
+ } else if (!args[i].startsWith("-") && !posArg) {
345
+ posArg = args[i]
346
+ }
347
+ }
348
+
349
+ switch (command) {
350
+ case "status":
351
+ await cmdStatus()
352
+ break
353
+ case "web":
354
+ await cmdWeb(posArg, options)
355
+ break
356
+ case "tui":
357
+ await cmdTui(posArg, options)
358
+ break
359
+ case "queue":
360
+ await cmdQueue(options)
361
+ break
362
+ default:
363
+ console.error(`Unknown command: "${command}"`)
364
+ usage()
365
+ process.exit(1)
366
+ }
367
+ }
368
+
369
+ const isDirectExecution = process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])
370
+ if (isDirectExecution) {
371
+ main().catch(err => {
372
+ console.error(`Error: ${err.message}`)
373
+ process.exit(1)
374
+ })
375
+ }
@@ -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
+ }
package/agy/hooks.mjs ADDED
@@ -0,0 +1,100 @@
1
+ import { spawn } from "node:child_process"
2
+ import { fileURLToPath } from "node:url"
3
+ import path from "node:path"
4
+ import { dequeueAnnotations, defaultInboxRoot } from "./inbox.mjs"
5
+ import { listTargets, registryRoot } from "../bridge/receiver.mjs"
6
+
7
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
8
+
9
+ export async function readStdin() {
10
+ const chunks = []
11
+ for await (const chunk of process.stdin) {
12
+ chunks.push(chunk)
13
+ }
14
+ const text = Buffer.concat(chunks).toString("utf8").trim()
15
+ if (!text) return {}
16
+ try {
17
+ return JSON.parse(text)
18
+ } catch {
19
+ return {}
20
+ }
21
+ }
22
+
23
+ export async function handleSessionStart(payload, { root = registryRoot(), inboxRoot = defaultInboxRoot() } = {}) {
24
+ const conversationId = payload.conversationId
25
+ if (!conversationId) return {}
26
+
27
+ // Check if a receiver target is already registered for this session
28
+ const targets = await listTargets(root)
29
+ const exists = targets.some(t => t.sessionID === conversationId)
30
+ if (!exists) {
31
+ const dir = payload.workspacePaths?.[0] || process.cwd()
32
+ const daemonScript = path.join(__dirname, "daemon.mjs")
33
+ const args = ["--session", conversationId, "--dir", dir]
34
+ if (process.ppid) args.push("--pid", String(process.ppid))
35
+
36
+ const child = spawn(process.execPath, [daemonScript, ...args], {
37
+ detached: true,
38
+ stdio: "ignore",
39
+ })
40
+ child.unref()
41
+ }
42
+
43
+ return {}
44
+ }
45
+
46
+ export async function handlePreInvocation(payload, { inboxRoot = defaultInboxRoot() } = {}) {
47
+ const conversationId = payload.conversationId
48
+ if (!conversationId) return {}
49
+
50
+ const dequeued = await dequeueAnnotations(conversationId, inboxRoot)
51
+ if (!dequeued || !dequeued.combinedMarkdown.trim()) {
52
+ return {}
53
+ }
54
+
55
+ return {
56
+ injectSteps: [
57
+ {
58
+ userMessage: `# Delivered Annotations\n\n${dequeued.combinedMarkdown}`,
59
+ },
60
+ ],
61
+ }
62
+ }
63
+
64
+ export async function handleStop(payload, { inboxRoot = defaultInboxRoot() } = {}) {
65
+ const conversationId = payload.conversationId
66
+ if (!conversationId) return {}
67
+
68
+ const dequeued = await dequeueAnnotations(conversationId, inboxRoot)
69
+ if (!dequeued || !dequeued.combinedMarkdown.trim()) {
70
+ return {}
71
+ }
72
+
73
+ return {
74
+ decision: "continue",
75
+ reason: `Delivered annotations:\n\n${dequeued.combinedMarkdown}`,
76
+ }
77
+ }
78
+
79
+ export async function runHook(event, payload, options = {}) {
80
+ switch (event) {
81
+ case "SessionStart":
82
+ case "session-start":
83
+ return handleSessionStart(payload, options)
84
+ case "PreInvocation":
85
+ case "pre-invocation":
86
+ return handlePreInvocation(payload, options)
87
+ case "Stop":
88
+ case "stop":
89
+ return handleStop(payload, options)
90
+ default:
91
+ return {}
92
+ }
93
+ }
94
+
95
+ if (process.argv[1] && process.argv[1].endsWith("hooks.mjs")) {
96
+ const event = process.argv[2]
97
+ const payload = await readStdin()
98
+ const result = await runHook(event, payload)
99
+ process.stdout.write(JSON.stringify(result) + "\n")
100
+ }