@nxxxsooo/opencode-annotate 0.7.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,17 @@
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
+
3
15
  ## 0.7.0 — one-key send and browser review rounds
4
16
 
5
17
  ### 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
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
+ }
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
+ }