@nxxxsooo/opencode-annotate 0.0.0-stage → 0.5.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 +56 -0
- package/LICENSE +21 -0
- package/README.md +247 -2
- package/bridge/native-host.mjs +29 -0
- package/bridge/receiver.mjs +77 -0
- package/bridge/wire.mjs +38 -0
- package/browser/UPSTREAM.md +9 -0
- package/browser/capture.js +96 -0
- package/browser/icons/icon-128.png +0 -0
- package/browser/icons/icon-16.png +0 -0
- package/browser/icons/icon-32.png +0 -0
- package/browser/icons/icon-48.png +0 -0
- package/browser/icons/icon.svg +3 -0
- package/browser/inspector.js +125 -0
- package/browser/manifest.json +13 -0
- package/browser/panel.css +3 -0
- package/browser/panel.html +23 -0
- package/browser/panel.mjs +155 -0
- package/browser/protocol.mjs +45 -0
- package/browser/upstream/LICENSE +21 -0
- package/browser/upstream/annotate-1.0.0.js +1910 -0
- package/browser/worker.mjs +105 -0
- package/package.json +64 -4
- package/review.mjs +252 -0
- package/scripts/install-bridge.mjs +27 -0
- package/scripts/install-plugin.mjs +34 -0
- package/scripts/migrate-page-context.mjs +31 -0
- package/targets.mjs +32 -0
- package/tui.ts +42 -0
- package/web-review.mjs +36 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.5.0 — new package name
|
|
4
|
+
|
|
5
|
+
- Publish as `@nxxxsooo/opencode-annotate` from `nxxxsooo/opencode-annotate`. The old
|
|
6
|
+
`opencode-plannotator-tui` package is deprecated; remove it and add the new one.
|
|
7
|
+
- No behavior changes from 0.4.2.
|
|
8
|
+
|
|
9
|
+
## 0.4.2 — OpenCode Annotate
|
|
10
|
+
|
|
11
|
+
The project is now called OpenCode Annotate. It is still published as
|
|
12
|
+
`opencode-plannotator-tui`, because the npm name `opencode-annotate` belongs to an
|
|
13
|
+
unrelated package.
|
|
14
|
+
|
|
15
|
+
- Fix `/annotate` on OpenCode 2.1.1: the terminal stayed blank and Plannotator TUI
|
|
16
|
+
never opened, so Ctrl+C then quit the OpenCode client. The plugin now waits for
|
|
17
|
+
the renderer to suspend and resume.
|
|
18
|
+
- Add webpage review: `/annotate page.html`, `/annotate https://…`, `/annotate web`
|
|
19
|
+
and `/annotate web off`, with an Annotate HTML-derived Chrome companion and
|
|
20
|
+
exact-session Native Messaging delivery. Text review is unchanged.
|
|
21
|
+
- The browser companion shows live sessions automatically, preselects a sole target
|
|
22
|
+
without sending, saves the current note on **Send & continue**, keeps drafts per URL,
|
|
23
|
+
and filters private values and hidden text from exported context.
|
|
24
|
+
|
|
25
|
+
## 0.3.0
|
|
26
|
+
|
|
27
|
+
- Select older completed replies with `/annotate 2`, `/annotate 3`, and so on.
|
|
28
|
+
Bare `/annotate` and `/annotate 1` still select the latest reply.
|
|
29
|
+
- Count only eligible completed text replies across history pages; report missing
|
|
30
|
+
replies and invalid numbers without opening a different source.
|
|
31
|
+
- `/annotate-last` now always selects the latest reply and ignores arguments.
|
|
32
|
+
**Migration:** replace `/annotate-last file.md` with `/annotate file.md`.
|
|
33
|
+
- Verify numbered feedback delivery and fixed latest-reply selection in the real
|
|
34
|
+
terminal smoke test, alongside 21 behavior tests.
|
|
35
|
+
|
|
36
|
+
## 0.2.2
|
|
37
|
+
|
|
38
|
+
- All confirmation dialogs, status notices, errors, and the feedback header sent
|
|
39
|
+
to the assistant are now in English.
|
|
40
|
+
|
|
41
|
+
## 0.2.1
|
|
42
|
+
|
|
43
|
+
- Use an English command description in the slash menu and command palette.
|
|
44
|
+
- Compare actual published file contents when checking an existing npm release,
|
|
45
|
+
avoiding false failures from platform-specific tar/gzip encoding.
|
|
46
|
+
|
|
47
|
+
## 0.2.0
|
|
48
|
+
|
|
49
|
+
Initial public release of the OpenCode adapter for Plannotator TUI.
|
|
50
|
+
|
|
51
|
+
- `/annotate [file]` and `/annotate-last` for replies or local Markdown/text documents.
|
|
52
|
+
- Same-terminal handoff and confirmed feedback to the captured session.
|
|
53
|
+
- Paginated completed-reply lookup and isolated document snapshots.
|
|
54
|
+
- Original document path and snapshot hash included in feedback.
|
|
55
|
+
- Recovery drafts on failure and preservation of archived annotations.
|
|
56
|
+
- 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,248 @@
|
|
|
1
|
-
#
|
|
1
|
+
# OpenCode Annotate
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@nxxxsooo/opencode-annotate)
|
|
4
|
+
[](https://github.com/nxxxsooo/opencode-annotate/actions/workflows/ci.yml)
|
|
5
|
+
[](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 2 Review the second most recent reply
|
|
21
|
+
/annotate 3 Review the third most recent reply
|
|
22
|
+
/annotate docs/plan.md Review a Markdown document
|
|
23
|
+
/annotate "docs/release plan.md" Review a path containing spaces
|
|
24
|
+
/annotate ~/Documents/notes.txt Review a plain-text document
|
|
25
|
+
/annotate page.html Review the specified local HTML in Chrome
|
|
26
|
+
/annotate https://example.com Review the specified webpage
|
|
27
|
+
/annotate web Open this session for browser pairing
|
|
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
|
+
## Install
|
|
34
|
+
|
|
35
|
+
Requires **OpenCode 2.0.22+** and a separately installed `plannotator-tui` on your PATH.
|
|
36
|
+
Tested with OpenCode 2.1.1 and Plannotator TUI 0.9.4 on macOS; unit tests also run on
|
|
37
|
+
Linux. Windows terminal handoff has not been verified.
|
|
38
|
+
|
|
39
|
+
Install the upstream TUI on macOS or Linux:
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
brew install plannotator/tap/plannotator-tui
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Homebrew 6 may first require `brew trust plannotator/tap`. Alternatively, use
|
|
46
|
+
`cargo install plannotator-tui --locked` or the upstream
|
|
47
|
+
[prebuilt binaries](https://github.com/plannotator/plannotator-tui/releases).
|
|
48
|
+
|
|
49
|
+
Then install the plugin:
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
opencode plugin add @nxxxsooo/opencode-annotate@latest
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
OpenCode detects its TUI-only entrypoint and adds it to your global **`cli.json`**.
|
|
56
|
+
It does not need a server-plugin entry. Reopen the terminal client if its command
|
|
57
|
+
list has not refreshed.
|
|
58
|
+
|
|
59
|
+
Manual configuration, preserving other entries:
|
|
60
|
+
|
|
61
|
+
```json
|
|
62
|
+
{
|
|
63
|
+
"plugins": ["@nxxxsooo/opencode-annotate@latest"]
|
|
64
|
+
}
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
## Browser review (optional)
|
|
68
|
+
|
|
69
|
+
Requirements: macOS and Chrome 116+, plus Node 22+ for the native host.
|
|
70
|
+
|
|
71
|
+
1. Clone this repository and load its `browser/` directory as an unpacked extension in
|
|
72
|
+
`chrome://extensions`. Allow file URL access if reviewing local HTML.
|
|
73
|
+
2. Run `npm run install:bridge` in the clone to register the native host. It allows only this
|
|
74
|
+
companion's fixed extension ID and resolves Node absolutely. The host starts on demand and
|
|
75
|
+
opens no HTTP port.
|
|
76
|
+
3. Reopen the OpenCode terminal client; the shared service needs no restart.
|
|
77
|
+
|
|
78
|
+
Run `/annotate web` in a target session, then open the Chrome extension. A sole live
|
|
79
|
+
session is shown automatically; with several sessions, choose one once. **Change**
|
|
80
|
+
opens the optional session selector. The target title is always visible, with its directory
|
|
81
|
+
available on hover. A sole target is only preselected: no binding or model turn occurs until
|
|
82
|
+
the user clicks **Send & continue**. A disconnected destination never silently switches to another session.
|
|
83
|
+
|
|
84
|
+
Pick an element or select text, write feedback, then click **Send & continue**. It saves
|
|
85
|
+
the current feedback and sends it in one action; **Save note** remains available for batching.
|
|
86
|
+
This sends pending notes to that captured
|
|
87
|
+
session and starts a normal model turn; pairing and saving notes make no model call.
|
|
88
|
+
Switching terminal tabs never changes the paired target. Revoke with `/annotate web off`.
|
|
89
|
+
|
|
90
|
+
### Explicit routing
|
|
91
|
+
|
|
92
|
+
No argument or a reply number always means TUI. Markdown/plain text files also use TUI.
|
|
93
|
+
Only explicit `.html`/`.htm` paths, HTTP/HTTPS URLs, HTML file URLs, or `web` enter the browser
|
|
94
|
+
workflow. A reply containing HTML links or code fences does not change the default.
|
|
95
|
+
|
|
96
|
+
### Browser safeguards and limitations
|
|
97
|
+
|
|
98
|
+
Saved notes survive reloads and are isolated by URL, including SPA routes. Per-note revision
|
|
99
|
+
checks prevent stale tabs overwriting newer feedback. Full JSON/Markdown exports include
|
|
100
|
+
redacted URLs, exact selected text/context, verified selector hints, styles and accessibility.
|
|
101
|
+
Missing/changed/ambiguous targets are labeled in the sidebar instead of silently rebound.
|
|
102
|
+
Comments and drafts live in extension-owned UI/storage; the page receives only selection
|
|
103
|
+
metadata and numbered markers, not your written feedback.
|
|
104
|
+
|
|
105
|
+
Native delivery requires an open, paired local TUI. If the receiver closes, feedback stays
|
|
106
|
+
pending. A failed batch retains its original target and ID for safe retry; if that target
|
|
107
|
+
is permanently gone, export the notes before starting a new review. Sent-note edits become
|
|
108
|
+
new revisions. Clipboard failures expose a selectable preview. Browser-internal pages, PDF,
|
|
109
|
+
cross-origin iframes, Canvas and remote SSH TUI clients are outside this version's scope.
|
|
110
|
+
Page Context is retired only after exporting its drafts and verifying this replacement.
|
|
111
|
+
|
|
112
|
+
See [implementation plan](docs/annotate-html-integration-plan.md) and
|
|
113
|
+
[shipped-artifact evaluation](docs/annotate-html-evaluation.md), plus
|
|
114
|
+
[browser provenance](browser/UPSTREAM.md). `npm test`, `npm run test:smoke`, and
|
|
115
|
+
`npm run test:browser` verify each layer; the browser test uses an existing Playwright installation
|
|
116
|
+
(`PLAYWRIGHT_MODULE`) and browser executable (`CHROMIUM_PATH`) in an isolated profile.
|
|
117
|
+
|
|
118
|
+
## Review and send
|
|
119
|
+
|
|
120
|
+
1. Run `/annotate` or `/annotate path/to/file.md` in a session.
|
|
121
|
+
2. Select text by dragging, or press `v` and use movement keys.
|
|
122
|
+
3. Press `c` to comment, `a` for “looks good,” or `d` to request deletion.
|
|
123
|
+
Without a selection, `c` comments on the current block. Enter saves a comment.
|
|
124
|
+
4. Press **`q`** to return to OpenCode.
|
|
125
|
+
5. Choose **Send and continue** to submit the annotations. Escape or **Cancel**
|
|
126
|
+
cancels.
|
|
127
|
+
|
|
128
|
+
The upstream **`E`** action copies to the clipboard. This adapter's automatic
|
|
129
|
+
delivery path is **q → confirm** and does not need clipboard access.
|
|
130
|
+
|
|
131
|
+
Opening a review makes no model call. Confirming sends a normal user prompt and
|
|
132
|
+
resumes the **original session**, even if the active tab changes. Empty and
|
|
133
|
+
cancelled reviews submit nothing.
|
|
134
|
+
|
|
135
|
+
## What it reviews
|
|
136
|
+
|
|
137
|
+
**Replies:** the latest completed text reply, with paginated history lookup.
|
|
138
|
+
Reasoning, in-progress messages and tool-call commentary are excluded.
|
|
139
|
+
Pass a positive integer to select the Nth most recent eligible reply: `1` is the
|
|
140
|
+
default, `2` is the previous reply, and so on. If there are too few replies, the
|
|
141
|
+
plugin reports that instead of opening another reply.
|
|
142
|
+
|
|
143
|
+
**Documents:** local UTF-8 `.md`, `.mdx`, `.markdown` and `.txt` files up to 2 MiB.
|
|
144
|
+
Relative paths resolve against the captured session's working directory, not the
|
|
145
|
+
directory from which the terminal client happened to start. Absolute and `~/`
|
|
146
|
+
paths work too. The file must exist on the machine running the terminal client.
|
|
147
|
+
|
|
148
|
+
The TUI reads a fixed snapshot and does not edit the original document. Feedback
|
|
149
|
+
includes the original path and snapshot hash, with instructions to re-read the
|
|
150
|
+
current file before applying suggestions. Document review works even before the
|
|
151
|
+
session has an assistant reply.
|
|
152
|
+
|
|
153
|
+
## Updates and uninstall
|
|
154
|
+
|
|
155
|
+
`@latest` selects the npm release channel. OpenCode caches installed packages;
|
|
156
|
+
it does not follow this repository's commits. Update just this plugin with:
|
|
157
|
+
|
|
158
|
+
```sh
|
|
159
|
+
opencode plugin update @nxxxsooo/opencode-annotate@latest
|
|
160
|
+
```
|
|
161
|
+
|
|
162
|
+
Reopen your terminal client to load updated package code. No shared background
|
|
163
|
+
service restart is required. Check the installed version with `opencode plugin list`.
|
|
164
|
+
|
|
165
|
+
To remove it:
|
|
166
|
+
|
|
167
|
+
```sh
|
|
168
|
+
opencode plugin remove @nxxxsooo/opencode-annotate@latest
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Configuration
|
|
172
|
+
|
|
173
|
+
Set `binary` if Plannotator TUI is installed outside the terminal client's PATH:
|
|
174
|
+
|
|
175
|
+
```json
|
|
176
|
+
{
|
|
177
|
+
"plugins": [
|
|
178
|
+
{
|
|
179
|
+
"package": "@nxxxsooo/opencode-annotate@latest",
|
|
180
|
+
"options": { "binary": "/path/to/plannotator-tui" }
|
|
181
|
+
}
|
|
182
|
+
]
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
The adapter launches Plannotator TUI in the current terminal, not through Herdr;
|
|
187
|
+
`[herdr]` placement and popup dimensions do not affect `/annotate`. Layout is
|
|
188
|
+
owned by the selected binary, while font family and size belong to the terminal.
|
|
189
|
+
The adapter supplies `PLANNOTATOR_TUI_THEME` to follow OpenCode's light/dark mode,
|
|
190
|
+
overriding Plannotator TUI's configured theme. Use `binary` to select a custom
|
|
191
|
+
build or launcher without replacing the system installation.
|
|
192
|
+
|
|
193
|
+
## Draft recovery
|
|
194
|
+
|
|
195
|
+
Each review has its own private temporary source and annotation store. Successful,
|
|
196
|
+
empty and cancelled reviews are cleaned up. Failures and archived notes retain the
|
|
197
|
+
store, and a status message gives its directory.
|
|
198
|
+
|
|
199
|
+
`review.json` records the session, original source and relative `snapshot` path.
|
|
200
|
+
`feedback.md` holds exported feedback when available. To recover a retained review:
|
|
201
|
+
|
|
202
|
+
```sh
|
|
203
|
+
PLANNOTATOR_DATA_DIR="<retained-directory>/data" \
|
|
204
|
+
plannotator-tui "<retained-directory>/<snapshot>"
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Use the `snapshot` value from `review.json`. Press `H` to restore archived notes,
|
|
208
|
+
then `E` to copy them for pasting into OpenCode. An upstream **E → F** archive is
|
|
209
|
+
preserved even when `--export` reports “No annotations.”
|
|
210
|
+
|
|
211
|
+
## Development
|
|
212
|
+
|
|
213
|
+
```sh
|
|
214
|
+
npm ci
|
|
215
|
+
npm run check
|
|
216
|
+
npm run test:smoke
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
Unit tests use the real upstream annotation/export binary. The optional smoke test
|
|
220
|
+
also requires Python 3, tmux and OpenCode. It runs a detached terminal, verifies
|
|
221
|
+
commands and feedback through the actual API, then removes its test session.
|
|
222
|
+
Its submission uses `resume: false`, so it makes no model call or visible window.
|
|
223
|
+
|
|
224
|
+
Set `ANNOTATE_TUI_BINARY` to test a custom binary or launcher through the plugin's
|
|
225
|
+
real configuration path. For a build with a centered 120-column viewport, also
|
|
226
|
+
set `ANNOTATE_EXPECT_MARGIN=10` to assert blank margins in the 140-column smoke
|
|
227
|
+
terminal. These variables configure the test, not the shipped plugin.
|
|
228
|
+
|
|
229
|
+
For development loading, run `npm run install:plugin` to replace the npm entry in
|
|
230
|
+
`cli.json` with this checkout's absolute directory. It backs up the CLI preferences and
|
|
231
|
+
keeps `options.binary` and unrelated settings. Use only one installation at a time.
|
|
232
|
+
|
|
233
|
+
See [release instructions](docs/releasing.md) and [changelog](CHANGELOG.md).
|
|
234
|
+
|
|
235
|
+
## 中文速用
|
|
236
|
+
|
|
237
|
+
这是**非官方 OpenCode 批注插件**:文本用 Plannotator TUI,网页用 Chrome 伴随扩展。
|
|
238
|
+
|
|
239
|
+
- `/annotate`:批注上一条完整回复。
|
|
240
|
+
- `/annotate 2`:批注倒数第二条,`3`、`4` 依次往前;`1` 等同于默认。
|
|
241
|
+
- `/annotate 文档.md`:批注文档,支持中文、空格和相对路径。
|
|
242
|
+
- `/annotate-last`:固定批注最新一条完整回复,忽略附带参数。
|
|
243
|
+
- `/annotate 页面.html`、`/annotate https://…`、`/annotate web`:在 Chrome 中批注网页;`/annotate web off` 撤销配对。
|
|
244
|
+
- 选中文字 → `c` 写批注 → Enter 保存 → `q` 返回 →「Send and continue」。
|
|
245
|
+
- 文档采用独立快照,反馈附原文件路径,确认后发回发起批注的会话。
|
|
246
|
+
- 更新:`opencode plugin update @nxxxsooo/opencode-annotate@latest`,然后重新打开终端客户端。
|
|
247
|
+
|
|
248
|
+
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
|
+
}
|
package/bridge/wire.mjs
ADDED
|
@@ -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.
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
if (globalThis.__opencodeAnnotate === true) throw new Error("Refresh this page once to update annotation tools. Saved notes will remain.")
|
|
3
|
+
globalThis.__opencodeAnnotate?.dispose()
|
|
4
|
+
if (!["text/html", "application/xhtml+xml"].includes(document.contentType)) throw new Error("Only HTML pages are supported")
|
|
5
|
+
const listeners = new AbortController()
|
|
6
|
+
const on = (target, event, handler, options = {}) => target.addEventListener(event, handler, { ...options, signal: listeners.signal })
|
|
7
|
+
const host = document.createElement("div")
|
|
8
|
+
host.setAttribute("data-opencode-annotate", "")
|
|
9
|
+
host.style.cssText = "all:initial!important;position:fixed!important;inset:0!important;pointer-events:none!important;z-index:2147483647!important"
|
|
10
|
+
const root = host.attachShadow({ mode: "closed" })
|
|
11
|
+
const style = document.createElement("style")
|
|
12
|
+
style.textContent = '.box{position:fixed;pointer-events:none;border:2px solid #c96442;background:#c9644210}.pin{position:fixed;background:#c96442;color:#fff;border:2px solid #fff;border-radius:50%;font:600 12px system-ui;width:26px;height:26px;pointer-events:none}'
|
|
13
|
+
root.append(style); document.documentElement.append(host)
|
|
14
|
+
const box = document.createElement("div"); box.className = "box"
|
|
15
|
+
let picking = false, url = location.href, timer, markers = [], active = true
|
|
16
|
+
function send(anchor = null, error = null, modeOnly = false) {
|
|
17
|
+
if (!active) return
|
|
18
|
+
try {
|
|
19
|
+
chrome.runtime.sendMessage({ action: "capture", page: { url: location.href, title: document.title }, anchor, error, picking, modeOnly }).catch(dispose)
|
|
20
|
+
} catch { dispose() }
|
|
21
|
+
}
|
|
22
|
+
function setPicking(value, notify = true) {
|
|
23
|
+
picking = value
|
|
24
|
+
if (picking) root.append(box); else box.remove()
|
|
25
|
+
if (notify) send(null, null, true)
|
|
26
|
+
}
|
|
27
|
+
function selection() {
|
|
28
|
+
if (picking || !active) return
|
|
29
|
+
const selected = getSelection()
|
|
30
|
+
if (!selected?.rangeCount || selected.isCollapsed || selected.anchorNode?.getRootNode() !== document) return
|
|
31
|
+
const range = selected.getRangeAt(0).cloneRange()
|
|
32
|
+
let element = range.commonAncestorContainer
|
|
33
|
+
if (element.nodeType !== 1) element = element.parentElement
|
|
34
|
+
try { send(AnnotateInspector.capture(element, range)) } catch (error) { send(null, error.message) }
|
|
35
|
+
}
|
|
36
|
+
on(document, "selectionchange", () => { clearTimeout(timer); timer = setTimeout(selection, 160) })
|
|
37
|
+
on(document, "pointerup", selection)
|
|
38
|
+
on(document, "mousemove", event => {
|
|
39
|
+
if (!picking) return
|
|
40
|
+
const rect = event.target.getBoundingClientRect()
|
|
41
|
+
box.style.cssText = `left:${rect.x}px;top:${rect.y}px;width:${rect.width}px;height:${rect.height}px`
|
|
42
|
+
}, { capture: true })
|
|
43
|
+
on(document, "pointerdown", event => { if (picking) { event.preventDefault(); event.stopImmediatePropagation() } }, { capture: true })
|
|
44
|
+
on(document, "click", event => {
|
|
45
|
+
if (!picking) return
|
|
46
|
+
event.preventDefault(); event.stopImmediatePropagation()
|
|
47
|
+
// A failed pick must never leave the page trapped in interception mode.
|
|
48
|
+
setPicking(false, false)
|
|
49
|
+
try { send(AnnotateInspector.capture(event.target)) } catch (error) { send(null, error.message) }
|
|
50
|
+
}, { capture: true })
|
|
51
|
+
on(document, "keydown", event => { if (picking && event.key === "Escape") setPicking(false) })
|
|
52
|
+
const onMessage = (message, _sender, respond) => {
|
|
53
|
+
if (message.action === "pick") { setPicking(!picking); respond({ ok: true, picking }) }
|
|
54
|
+
if (message.action === "markers") { markers = message.notes || []; draw(); respond({ ok: true }) }
|
|
55
|
+
if (message.action === "locate") respond({ states: message.anchors.map(locate) })
|
|
56
|
+
}
|
|
57
|
+
chrome.runtime.onMessage.addListener(onMessage)
|
|
58
|
+
function locate(anchor) {
|
|
59
|
+
try {
|
|
60
|
+
const matches = document.querySelectorAll(anchor.selector)
|
|
61
|
+
if (matches.length !== 1) return matches.length ? "ambiguous" : "missing"
|
|
62
|
+
const text = AnnotateInspector.text(matches[0])
|
|
63
|
+
if (!text.includes(anchor.quote)) return "changed"
|
|
64
|
+
if (anchor.type === "text" && text.split(anchor.quote).length > 2) {
|
|
65
|
+
if (!text.includes(`${anchor.prefix || ""}${anchor.quote}${anchor.suffix || ""}`)) return "ambiguous"
|
|
66
|
+
}
|
|
67
|
+
return "located"
|
|
68
|
+
} catch { return "invalid selector" }
|
|
69
|
+
}
|
|
70
|
+
function draw() {
|
|
71
|
+
root.querySelectorAll(".pin").forEach(node => node.remove())
|
|
72
|
+
for (const [index, note] of markers.entries()) {
|
|
73
|
+
let matches
|
|
74
|
+
try { matches = document.querySelectorAll(note.anchor.selector) } catch { continue }
|
|
75
|
+
if (matches.length !== 1) continue
|
|
76
|
+
const element = matches[0]
|
|
77
|
+
// A changed or removed quote is an orphan, not another equally named element.
|
|
78
|
+
if (!AnnotateInspector.text(element).includes(note.anchor.quote)) continue
|
|
79
|
+
const rect = element.getBoundingClientRect()
|
|
80
|
+
const pin = document.createElement("span"); pin.className = "pin"; pin.textContent = String(index + 1)
|
|
81
|
+
pin.style.cssText = `left:${rect.left - 10}px;top:${rect.top - 10}px`; root.append(pin)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
on(window, "scroll", draw, { passive: true }); on(window, "resize", draw)
|
|
85
|
+
const observer = new MutationObserver(() => { clearTimeout(timer); timer = setTimeout(draw, 160) })
|
|
86
|
+
observer.observe(document.body, { childList: true, subtree: true, characterData: true })
|
|
87
|
+
const routeTimer = setInterval(() => { if (!active) { observer.disconnect(); return } if (url !== location.href) { url = location.href; markers = []; draw(); send() } }, 700)
|
|
88
|
+
function dispose() {
|
|
89
|
+
if (!active) return
|
|
90
|
+
active = false; listeners.abort(); clearInterval(routeTimer); clearTimeout(timer); observer.disconnect(); host.remove()
|
|
91
|
+
try { chrome.runtime.onMessage.removeListener(onMessage) } catch { /* previous extension context may already be invalidated */ }
|
|
92
|
+
delete globalThis.__opencodeAnnotate
|
|
93
|
+
}
|
|
94
|
+
globalThis.__opencodeAnnotate = { dispose }
|
|
95
|
+
send()
|
|
96
|
+
})();
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 155 157" width="128" height="128">
|
|
2
|
+
<path d="M58.8282 156.513L62.2248 103.934L18.2055 133.416L0 101.353L47.4158 78.2565L0 55.1599L18.2055 23.0965L62.2248 52.5786L58.8282 0H95.3751L91.8427 52.5786L135.862 23.0965L154.067 55.1599L106.787 78.2565L154.067 101.353L135.862 133.416L91.8427 103.934L95.3751 156.513H58.8282Z" fill="#C96442"/>
|
|
3
|
+
</svg>
|