@nxxxsooo/opencode-annotate 0.0.0-stage → 0.6.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 ADDED
@@ -0,0 +1,86 @@
1
+ # Changelog
2
+
3
+ ## 0.6.0 — annotate any session text
4
+
5
+ ### Text review
6
+
7
+ - Add `/annotate-pick` to choose among recent replies and mid-turn progress updates, and
8
+ `/annotate-selection` to review the message containing the last transcript selection.
9
+ - Move browser review to `/annotate-web` (pairing, URL, HTML file or `off`); `/annotate`
10
+ now handles replies and documents only. Retire numbered `/annotate N`.
11
+
12
+ ### Inherited TUI colors
13
+
14
+ - Add opt-in `inheritTheme` support for the color-capable Plannotator fork, including
15
+ the OpenCode canvas, text, Markdown, borders, selection and cursor contrast pairs.
16
+ Inherited colors also cover strong/emphasis text, list markers, rules, link labels,
17
+ table headers and the send button.
18
+ - Validate a private per-review configuration before suspending the terminal; preserve
19
+ the user's layout settings, including the fork's `doc_width`, and keep the themed
20
+ config with recoverable drafts.
21
+
22
+ ### Compact browser workspace
23
+
24
+ - Replace the always-expanded browser form with a selection-focused composer, numbered
25
+ note queue, and persistent destination/delivery bar; keep controls visible at narrow widths and zoom.
26
+ - Autosave unfinished feedback by page, recover it after navigation or panel reload, and
27
+ protect selection changes and competing-panel edits with explicit draft choices.
28
+ - Fix cancelling and reselecting the same element, add safe Show on page and revision-aware
29
+ deletion Undo, and keep the intended destination visible while disconnected.
30
+ - Show pending/sent counts, distinguish original-batch retries from new feedback, and move
31
+ copy/export/context utilities into More review options. **Save note** is now **Add note**.
32
+
33
+ ## 0.5.0 — new package name
34
+
35
+ - Publish as `@nxxxsooo/opencode-annotate` from `nxxxsooo/opencode-annotate`. The old
36
+ `opencode-plannotator-tui` package is deprecated; remove it and add the new one.
37
+ - No behavior changes from 0.4.2.
38
+
39
+ ## 0.4.2 — OpenCode Annotate
40
+
41
+ The project is now called OpenCode Annotate. It is still published as
42
+ `opencode-plannotator-tui`, because the npm name `opencode-annotate` belongs to an
43
+ unrelated package.
44
+
45
+ - Fix `/annotate` on OpenCode 2.1.1: the terminal stayed blank and Plannotator TUI
46
+ never opened, so Ctrl+C then quit the OpenCode client. The plugin now waits for
47
+ the renderer to suspend and resume.
48
+ - Add webpage review: `/annotate page.html`, `/annotate https://…`, `/annotate web`
49
+ and `/annotate web off`, with an Annotate HTML-derived Chrome companion and
50
+ exact-session Native Messaging delivery. Text review is unchanged.
51
+ - The browser companion shows live sessions automatically, preselects a sole target
52
+ without sending, saves the current note on **Send & continue**, keeps drafts per URL,
53
+ and filters private values and hidden text from exported context.
54
+
55
+ ## 0.3.0
56
+
57
+ - Select older completed replies with `/annotate 2`, `/annotate 3`, and so on.
58
+ Bare `/annotate` and `/annotate 1` still select the latest reply.
59
+ - Count only eligible completed text replies across history pages; report missing
60
+ replies and invalid numbers without opening a different source.
61
+ - `/annotate-last` now always selects the latest reply and ignores arguments.
62
+ **Migration:** replace `/annotate-last file.md` with `/annotate file.md`.
63
+ - Verify numbered feedback delivery and fixed latest-reply selection in the real
64
+ terminal smoke test, alongside 21 behavior tests.
65
+
66
+ ## 0.2.2
67
+
68
+ - All confirmation dialogs, status notices, errors, and the feedback header sent
69
+ to the assistant are now in English.
70
+
71
+ ## 0.2.1
72
+
73
+ - Use an English command description in the slash menu and command palette.
74
+ - Compare actual published file contents when checking an existing npm release,
75
+ avoiding false failures from platform-specific tar/gzip encoding.
76
+
77
+ ## 0.2.0
78
+
79
+ Initial public release of the OpenCode adapter for Plannotator TUI.
80
+
81
+ - `/annotate [file]` and `/annotate-last` for replies or local Markdown/text documents.
82
+ - Same-terminal handoff and confirmed feedback to the captured session.
83
+ - Paginated completed-reply lookup and isolated document snapshots.
84
+ - Original document path and snapshot hash included in feedback.
85
+ - Recovery drafts on failure and preservation of archived annotations.
86
+ - Fourteen behavior tests and real terminal/API smoke coverage.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 nxxxsooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,299 @@
1
- # Temporary Holding Version
1
+ # OpenCode Annotate
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@nxxxsooo/opencode-annotate)](https://www.npmjs.com/package/@nxxxsooo/opencode-annotate)
4
+ [![CI](https://github.com/nxxxsooo/opencode-annotate/actions/workflows/ci.yml/badge.svg)](https://github.com/nxxxsooo/opencode-annotate/actions/workflows/ci.yml)
5
+ [![MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE)
6
+
7
+ **Annotate replies, documents, or live HTML pages, then send feedback to the originating OpenCode session.**
8
+
9
+ This is an **unofficial OpenCode plugin**. [Plannotator TUI](https://github.com/plannotator/plannotator-tui)
10
+ provides text review; the [Annotate HTML-derived browser companion](browser/UPSTREAM.md)
11
+ provides webpage review. This repository owns explicit routing, native messaging,
12
+ session targeting, terminal handoff and confirmed feedback delivery.
13
+
14
+ Published on npm as `@nxxxsooo/opencode-annotate`. It replaces `opencode-plannotator-tui`
15
+ (0.4.2 and earlier); to switch, run
16
+ `opencode plugin remove opencode-plannotator-tui@latest` and then install this package as below.
17
+
18
+ ```text
19
+ /annotate Review the last completed assistant reply
20
+ /annotate docs/plan.md Review a Markdown document
21
+ /annotate "docs/release plan.md" Review a path containing spaces
22
+ /annotate ~/Documents/notes.txt Review a plain-text document
23
+ /annotate-pick Choose a recent reply or mid-turn progress update
24
+ /annotate-selection Review the message containing your last transcript selection
25
+ /annotate-web Open this session for browser pairing
26
+ /annotate-web page.html Review the specified local HTML in Chrome
27
+ /annotate-web https://example.com Review the specified webpage
28
+ /annotate-web off Revoke this session's browser pairing
29
+ ```
30
+
31
+ `/annotate-last` always reviews the latest completed reply; any supplied argument is ignored.
32
+
33
+ Progress updates written during a long tool run are not replies, so `/annotate` skips them.
34
+ Reach them with `/annotate-pick`, or drag over text in the transcript and run
35
+ `/annotate-selection`: the plugin opens the reply or progress update containing that text,
36
+ or just the selected text when it spans messages. Numbered `/annotate N` is retired.
37
+
38
+ ## Install
39
+
40
+ Requires **OpenCode 2.0.22+** and a separately installed `plannotator-tui` on your PATH.
41
+ Tested with OpenCode 2.1.2 and Plannotator TUI 0.9.4 on macOS; unit tests also run on
42
+ Linux. Windows terminal handoff has not been verified.
43
+
44
+ Install the upstream TUI on macOS or Linux:
45
+
46
+ ```sh
47
+ brew install plannotator/tap/plannotator-tui
48
+ ```
49
+
50
+ Homebrew 6 may first require `brew trust plannotator/tap`. Alternatively, use
51
+ `cargo install plannotator-tui --locked` or the upstream
52
+ [prebuilt binaries](https://github.com/plannotator/plannotator-tui/releases).
53
+
54
+ Then install the plugin:
55
+
56
+ ```sh
57
+ opencode plugin add @nxxxsooo/opencode-annotate@latest
58
+ ```
59
+
60
+ OpenCode detects its TUI-only entrypoint and adds it to your global **`cli.json`**.
61
+ It does not need a server-plugin entry. Reopen the terminal client if its command
62
+ list has not refreshed.
63
+
64
+ Manual configuration, preserving other entries:
65
+
66
+ ```json
67
+ {
68
+ "plugins": ["@nxxxsooo/opencode-annotate@latest"]
69
+ }
70
+ ```
71
+
72
+ ### Match OpenCode's colors (fork required)
73
+
74
+ Set `"inheritTheme": true` in the plugin's `options`, alongside `binary`. It requires
75
+ the extended color-capable Plannotator fork
76
+ ([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).
79
+
80
+ Each review uses OpenCode's current resolved colors for the canvas, text, Markdown,
81
+ borders, highlights, cursor and selection. The plugin asks the chosen binary for its
82
+ effective configuration, copies it into that review's private directory, and validates
83
+ the themed copy before taking over the terminal. Your original settings stay intact.
84
+ Launchers must honor an existing `PLANNOTATOR_TUI_CONFIG`.
85
+
86
+ ## Browser review (optional)
87
+
88
+ Requirements: macOS and Chrome 116+, plus Node 22+ for the native host.
89
+
90
+ 1. Clone this repository and load its `browser/` directory as an unpacked extension in
91
+ `chrome://extensions`. Allow file URL access if reviewing local HTML.
92
+ 2. Run `npm run install:bridge` in the clone to register the native host. It allows only this
93
+ companion's fixed extension ID and resolves Node absolutely. The host starts on demand and
94
+ opens no HTTP port.
95
+ 3. Reopen the OpenCode terminal client; the shared service needs no restart.
96
+
97
+ Run `/annotate-web` in a target session, then open the Chrome extension. A sole live
98
+ session is shown automatically; with several sessions, choose one once. Click the
99
+ destination beside **To** to change or refresh it. Its title stays visible beside Send,
100
+ including while disconnected, with its directory available on hover and in the chooser.
101
+ A sole target is only preselected: no binding or model turn occurs until
102
+ the user clicks **Send & continue**. A disconnected destination never silently switches to another session.
103
+
104
+ Choose **Pick element** or select text, then write a comment or question. The composer
105
+ appears for that selection. **Send N notes & continue** saves the current feedback and
106
+ sends pending notes in one action; **Add note** collects feedback locally for a batch.
107
+ Cmd/Ctrl+Enter adds a note or saves an edit. This sends pending notes to that captured
108
+ session and starts a normal model turn; pairing and saving notes make no model call.
109
+ Switching terminal tabs never changes the paired target. Revoke with `/annotate-web off`.
110
+
111
+ The numbered queue matches the page markers. Click a note's quoted target to show it
112
+ 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.
116
+
117
+ ### Explicit routing
118
+
119
+ `/annotate`, `/annotate-pick` and `/annotate-selection` always use the TUI; Markdown and
120
+ plain-text files do too. Only `/annotate-web` enters the browser workflow; passing a URL or
121
+ HTML file to `/annotate` points you there. A reply containing HTML links or code fences does
122
+ not change the default.
123
+
124
+ ### Browser safeguards and limitations
125
+
126
+ Written drafts autosave locally and restore after panel reload or a return to the same URL,
127
+ including SPA routes. Selecting another target with unfinished feedback offers **Add/Save
128
+ & switch**, **Keep editing**, or **Discard & switch**. Storage failures keep the input and
129
+ offer a retry; competing panels require an explicit choice of draft. Saved-note revision
130
+ checks likewise prevent stale tabs overwriting newer feedback. Full JSON/Markdown exports include
131
+ redacted URLs, exact selected text/context, verified selector hints, styles and accessibility.
132
+ Missing/changed/ambiguous targets are labeled in the sidebar instead of silently rebound.
133
+ Comments and drafts live in extension-owned UI/storage; the page receives only selection
134
+ metadata and numbered markers, not your written feedback.
135
+
136
+ Native delivery requires an open, paired local TUI. If the receiver closes, feedback stays
137
+ pending. A failed batch retains its original target and ID for safe retry; if that target
138
+ is permanently gone, export the notes before starting a new review. **Retry N notes &
139
+ 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,
142
+ cross-origin iframes, Canvas and remote SSH TUI clients are outside this version's scope.
143
+ Page Context is retired only after exporting its drafts and verifying this replacement.
144
+
145
+ See [implementation plan](docs/annotate-html-integration-plan.md) and
146
+ [shipped-artifact evaluation](docs/annotate-html-evaluation.md), plus
147
+ [browser provenance](browser/UPSTREAM.md). `npm test`, `npm run test:smoke`, and
148
+ `npm run test:browser` verify each layer; the browser test uses an existing Playwright installation
149
+ (`PLAYWRIGHT_MODULE`) and browser executable (`CHROMIUM_PATH`) in an isolated profile.
150
+
151
+ ### Reload after browser companion updates
152
+
153
+ After updating the unpacked `browser/` files, open `chrome://extensions` and click
154
+ **Reload** for **OpenCode Annotate**. Return to the target webpage and open Annotate
155
+ using its extension icon or **Alt+Shift+A**.
156
+
157
+ 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.
162
+ Saved extension-local data survives an extension reload.
163
+
164
+ For diagnosis, compare the running worker's source (DevTools/CDP
165
+ `Debugger.getScriptSource`) with `browser/worker.mjs` in the loaded checkout.
166
+ The manifest version alone cannot identify edits to an unpacked extension.
167
+
168
+ ## Review and send
169
+
170
+ 1. Run `/annotate` or `/annotate path/to/file.md` in a session.
171
+ 2. Select text by dragging, or press `v` and use movement keys.
172
+ 3. Press `c` to comment, `a` for “looks good,” or `d` to request deletion.
173
+ Without a selection, `c` comments on the current block. Enter saves a comment.
174
+ 4. Press **`q`** to return to OpenCode.
175
+ 5. Choose **Send and continue** to submit the annotations. Escape or **Cancel**
176
+ cancels.
177
+
178
+ The upstream **`E`** action copies to the clipboard. This adapter's automatic
179
+ delivery path is **q → confirm** and does not need clipboard access.
180
+
181
+ Opening a review makes no model call. Confirming sends a normal user prompt and
182
+ resumes the **original session**, even if the active tab changes. Empty and
183
+ cancelled reviews submit nothing.
184
+
185
+ ## What it reviews
186
+
187
+ **Replies:** the latest completed text reply, with paginated history lookup.
188
+ Reasoning, in-progress messages and tool-call commentary are excluded.
189
+ Pass a positive integer to select the Nth most recent eligible reply: `1` is the
190
+ default, `2` is the previous reply, and so on. If there are too few replies, the
191
+ plugin reports that instead of opening another reply.
192
+
193
+ **Documents:** local UTF-8 `.md`, `.mdx`, `.markdown` and `.txt` files up to 2 MiB.
194
+ Relative paths resolve against the captured session's working directory, not the
195
+ directory from which the terminal client happened to start. Absolute and `~/`
196
+ paths work too. The file must exist on the machine running the terminal client.
197
+
198
+ The TUI reads a fixed snapshot and does not edit the original document. Feedback
199
+ includes the original path and snapshot hash, with instructions to re-read the
200
+ current file before applying suggestions. Document review works even before the
201
+ session has an assistant reply.
202
+
203
+ ## Updates and uninstall
204
+
205
+ `@latest` selects the npm release channel. OpenCode caches installed packages;
206
+ it does not follow this repository's commits. Update just this plugin with:
207
+
208
+ ```sh
209
+ opencode plugin update @nxxxsooo/opencode-annotate@latest
210
+ ```
211
+
212
+ Reopen your terminal client to load updated package code. No shared background
213
+ service restart is required. Check the installed version with `opencode plugin list`.
214
+
215
+ To remove it:
216
+
217
+ ```sh
218
+ opencode plugin remove @nxxxsooo/opencode-annotate@latest
219
+ ```
220
+
221
+ ## Configuration
222
+
223
+ Set `binary` if Plannotator TUI is installed outside the terminal client's PATH:
224
+
225
+ ```json
226
+ {
227
+ "plugins": [
228
+ {
229
+ "package": "@nxxxsooo/opencode-annotate@latest",
230
+ "options": { "binary": "/path/to/plannotator-tui" }
231
+ }
232
+ ]
233
+ }
234
+ ```
235
+
236
+ The adapter launches Plannotator TUI in the current terminal, not through Herdr;
237
+ `[herdr]` placement and popup dimensions do not affect `/annotate`. Layout is
238
+ owned by the selected binary, while font family and size belong to the terminal.
239
+ The adapter supplies `PLANNOTATOR_TUI_THEME` to follow OpenCode's light/dark mode,
240
+ overriding Plannotator TUI's configured theme. Use `binary` to select a custom
241
+ build or launcher without replacing the system installation.
242
+
243
+ ## Draft recovery
244
+
245
+ Each review has its own private temporary source and annotation store. Successful,
246
+ empty and cancelled reviews are cleaned up. Failures and archived notes retain the
247
+ store, and a status message gives its directory.
248
+
249
+ `review.json` records the session, original source and relative `snapshot` path.
250
+ `feedback.md` holds exported feedback when available. To recover a retained review:
251
+
252
+ ```sh
253
+ PLANNOTATOR_DATA_DIR="<retained-directory>/data" \
254
+ plannotator-tui "<retained-directory>/<snapshot>"
255
+ ```
256
+
257
+ Use the `snapshot` value from `review.json`. Press `H` to restore archived notes,
258
+ then `E` to copy them for pasting into OpenCode. An upstream **E → F** archive is
259
+ preserved even when `--export` reports “No annotations.”
260
+
261
+ ## Development
262
+
263
+ ```sh
264
+ npm ci
265
+ npm run check
266
+ npm run test:smoke
267
+ ```
268
+
269
+ Unit tests use the real upstream annotation/export binary. The optional smoke test
270
+ also requires Python 3, tmux and OpenCode. It runs a detached terminal, verifies
271
+ commands and feedback through the actual API, then removes its test session.
272
+ Its submission uses `resume: false`, so it makes no model call or visible window.
273
+
274
+ Set `ANNOTATE_TUI_BINARY` to test a custom binary or launcher through the plugin's
275
+ real configuration path. For a build with a centered 120-column viewport, also
276
+ set `ANNOTATE_EXPECT_MARGIN=10` to assert blank margins in the 140-column smoke
277
+ terminal. These variables configure the test, not the shipped plugin.
278
+
279
+ For development loading, run `npm run install:plugin` to replace the npm entry in
280
+ `cli.json` with this checkout's absolute directory. It backs up the CLI preferences and
281
+ keeps `options.binary` and unrelated settings. Use only one installation at a time.
282
+
283
+ See [release instructions](docs/releasing.md) and [changelog](CHANGELOG.md).
284
+
285
+ ## 中文速用
286
+
287
+ 这是**非官方 OpenCode 批注插件**:文本用 Plannotator TUI,网页用 Chrome 伴随扩展。
288
+
289
+ - `/annotate`:批注上一条完整回复。
290
+ - `/annotate 文档.md`:批注文档,支持中文、空格和相对路径。
291
+ - `/annotate-pick`:从最近的回复和运行中的进度说明里选一条批注。
292
+ - `/annotate-selection`:先在会话里拖选文字,再批注包含这段文字的消息。
293
+ - `/annotate-last`:固定批注最新一条完整回复,忽略附带参数。
294
+ - `/annotate-web`:配对 Chrome;`/annotate-web 页面.html`、`/annotate-web https://…` 批注网页;`/annotate-web off` 撤销配对。
295
+ - 选中文字 → `c` 写批注 → Enter 保存 → `q` 返回 →「Send and continue」。
296
+ - 文档采用独立快照,反馈附原文件路径,确认后发回发起批注的会话。
297
+ - 更新:`opencode plugin update @nxxxsooo/opencode-annotate@latest`,然后重新打开终端客户端。
298
+
299
+ MIT licensed. The annotation UI is maintained upstream by the Plannotator project.
@@ -0,0 +1,29 @@
1
+ import { readFile } from "node:fs/promises"
2
+ import { decodeStream, encode, request } from "./wire.mjs"
3
+ import { listTargets } from "./receiver.mjs"
4
+
5
+ const configPath = process.argv[2]
6
+ const origin = process.argv[3]
7
+ const config = JSON.parse(await readFile(configPath, "utf8"))
8
+ if (origin !== `chrome-extension://${config.extensionID}/`) throw new Error("Unapproved extension origin")
9
+ let handled = false
10
+ const timeout = setTimeout(() => process.exit(1), 20000)
11
+ decodeStream(process.stdin, async message => {
12
+ if (handled) return
13
+ handled = true; process.stdin.pause()
14
+ let response
15
+ try {
16
+ const targets = await listTargets(config.targetsDirectory)
17
+ if (message.action === "targets") {
18
+ const live = await Promise.all(targets.map(async target => {
19
+ try { return (await request(target.socket, { action: "info", targetID: target.id })).target } catch { return null }
20
+ }))
21
+ response = { ok: true, targets: live.filter(Boolean) }
22
+ } else {
23
+ const target = targets.find(target => target.id === message.targetID)
24
+ if (!target) throw new Error("Paired session is offline; run /annotate web and pair again")
25
+ response = await request(target.socket, message)
26
+ }
27
+ } catch (error) { response = { ok: false, error: error.message } }
28
+ clearTimeout(timeout); process.stdout.end(encode(response))
29
+ }, error => { clearTimeout(timeout); process.stdout.end(encode({ ok: false, error: error.message })) })
@@ -0,0 +1,77 @@
1
+ import net from "node:net"
2
+ import { randomUUID, createHash } from "node:crypto"
3
+ import { mkdir, chmod, writeFile, readdir, readFile, rm, lstat } from "node:fs/promises"
4
+ import os from "node:os"
5
+ import path from "node:path"
6
+ import { encode, decodeStream } from "./wire.mjs"
7
+ import { markdown, validateReview } from "../browser/protocol.mjs"
8
+
9
+ export const registryRoot = () => path.join(os.homedir(), ".local/share/opencode-annotate/targets")
10
+ export async function listTargets(root = registryRoot()) {
11
+ let files
12
+ try { files = await readdir(root) } catch (error) { if (error.code === "ENOENT") return []; throw error }
13
+ const results = []
14
+ for (const file of files.filter(name => /^[a-f0-9-]+\.json$/.test(name))) {
15
+ const location = path.join(root, file)
16
+ const info = await lstat(location)
17
+ if (info.isSymbolicLink() || (info.mode & 0o077) || info.uid !== process.getuid() || info.size > 16384) continue
18
+ try {
19
+ const value = JSON.parse(await readFile(location, "utf8"))
20
+ if (typeof value.id !== "string" || file !== `${value.id}.json` || value.socket !== path.join(root, `${value.id}.sock`)) continue
21
+ try { process.kill(value.pid, 0) } catch { continue }
22
+ results.push(value)
23
+ } catch { /* stale/incomplete registration is not a target */ }
24
+ }
25
+ return results
26
+ }
27
+ export async function createReceiver({ sessionID, title, directory, client, root = registryRoot(), resume = true, onError = () => {} }) {
28
+ await mkdir(root, { recursive: true, mode: 0o700 }); await chmod(root, 0o700)
29
+ const id = randomUUID(), socketPath = path.join(root, `${id}.sock`)
30
+ // macOS sockaddr_un is limited to 104 bytes, including the NUL terminator.
31
+ if (Buffer.byteLength(socketPath) > 103) throw new Error("Annotation socket path is too long")
32
+ const target = { id, title, directory, sessionID, socket: socketPath, pid: process.pid }
33
+ const received = new Map(), sockets = new Set()
34
+ let closed = false
35
+ const server = net.createServer(socket => {
36
+ let handled = false
37
+ sockets.add(socket); socket.once("close", () => sockets.delete(socket)); socket.on("error", () => {})
38
+ socket.setTimeout(20000, () => socket.destroy())
39
+ decodeStream(socket, async message => {
40
+ if (handled) return
41
+ handled = true
42
+ try {
43
+ if (closed || message.targetID !== id) throw new Error("Pairing is no longer active")
44
+ if (message.action === "info") { await client.session.get({ sessionID }); socket.end(encode({ ok: true, target: { id, title, directory } })); return }
45
+ if (message.action !== "send" || !/^[a-f0-9-]{36}$/.test(message.batchID)) throw new Error("Invalid delivery request")
46
+ validateReview(message.review)
47
+ const digest = createHash("sha256").update(JSON.stringify(message.review)).digest("hex")
48
+ const existing = received.get(message.batchID)
49
+ if (existing && existing.digest !== digest) throw new Error("Batch ID was reused with different content")
50
+ if (!existing) {
51
+ // Capture immutable input before awaiting; simultaneous retries share one admission promise.
52
+ const promptID = `msg_${createHash("sha256").update(`${id}:${message.batchID}`).digest("hex").slice(0, 32)}`
53
+ const promise = (async () => {
54
+ await client.session.get({ sessionID })
55
+ const response = await client.session.prompt({ sessionID, id: promptID, text: markdown(message.review), delivery: "queue", resume })
56
+ return { ok: true, messageID: response?.id || promptID, state: "admitted" }
57
+ })()
58
+ received.set(message.batchID, { digest, promise })
59
+ promise.catch(() => received.delete(message.batchID))
60
+ }
61
+ socket.end(encode(await received.get(message.batchID).promise))
62
+ } catch (error) { if (!socket.destroyed) socket.end(encode({ ok: false, error: error.message })) }
63
+ }, () => socket.destroy())
64
+ })
65
+ await new Promise((resolve, reject) => { server.once("error", reject); server.listen(socketPath, resolve) })
66
+ server.on("error", onError)
67
+ await chmod(socketPath, 0o600)
68
+ const registration = path.join(root, `${id}.json`)
69
+ try { await writeFile(registration, JSON.stringify(target), { mode: 0o600, flag: "wx" }) }
70
+ catch (error) { await new Promise(resolve => server.close(resolve)); await rm(socketPath, { force: true }); throw error }
71
+ return { target, async close() {
72
+ if (closed) return
73
+ closed = true; for (const socket of sockets) socket.destroy()
74
+ await new Promise(resolve => server.close(resolve))
75
+ await rm(registration, { force: true }); await rm(socketPath, { force: true })
76
+ } }
77
+ }
@@ -0,0 +1,38 @@
1
+ import net from "node:net"
2
+ import { MAX_BYTES } from "../browser/protocol.mjs"
3
+
4
+ export function encode(value) {
5
+ const body = Buffer.from(JSON.stringify(value))
6
+ if (body.length > MAX_BYTES) throw new Error("Message exceeds 512 KiB")
7
+ const header = Buffer.alloc(4); header.writeUInt32LE(body.length)
8
+ return Buffer.concat([header, body])
9
+ }
10
+ export function decodeStream(stream, onMessage, onError) {
11
+ let buffer = Buffer.alloc(0), stopped = false
12
+ const data = chunk => {
13
+ if (stopped) return
14
+ try {
15
+ buffer = Buffer.concat([buffer, chunk])
16
+ while (buffer.length >= 4) {
17
+ const size = buffer.readUInt32LE(0)
18
+ if (!size || size > MAX_BYTES) throw new Error("Invalid frame size")
19
+ if (buffer.length < size + 4) break
20
+ const value = JSON.parse(buffer.subarray(4, size + 4).toString("utf8"))
21
+ buffer = buffer.subarray(size + 4); onMessage(value)
22
+ }
23
+ } catch (error) { stopped = true; onError(error) }
24
+ }
25
+ stream.on("data", data)
26
+ return () => { stopped = true; stream.off("data", data) }
27
+ }
28
+ export function request(socketPath, value) {
29
+ return new Promise((resolve, reject) => {
30
+ const socket = net.createConnection(socketPath)
31
+ const done = (error, result) => { stop(); socket.destroy(); error ? reject(error) : resolve(result) }
32
+ const stop = decodeStream(socket, result => done(null, result), error => done(error))
33
+ socket.setTimeout(15000, () => done(new Error("Annotation receiver timed out")))
34
+ socket.once("error", error => done(error))
35
+ socket.once("end", () => done(new Error("Annotation receiver disconnected")))
36
+ socket.once("connect", () => { try { socket.write(encode(value)) } catch (error) { done(error) } })
37
+ })
38
+ }
@@ -0,0 +1,9 @@
1
+ # Annotate HTML-derived browser companion
2
+
3
+ Based on Asim Sayed's MIT-licensed [Annotate HTML](https://github.com/AsimSayed/annotate-html), Chrome Web Store release 1.0.0 (extension ID `ageaediaogfbmbmjoamkcloagepjcgdp`).
4
+
5
+ `upstream/annotate-1.0.0.js` preserves the unmodified released JavaScript, SHA-256 `ae30233d0db847c21ced822c63ec5f0ead1c6f361518ec28a21ea49defcd1206`; its MIT license is adjacent. Icons are preserved from that release. The original implementation credits Agentation for its element-identification approach.
6
+
7
+ `inspector.js` adapts the original element identification, computed-style snapshot, and accessibility collectors. This local enhancement replaces the in-page comment popup and volatile state with an extension-origin side panel, durable per-note storage, exact range context and validated selectors. It adds complete export and opt-in paired session delivery. The original upstream implementation is not injected alongside the enhanced runtime.
8
+
9
+ This is a distinct local extension with its own ID, not an official Annotate HTML update. It has no upstream update URL, analytics or external data service. Only user-requested Native Messaging can send feedback to a paired local OpenCode client. Native Messaging and side-panel installation are macOS/Chrome-only in this version.