@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 +86 -0
- package/LICENSE +21 -0
- package/README.md +298 -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 +116 -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 +114 -0
- package/browser/panel.html +56 -0
- package/browser/panel.mjs +435 -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 +183 -0
- package/package.json +65 -4
- package/review.mjs +327 -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/theme.mjs +115 -0
- package/tui.ts +66 -0
- package/web-review.mjs +36 -0
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { HOST, safeUrl, validateReview } from "./protocol.mjs"
|
|
2
|
+
|
|
3
|
+
const pageKey = async url => [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(url)))].map(v => v.toString(16).padStart(2, "0")).join("")
|
|
4
|
+
let writes = Promise.resolve()
|
|
5
|
+
const serial = fn => { const next = writes.then(fn); writes = next.catch(() => {}); return next }
|
|
6
|
+
async function activate(tab) {
|
|
7
|
+
if (!tab?.id || !/^(https?|file):/.test(tab.url || "")) throw new Error("Open an ordinary webpage or authorized local HTML")
|
|
8
|
+
await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: ["inspector.js", "capture.js"] })
|
|
9
|
+
await chrome.storage.session.set({ [`tab:${tab.id}`]: { page: { url: safeUrl(tab.url), title: tab.title || "Page" }, anchor: null } })
|
|
10
|
+
}
|
|
11
|
+
chrome.action.onClicked.addListener(tab => {
|
|
12
|
+
// open() must retain the browser's action user gesture, before asynchronous injection.
|
|
13
|
+
chrome.sidePanel.open({ tabId: tab.id }).catch(console.error)
|
|
14
|
+
activate(tab).catch(async error => { await chrome.storage.session.set({ [`tab:${tab.id}`]: { error: error.message } }) })
|
|
15
|
+
})
|
|
16
|
+
async function current() {
|
|
17
|
+
const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true })
|
|
18
|
+
if (!tab) throw new Error("No active page")
|
|
19
|
+
const state = (await chrome.storage.session.get(`tab:${tab.id}`))[`tab:${tab.id}`]
|
|
20
|
+
if (!state?.page) throw new Error(state?.error || "Click the extension icon on this page to grant access")
|
|
21
|
+
const hash = await pageKey(state.page.url)
|
|
22
|
+
const storage = await chrome.storage.local.get(null)
|
|
23
|
+
const notes = Object.entries(storage).filter(([key, value]) => key.startsWith(`note:${hash}:`) && !value.deleted).map(([, value]) => value).sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id))
|
|
24
|
+
let anchorStates = notes.map(() => "unavailable")
|
|
25
|
+
try { anchorStates = (await chrome.tabs.sendMessage(tab.id, { action: "locate", anchors: notes.map(note => note.anchor) })).states } catch { /* visibly unavailable while navigating */ }
|
|
26
|
+
const draft = storage[`draft:${hash}`] || { revision: 0, value: null }
|
|
27
|
+
const outbox = storage[`outbox:${hash}`]
|
|
28
|
+
let draftAnchorState
|
|
29
|
+
if (draft.value) {
|
|
30
|
+
try { draftAnchorState = (await chrome.tabs.sendMessage(tab.id, { action: "locate", anchors: [draft.value.anchor] })).states[0] }
|
|
31
|
+
catch { draftAnchorState = "unavailable" }
|
|
32
|
+
}
|
|
33
|
+
return { tabID: tab.id, ...state, notes, anchorStates, hash, draft, draftAnchorState,
|
|
34
|
+
outbox: outbox ? { targetID: outbox.targetID, count: outbox.review.annotations.length } : null }
|
|
35
|
+
}
|
|
36
|
+
function draftConflict(draft) {
|
|
37
|
+
return Object.assign(new Error("This draft changed in another panel. Choose which version to keep."), { code: "draft-conflict", draft })
|
|
38
|
+
}
|
|
39
|
+
function validateDraft(page, draft) {
|
|
40
|
+
if (draft === null) return
|
|
41
|
+
if (!draft || typeof draft.comment !== "string" || draft.comment.length > 8000 || !["comment", "ask"].includes(draft.kind)) throw new Error("Invalid draft")
|
|
42
|
+
validateReview({ version: 1, page, annotations: [{ id: "draft", revision: 1, createdAt: new Date().toISOString(),
|
|
43
|
+
kind: draft.kind, comment: draft.comment.trim() || "Draft", anchor: draft.anchor }] })
|
|
44
|
+
if (draft.editing) validateReview({ version: 1, page, annotations: [draft.editing] })
|
|
45
|
+
consumedCaptures({}, draft.captures)
|
|
46
|
+
}
|
|
47
|
+
function consumedCaptures(previous, captures) {
|
|
48
|
+
const result = { ...previous }
|
|
49
|
+
if (!captures) return result
|
|
50
|
+
if (typeof captures !== "object" || Array.isArray(captures)) throw new Error("Invalid capture acknowledgement")
|
|
51
|
+
for (const [tab, id] of Object.entries(captures)) {
|
|
52
|
+
if (!Number.isSafeInteger(Number(tab)) || Number(tab) < 0 || String(Number(tab)) !== tab || typeof id !== "string" || !id) throw new Error("Invalid capture acknowledgement")
|
|
53
|
+
result[tab] = id
|
|
54
|
+
}
|
|
55
|
+
return result
|
|
56
|
+
}
|
|
57
|
+
async function handle(message, sender) {
|
|
58
|
+
if (message.action === "capture") {
|
|
59
|
+
if (!sender.tab || !sender.url || new URL(message.page.url).origin !== new URL(sender.url).origin) throw new Error("Invalid page source")
|
|
60
|
+
const key = `tab:${sender.tab.id}`
|
|
61
|
+
const previous = (await chrome.storage.session.get(key))[key] || {}
|
|
62
|
+
await chrome.storage.session.set({ [key]: { ...previous, page: { url: safeUrl(message.page.url), title: String(message.page.title).slice(0, 500) }, picking: !!message.picking,
|
|
63
|
+
...(!message.modeOnly ? { anchor: message.anchor, error: message.error, captureID: crypto.randomUUID() } : {}) } })
|
|
64
|
+
return {}
|
|
65
|
+
}
|
|
66
|
+
if (sender.url && !sender.url.startsWith(chrome.runtime.getURL(""))) throw new Error("Only the extension panel can manage feedback")
|
|
67
|
+
if (message.action === "current") return current()
|
|
68
|
+
if (message.action === "draft") return serial(async () => {
|
|
69
|
+
// A route change must still be able to persist the previous page's draft.
|
|
70
|
+
if (!message.page || safeUrl(message.page.url) !== message.page.url || typeof message.page.title !== "string" ||
|
|
71
|
+
typeof message.writerID !== "string" || !message.writerID || !Number.isSafeInteger(message.sequence) || message.sequence < 1 ||
|
|
72
|
+
!Number.isSafeInteger(message.baseRevision) || message.baseRevision < 0) throw new Error("Invalid draft update")
|
|
73
|
+
validateDraft(message.page, message.value)
|
|
74
|
+
const key = `draft:${await pageKey(message.page.url)}`
|
|
75
|
+
const old = (await chrome.storage.local.get(key))[key] || { revision: 0, value: null }
|
|
76
|
+
if (old.writerID === message.writerID && old.sequence >= message.sequence) return { draft: old }
|
|
77
|
+
if (old.revision !== message.baseRevision && old.writerID !== message.writerID) throw draftConflict(old)
|
|
78
|
+
const draft = { revision: old.revision + 1, value: message.value, writerID: message.writerID,
|
|
79
|
+
consumedCaptures: consumedCaptures(old.consumedCaptures, message.value === null ? message.captures : null),
|
|
80
|
+
sequence: message.sequence, updatedAt: new Date().toISOString() }
|
|
81
|
+
await chrome.storage.local.set({ [key]: draft })
|
|
82
|
+
return { draft }
|
|
83
|
+
})
|
|
84
|
+
if (message.action === "targets") return chrome.runtime.sendNativeMessage(HOST, { action: "targets" })
|
|
85
|
+
if (message.action === "connection") {
|
|
86
|
+
const { paired } = await chrome.storage.local.get("paired")
|
|
87
|
+
let result
|
|
88
|
+
try {
|
|
89
|
+
result = await chrome.runtime.sendNativeMessage(HOST, { action: "targets" })
|
|
90
|
+
if (!result.ok) throw new Error(result.error)
|
|
91
|
+
} catch (error) {
|
|
92
|
+
return { targets: [], target: null, destination: paired || null, stale: !!paired, error: error.message }
|
|
93
|
+
}
|
|
94
|
+
const target = paired ? result.targets.find(target => target.id === paired.id) : result.targets.length === 1 ? result.targets[0] : null
|
|
95
|
+
return { targets: result.targets, target: target || null, destination: target || paired || null, stale: !!paired && !target }
|
|
96
|
+
}
|
|
97
|
+
if (message.action === "pair") {
|
|
98
|
+
const result = await chrome.runtime.sendNativeMessage(HOST, { action: "info", targetID: message.target.id })
|
|
99
|
+
if (!result.ok) throw new Error(result.error)
|
|
100
|
+
await chrome.storage.local.set({ paired: result.target }); return { target: result.target }
|
|
101
|
+
}
|
|
102
|
+
if (message.action === "pairing") return { target: (await chrome.storage.local.get("paired")).paired || null }
|
|
103
|
+
if (message.action === "unpair") { await chrome.storage.local.remove("paired"); return {} }
|
|
104
|
+
const state = await current()
|
|
105
|
+
if (message.url && message.url !== state.page.url) throw new Error("The active page changed; retry on the original page")
|
|
106
|
+
if (message.action === "pick") return chrome.tabs.sendMessage(state.tabID, { action: "pick" })
|
|
107
|
+
if (message.action === "reveal") {
|
|
108
|
+
const note = state.notes.find(note => note.id === message.noteID)
|
|
109
|
+
if (!note) throw new Error("This note is no longer on the page")
|
|
110
|
+
const result = await chrome.tabs.sendMessage(state.tabID, { action: "reveal", anchor: note.anchor })
|
|
111
|
+
if (!result.ok) throw new Error(result.error)
|
|
112
|
+
return result
|
|
113
|
+
}
|
|
114
|
+
if (["save", "delete", "restore"].includes(message.action)) return serial(async () => {
|
|
115
|
+
const key = `note:${state.hash}:${message.note.id}`
|
|
116
|
+
const old = (await chrome.storage.local.get(key))[key]
|
|
117
|
+
if ((old?.revision || 0) !== message.baseRevision) throw Object.assign(new Error("This note changed in another tab. Choose which version to keep."), { code: "note-conflict", note: old || null })
|
|
118
|
+
if (message.action !== "save" && !old) throw new Error("This note no longer exists")
|
|
119
|
+
if (message.action === "restore" && !old.deleted) throw new Error("This note has already been restored")
|
|
120
|
+
const note = { ...(message.action === "save" ? message.note : old), page: state.page,
|
|
121
|
+
revision: (old?.revision || 0) + 1, deleted: message.action === "delete" }
|
|
122
|
+
if (message.action === "delete") note.wasSent = old.sentRevision === old.revision
|
|
123
|
+
else if (message.action === "restore") {
|
|
124
|
+
if (old.wasSent) note.sentRevision = note.revision
|
|
125
|
+
delete note.wasSent
|
|
126
|
+
} else {
|
|
127
|
+
note.sentRevision = old?.sentRevision
|
|
128
|
+
delete note.wasSent
|
|
129
|
+
}
|
|
130
|
+
validateReview({ version: 1, page: state.page, annotations: [note] })
|
|
131
|
+
if (!old && state.notes.length >= 200) throw new Error("This page has 200 notes; export and remove some first")
|
|
132
|
+
const updates = { [key]: note }
|
|
133
|
+
let draft
|
|
134
|
+
if (message.draftRevision !== undefined) {
|
|
135
|
+
const draftKey = `draft:${state.hash}`
|
|
136
|
+
const previous = (await chrome.storage.local.get(draftKey))[draftKey] || { revision: 0, value: null }
|
|
137
|
+
if (previous.revision !== message.draftRevision) throw draftConflict(previous)
|
|
138
|
+
draft = { ...previous, revision: previous.revision + 1, value: null,
|
|
139
|
+
consumedCaptures: consumedCaptures(previous.consumedCaptures, message.captures), updatedAt: new Date().toISOString() }
|
|
140
|
+
updates[draftKey] = draft
|
|
141
|
+
}
|
|
142
|
+
await chrome.storage.local.set(updates); return { note, draft }
|
|
143
|
+
})
|
|
144
|
+
if (message.action === "markers") return chrome.tabs.sendMessage(state.tabID, { action: "markers", notes: state.notes.map(note => ({ anchor: note.anchor })) })
|
|
145
|
+
if (message.action === "send") return serial(async () => {
|
|
146
|
+
const latest = await current()
|
|
147
|
+
if (latest.page.url !== state.page.url) throw new Error("The active page changed; return to the original page to send")
|
|
148
|
+
if (typeof message.targetID !== "string" || !message.targetID) throw new Error("Choose a destination session before sending")
|
|
149
|
+
let { paired } = await chrome.storage.local.get("paired")
|
|
150
|
+
if (paired && paired.id !== message.targetID) throw new Error("The destination changed in another panel; choose it again")
|
|
151
|
+
if (!paired) {
|
|
152
|
+
// A sole target is only preselected. The user's Send click authorizes this binding.
|
|
153
|
+
const result = await chrome.runtime.sendNativeMessage(HOST, { action: "info", targetID: message.targetID })
|
|
154
|
+
if (!result.ok) throw new Error(result.error)
|
|
155
|
+
paired = result.target
|
|
156
|
+
await chrome.storage.local.set({ paired })
|
|
157
|
+
}
|
|
158
|
+
const outboxKey = `outbox:${state.hash}`
|
|
159
|
+
let batch = (await chrome.storage.local.get(outboxKey))[outboxKey]
|
|
160
|
+
if (batch && batch.targetID !== paired.id) throw new Error("An unsent batch belongs to the previous pairing; restore that pairing or export your notes")
|
|
161
|
+
if (!batch) {
|
|
162
|
+
const pending = latest.notes.filter(note => note.sentRevision !== note.revision)
|
|
163
|
+
if (!pending.length) throw new Error("No new feedback to send")
|
|
164
|
+
const review = validateReview({ version: 1, page: state.page, annotations: pending })
|
|
165
|
+
batch = { action: "send", batchID: crypto.randomUUID(), targetID: paired.id, review }
|
|
166
|
+
await chrome.storage.local.set({ [outboxKey]: batch })
|
|
167
|
+
}
|
|
168
|
+
const response = await chrome.runtime.sendNativeMessage(HOST, batch)
|
|
169
|
+
if (!response.ok) throw new Error(response.error)
|
|
170
|
+
for (const sent of batch.review.annotations) {
|
|
171
|
+
const key = `note:${state.hash}:${sent.id}`
|
|
172
|
+
const note = (await chrome.storage.local.get(key))[key]
|
|
173
|
+
if (note && note.revision === sent.revision) await chrome.storage.local.set({ [key]: { ...note, sentRevision: sent.revision } })
|
|
174
|
+
}
|
|
175
|
+
await chrome.storage.local.remove(outboxKey)
|
|
176
|
+
return response
|
|
177
|
+
})
|
|
178
|
+
throw new Error("Unknown annotation action")
|
|
179
|
+
}
|
|
180
|
+
chrome.runtime.onMessage.addListener((message, sender, respond) => {
|
|
181
|
+
handle(message, sender).then(result => respond({ ok: true, ...result }), error => respond({ ok: false, error: error.message, code: error.code, draft: error.draft, note: error.note }))
|
|
182
|
+
return true
|
|
183
|
+
})
|
package/package.json
CHANGED
|
@@ -1,6 +1,67 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nxxxsooo/opencode-annotate",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.6.0",
|
|
4
|
+
"description": "Unofficial OpenCode plugin: annotate replies, documents and webpages, then send the feedback to the originating session.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
"./tui": "./tui.ts"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"test": "node --test *.test.mjs bridge/*.test.mjs",
|
|
12
|
+
"test:browser": "node tests/browser.mjs",
|
|
13
|
+
"install:bridge": "node scripts/install-bridge.mjs",
|
|
14
|
+
"install:plugin": "node scripts/install-plugin.mjs",
|
|
15
|
+
"test:smoke": "python3 smoke.py",
|
|
16
|
+
"check": "node --check review.mjs && npm test && npm pack --dry-run",
|
|
17
|
+
"prepublishOnly": "npm run check"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"tui.ts",
|
|
21
|
+
"review.mjs",
|
|
22
|
+
"theme.mjs",
|
|
23
|
+
"targets.mjs",
|
|
24
|
+
"web-review.mjs",
|
|
25
|
+
"browser",
|
|
26
|
+
"bridge/native-host.mjs",
|
|
27
|
+
"bridge/receiver.mjs",
|
|
28
|
+
"bridge/wire.mjs",
|
|
29
|
+
"scripts/install-bridge.mjs",
|
|
30
|
+
"scripts/install-plugin.mjs",
|
|
31
|
+
"scripts/migrate-page-context.mjs",
|
|
32
|
+
"README.md",
|
|
33
|
+
"LICENSE",
|
|
34
|
+
"CHANGELOG.md"
|
|
35
|
+
],
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=22"
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"@opencode/plugin": ">=2.0.22 <3"
|
|
41
|
+
},
|
|
42
|
+
"peerDependenciesMeta": {
|
|
43
|
+
"@opencode/plugin": {
|
|
44
|
+
"optional": true
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/nxxxsooo/opencode-annotate.git"
|
|
50
|
+
},
|
|
51
|
+
"homepage": "https://github.com/nxxxsooo/opencode-annotate#readme",
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": "https://github.com/nxxxsooo/opencode-annotate/issues"
|
|
54
|
+
},
|
|
55
|
+
"keywords": [
|
|
56
|
+
"opencode",
|
|
57
|
+
"opencode-plugin",
|
|
58
|
+
"plannotator",
|
|
59
|
+
"tui",
|
|
60
|
+
"annotation",
|
|
61
|
+
"markdown",
|
|
62
|
+
"review"
|
|
63
|
+
],
|
|
64
|
+
"publishConfig": {
|
|
65
|
+
"access": "public"
|
|
66
|
+
}
|
|
67
|
+
}
|
package/review.mjs
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { spawn, execFile } from "node:child_process"
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto"
|
|
3
|
+
import { mkdtemp, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"
|
|
4
|
+
import os from "node:os"
|
|
5
|
+
import path from "node:path"
|
|
6
|
+
import { promisify } from "node:util"
|
|
7
|
+
import { createWebReview } from "./web-review.mjs"
|
|
8
|
+
import { wantsBrowser } from "./targets.mjs"
|
|
9
|
+
import { prepareTheme } from "./theme.mjs"
|
|
10
|
+
|
|
11
|
+
const execute = promisify(execFile)
|
|
12
|
+
const documentExtensions = new Set([".md", ".mdx", ".markdown", ".txt"])
|
|
13
|
+
const maxDocumentBytes = 2 * 1024 * 1024
|
|
14
|
+
|
|
15
|
+
async function documentSource(input, client, sessionID, signal) {
|
|
16
|
+
let target = input.trim()
|
|
17
|
+
if ((target.startsWith('"') && target.endsWith('"')) || (target.startsWith("'") && target.endsWith("'"))) {
|
|
18
|
+
target = target.slice(1, -1)
|
|
19
|
+
}
|
|
20
|
+
if (!target || !documentExtensions.has(path.extname(target).toLowerCase())) {
|
|
21
|
+
throw new Error("Choose a Markdown or plain-text file (.md, .mdx, .markdown, .txt).")
|
|
22
|
+
}
|
|
23
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(target)) throw new Error("Use a local file path.")
|
|
24
|
+
if (target.startsWith("~/")) target = path.join(os.homedir(), target.slice(2))
|
|
25
|
+
const session = await client.session.get({ sessionID }, { signal })
|
|
26
|
+
const directory = session.location?.directory
|
|
27
|
+
if (!path.isAbsolute(target) && !directory) throw new Error("Can't determine the current session's working directory.")
|
|
28
|
+
const filePath = path.isAbsolute(target) ? path.normalize(target) : path.resolve(directory, target)
|
|
29
|
+
try {
|
|
30
|
+
const info = await stat(filePath)
|
|
31
|
+
if (!info.isFile()) throw new Error("The target is not a file.")
|
|
32
|
+
if (info.size > maxDocumentBytes) throw new Error("The file is larger than 2 MiB. Choose a smaller document.")
|
|
33
|
+
const bytes = await readFile(filePath, { signal })
|
|
34
|
+
if (bytes.length > maxDocumentBytes) throw new Error("The file is larger than 2 MiB.")
|
|
35
|
+
if (bytes.includes(0)) throw new Error("The file contains binary content.")
|
|
36
|
+
let text
|
|
37
|
+
try {
|
|
38
|
+
text = new TextDecoder("utf-8", { fatal: true }).decode(bytes)
|
|
39
|
+
} catch {
|
|
40
|
+
throw new Error("Use a UTF-8 text file.")
|
|
41
|
+
}
|
|
42
|
+
return {
|
|
43
|
+
text, filePath,
|
|
44
|
+
sourceHash: createHash("sha256").update(bytes).digest("hex"),
|
|
45
|
+
snapshot: path.join("source", path.basename(filePath)),
|
|
46
|
+
}
|
|
47
|
+
} catch (error) {
|
|
48
|
+
if (signal.aborted) throw error
|
|
49
|
+
throw new Error(`Can't read document "${filePath}": ${error.code === "ENOENT" ? "file not found." : error.message}`)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function selectReply(messages) {
|
|
54
|
+
return eligibleReplies(messages)[0]
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Completed assistant text, newest first. Mid-turn progress updates (finish "tool-calls")
|
|
58
|
+
// are text the user can read in the transcript, so pick and selection include them.
|
|
59
|
+
function textMessages(messages) {
|
|
60
|
+
const texts = []
|
|
61
|
+
const newest = [...messages].sort((a, b) =>
|
|
62
|
+
b.time.created - a.time.created || b.id.localeCompare(a.id),
|
|
63
|
+
)
|
|
64
|
+
for (const message of newest) {
|
|
65
|
+
if (message.type !== "assistant" || message.time.completed === undefined || message.error) continue
|
|
66
|
+
if (["error", "content-filter"].includes(message.finish)) continue
|
|
67
|
+
const text = message.content.filter(part => part.type === "text").map(part => part.text).join("\n\n")
|
|
68
|
+
if (text.trim()) {
|
|
69
|
+
texts.push({ id: message.id, text, progress: message.finish === "tool-calls", created: message.time.created })
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return texts
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function eligibleReplies(messages) {
|
|
76
|
+
return textMessages(messages).filter(message => !message.progress).map(({ id, text }) => ({ id, text }))
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Walk the session-scoped history newest first; the UI cache holds only a recent page.
|
|
80
|
+
async function* history(client, sessionID, signal) {
|
|
81
|
+
const seen = new Set()
|
|
82
|
+
let cursor
|
|
83
|
+
do {
|
|
84
|
+
signal.throwIfAborted()
|
|
85
|
+
const page = await client.message.list({
|
|
86
|
+
sessionID, type: "assistant", limit: 50,
|
|
87
|
+
...(cursor ? { cursor } : { order: "desc" }),
|
|
88
|
+
}, { signal })
|
|
89
|
+
yield page.data
|
|
90
|
+
cursor = page.cursor?.next
|
|
91
|
+
if (cursor && seen.has(cursor)) throw new Error("Session history returned a repeated page cursor.")
|
|
92
|
+
seen.add(cursor)
|
|
93
|
+
} while (cursor)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function latestReply(client, sessionID, signal) {
|
|
97
|
+
for await (const page of history(client, sessionID, signal)) {
|
|
98
|
+
const [reply] = eligibleReplies(page)
|
|
99
|
+
if (reply) return reply
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function recentTexts(client, sessionID, signal, limit) {
|
|
104
|
+
const texts = new Map()
|
|
105
|
+
for await (const page of history(client, sessionID, signal)) {
|
|
106
|
+
for (const message of textMessages(page)) {
|
|
107
|
+
texts.set(message.id, message)
|
|
108
|
+
if (texts.size >= limit) return [...texts.values()]
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return [...texts.values()]
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Rendered transcript text drops Markdown markers and rewraps lines, so compare letters
|
|
115
|
+
// and digits only.
|
|
116
|
+
const compact = text => text.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu, "")
|
|
117
|
+
const preview = (text, length) => {
|
|
118
|
+
const line = text.replace(/[#*_`>]+/g, "").replace(/\s+/g, " ").trim()
|
|
119
|
+
return line.length > length ? `${line.slice(0, length - 1)}…` : line
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function archivedNotes(data) {
|
|
123
|
+
let count = 0
|
|
124
|
+
for (const name of await readdir(data, { recursive: true })) {
|
|
125
|
+
if (path.basename(name) !== "annotations.json") continue
|
|
126
|
+
const record = JSON.parse(await readFile(path.join(data, name), "utf8"))
|
|
127
|
+
count += record.archived?.length ?? 0
|
|
128
|
+
}
|
|
129
|
+
return count
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function interactive({ binary, file, cwd, env, signal }) {
|
|
133
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
134
|
+
throw new Error("Run /annotate in the full OpenCode terminal interface.")
|
|
135
|
+
}
|
|
136
|
+
await new Promise((resolve, reject) => {
|
|
137
|
+
const child = spawn(binary, [file], { cwd, env, stdio: "inherit", signal })
|
|
138
|
+
child.once("error", reject)
|
|
139
|
+
child.once("close", (code, termination) => {
|
|
140
|
+
if (code === 0) resolve()
|
|
141
|
+
else reject(new Error(`plannotator-tui exited: ${termination ?? code}`))
|
|
142
|
+
})
|
|
143
|
+
})
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function createReviewCommand(context, options = {}) {
|
|
147
|
+
const web = createWebReview(context, options.web)
|
|
148
|
+
const binary = options.binary ?? context.options.binary ?? "plannotator-tui"
|
|
149
|
+
const runInteractive = options.interactive ?? interactive
|
|
150
|
+
let active
|
|
151
|
+
let disposed = false
|
|
152
|
+
const notice = (message, variant = "info") => context.ui.toast.show({
|
|
153
|
+
title: "Annotate", message, variant, duration: variant === "error" ? 15000 : 5000,
|
|
154
|
+
})
|
|
155
|
+
|
|
156
|
+
let selection
|
|
157
|
+
const remember = current => {
|
|
158
|
+
const text = current?.getSelectedText?.() ?? ""
|
|
159
|
+
const route = context.ui.router.current()
|
|
160
|
+
if (text.trim() && route.type === "session") selection = { text, sessionID: route.sessionID }
|
|
161
|
+
}
|
|
162
|
+
// OpenCode copies a mouse selection and clears it on release, before any command can
|
|
163
|
+
// run, so keep the last one per session.
|
|
164
|
+
context.renderer.on("selection", remember)
|
|
165
|
+
|
|
166
|
+
async function start(resolve) {
|
|
167
|
+
if (disposed) return
|
|
168
|
+
if (active) return notice("An annotation is already in progress.")
|
|
169
|
+
// Capture before the first await: changing tabs must never redirect a review.
|
|
170
|
+
const route = context.ui.router.current()
|
|
171
|
+
if (route.type !== "session") return notice("Open a session first.")
|
|
172
|
+
const sessionID = route.sessionID
|
|
173
|
+
const title = context.data.session.get(sessionID)?.title ?? sessionID
|
|
174
|
+
const controller = new AbortController()
|
|
175
|
+
active = controller
|
|
176
|
+
let directory
|
|
177
|
+
let keepDraft = false
|
|
178
|
+
try {
|
|
179
|
+
const source = await resolve({ sessionID, signal: controller.signal })
|
|
180
|
+
if (controller.signal.aborted || !source) return
|
|
181
|
+
|
|
182
|
+
directory = await mkdtemp(path.join(options.tempRoot ?? os.tmpdir(), "opencode-annotate-"))
|
|
183
|
+
keepDraft = true
|
|
184
|
+
const snapshot = source.snapshot ?? (source.selection ? "selection.md" : source.progress ? "progress-update.md" : "last-reply.md")
|
|
185
|
+
const file = path.join(directory, snapshot)
|
|
186
|
+
const data = path.join(directory, "data")
|
|
187
|
+
const promptID = `msg_${randomUUID().replaceAll("-", "")}`
|
|
188
|
+
await mkdir(data, { mode: 0o700 })
|
|
189
|
+
await mkdir(path.dirname(file), { recursive: true, mode: 0o700 })
|
|
190
|
+
await writeFile(file, source.text, { mode: 0o600 })
|
|
191
|
+
await writeFile(path.join(directory, "review.json"), JSON.stringify({
|
|
192
|
+
sessionID, messageID: source.id, filePath: source.filePath,
|
|
193
|
+
sourceHash: source.sourceHash, snapshot, promptID, title,
|
|
194
|
+
}, null, 2), { mode: 0o600 })
|
|
195
|
+
|
|
196
|
+
// Use a fresh store per invocation, and disable any inherited pane delivery.
|
|
197
|
+
// The OpenCode confirmation is the sole authority for sending feedback.
|
|
198
|
+
let env = Object.fromEntries(Object.entries(process.env).filter(([key]) =>
|
|
199
|
+
!key.startsWith("HERDR_") && !key.startsWith("PLANNOTATOR_TUI_"),
|
|
200
|
+
))
|
|
201
|
+
Object.assign(env, {
|
|
202
|
+
PLANNOTATOR_DATA_DIR: data,
|
|
203
|
+
PLANNOTATOR_FEEDBACK_HISTORY: "0",
|
|
204
|
+
PLANNOTATOR_TUI_THEME: context.themeMode === "light" ? "light" : "dark",
|
|
205
|
+
})
|
|
206
|
+
if ((options.inheritTheme ?? context.options.inheritTheme) === true) {
|
|
207
|
+
env = await prepareTheme({ binary, theme: context.theme, directory, env, signal: controller.signal })
|
|
208
|
+
}
|
|
209
|
+
context.ui.dialog.clear()
|
|
210
|
+
// OpenCode 2.1.1+ suspends and resumes asynchronously; resume forces a full repaint.
|
|
211
|
+
await context.renderer.suspend()
|
|
212
|
+
try {
|
|
213
|
+
await runInteractive({ binary, file, cwd: directory, env, signal: controller.signal })
|
|
214
|
+
} finally {
|
|
215
|
+
await context.renderer.resume()
|
|
216
|
+
context.renderer.requestRender()
|
|
217
|
+
}
|
|
218
|
+
if (controller.signal.aborted) return
|
|
219
|
+
const { stdout } = await execute(binary, ["--export", file], {
|
|
220
|
+
cwd: directory, env, signal: controller.signal, timeout: 15000, maxBuffer: 8 * 1024 * 1024,
|
|
221
|
+
})
|
|
222
|
+
const feedback = stdout.trim()
|
|
223
|
+
const archived = await archivedNotes(data)
|
|
224
|
+
const retainedArchive = archived ? `\n${archived} archived ${archived === 1 ? "note was" : "notes were"} kept in ${directory}.` : ""
|
|
225
|
+
// Upstream 0.9.4 emits this sentinel rather than empty stdout.
|
|
226
|
+
if (!feedback || feedback === "No annotations.") {
|
|
227
|
+
keepDraft = archived > 0
|
|
228
|
+
return notice(archived ? `No annotations to send.${retainedArchive}` : "No annotations. Returned to the session.", archived ? "warning" : "info")
|
|
229
|
+
}
|
|
230
|
+
if (!feedback.startsWith("# Annotations on ")) throw new Error("Can't recognize the TUI annotation export format.")
|
|
231
|
+
const subject = source.filePath
|
|
232
|
+
? `Here are my annotations on the document ${JSON.stringify(source.filePath)}. Please apply the feedback to that file.\nThe annotations are based on a snapshot taken when the document was opened (SHA-256: ${source.sourceHash}). Re-read the file and check the quoted text before editing.`
|
|
233
|
+
: source.selection
|
|
234
|
+
? "Here are my annotations on text I selected in this session. Please address the feedback."
|
|
235
|
+
: `Here are my annotations on your ${source.progress ? "progress update" : "reply"} ${source.id}. Please address the feedback.`
|
|
236
|
+
const text = `${subject}\n\n${feedback}`
|
|
237
|
+
const feedbackPath = path.join(directory, "feedback.md")
|
|
238
|
+
await writeFile(feedbackPath, text, { mode: 0o600 })
|
|
239
|
+
const count = (feedback.match(/^## Annotation /gm) ?? []).length
|
|
240
|
+
const confirmed = await context.ui.dialog.confirm({
|
|
241
|
+
title: "Send annotations?",
|
|
242
|
+
message: `${source.filePath ? `Document: ${source.filePath}\n` : ""}Send ${count} ${count === 1 ? "annotation" : "annotations"} to "${title}" and let the assistant continue?`,
|
|
243
|
+
label: { confirm: "Send and continue", cancel: "Cancel" },
|
|
244
|
+
})
|
|
245
|
+
if (controller.signal.aborted) return
|
|
246
|
+
if (confirmed !== true) {
|
|
247
|
+
keepDraft = archived > 0
|
|
248
|
+
return notice(`Sending cancelled.${retainedArchive}`)
|
|
249
|
+
}
|
|
250
|
+
await context.client.session.prompt({
|
|
251
|
+
sessionID, id: promptID, text, delivery: "queue", resume: true,
|
|
252
|
+
})
|
|
253
|
+
keepDraft = archived > 0
|
|
254
|
+
notice(`Sent ${count} ${count === 1 ? "annotation" : "annotations"}.${retainedArchive}`, "success")
|
|
255
|
+
} catch (error) {
|
|
256
|
+
if (!disposed) {
|
|
257
|
+
const detail = error?.code === "ENOENT"
|
|
258
|
+
? "Can't find plannotator-tui. Check that it is installed and on PATH."
|
|
259
|
+
: error instanceof Error ? error.message : String(error)
|
|
260
|
+
const recovery = keepDraft && directory
|
|
261
|
+
? `\nThe draft was kept in ${directory}. If it was exported, the feedback is in feedback.md.`
|
|
262
|
+
: ""
|
|
263
|
+
notice(`${detail}${recovery}`, "error")
|
|
264
|
+
}
|
|
265
|
+
} finally {
|
|
266
|
+
if (directory && !keepDraft) {
|
|
267
|
+
await rm(directory, { recursive: true, force: true }).catch(() => {})
|
|
268
|
+
}
|
|
269
|
+
active = undefined
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const run = (input = "") => start(async ({ sessionID, signal }) => {
|
|
274
|
+
const target = input.trim()
|
|
275
|
+
if (/^\d+$/.test(target)) throw new Error("Numbered replies are retired. Use /annotate-pick to choose earlier text.")
|
|
276
|
+
if (wantsBrowser(target)) throw new Error("Use /annotate-web for webpages and browser pairing.")
|
|
277
|
+
if (target) return documentSource(target, context.client, sessionID, signal)
|
|
278
|
+
const reply = await latestReply(context.client, sessionID, signal)
|
|
279
|
+
if (!reply) notice("This session has no completed assistant reply yet.")
|
|
280
|
+
return reply
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
const pick = () => start(async ({ sessionID, signal }) => {
|
|
284
|
+
const texts = await recentTexts(context.client, sessionID, signal, 30)
|
|
285
|
+
if (!texts.length) {
|
|
286
|
+
notice("This session has no completed assistant text yet.")
|
|
287
|
+
return
|
|
288
|
+
}
|
|
289
|
+
const time = new Intl.DateTimeFormat(undefined, { hour: "2-digit", minute: "2-digit" })
|
|
290
|
+
const chosen = await context.ui.dialog.select({
|
|
291
|
+
title: "Annotate text",
|
|
292
|
+
options: texts.map(text => ({
|
|
293
|
+
title: preview(text.text, 60), value: text.id,
|
|
294
|
+
description: `${text.progress ? "Progress update" : "Reply"} · ${time.format(text.created)}`,
|
|
295
|
+
})),
|
|
296
|
+
})
|
|
297
|
+
return texts.find(text => text.id === chosen)
|
|
298
|
+
})
|
|
299
|
+
|
|
300
|
+
const annotateSelection = () => start(async ({ sessionID, signal }) => {
|
|
301
|
+
const selected = selection?.sessionID === sessionID ? selection.text : ""
|
|
302
|
+
const needle = compact(selected)
|
|
303
|
+
if (!needle) {
|
|
304
|
+
notice("Select text in this session first, then run /annotate-selection.")
|
|
305
|
+
return
|
|
306
|
+
}
|
|
307
|
+
const texts = await recentTexts(context.client, sessionID, signal, 200)
|
|
308
|
+
return texts.find(text => compact(text.text).includes(needle)) ?? { text: selected, selection: true }
|
|
309
|
+
})
|
|
310
|
+
|
|
311
|
+
const webReview = (input = "") => start(async ({ sessionID }) => {
|
|
312
|
+
const target = input.trim()
|
|
313
|
+
if (!(await web.run(target === "" ? "web" : target === "off" ? "web off" : target, sessionID))) {
|
|
314
|
+
throw new Error("Use a webpage URL, an HTML file, or off.")
|
|
315
|
+
}
|
|
316
|
+
})
|
|
317
|
+
|
|
318
|
+
return {
|
|
319
|
+
run, pick, selection: annotateSelection, web: webReview,
|
|
320
|
+
dispose() {
|
|
321
|
+
context.renderer.off("selection", remember)
|
|
322
|
+
disposed = true
|
|
323
|
+
active?.abort()
|
|
324
|
+
return web.dispose()
|
|
325
|
+
},
|
|
326
|
+
}
|
|
327
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { readFile, mkdir, writeFile, chmod, copyFile } from "node:fs/promises"
|
|
2
|
+
import { createHash } from "node:crypto"
|
|
3
|
+
import { fileURLToPath } from "node:url"
|
|
4
|
+
import os from "node:os"
|
|
5
|
+
import path from "node:path"
|
|
6
|
+
import { registryRoot } from "../bridge/receiver.mjs"
|
|
7
|
+
const root = fileURLToPath(new URL("../", import.meta.url))
|
|
8
|
+
export async function installBridge({ profileDirectory = path.join(os.homedir(), "Library/Application Support/Google/Chrome"), installRoot = path.join(os.homedir(), ".local/share/opencode-annotate/native"), node = process.execPath, targetsDirectory = registryRoot() } = {}) {
|
|
9
|
+
const manifest = JSON.parse(await readFile(path.join(root, "browser/manifest.json"), "utf8"))
|
|
10
|
+
const extensionID = [...createHash("sha256").update(Buffer.from(manifest.key, "base64")).digest().subarray(0, 16)].flatMap(byte => [String.fromCharCode(97 + (byte >> 4)), String.fromCharCode(97 + (byte & 15))]).join("")
|
|
11
|
+
await mkdir(installRoot, { recursive: true, mode: 0o700 })
|
|
12
|
+
const launcher = path.join(installRoot, "host"), config = path.join(installRoot, "config.json")
|
|
13
|
+
const quote = value => `'${value.replaceAll("'", "'\\''")}'`
|
|
14
|
+
await writeFile(config, JSON.stringify({ extensionID, targetsDirectory }), { mode: 0o600 })
|
|
15
|
+
await writeFile(launcher, `#!/bin/sh\nexec ${quote(node)} ${quote(path.join(root, "bridge/native-host.mjs"))} ${quote(config)} "$@"\n`, { mode: 0o700 })
|
|
16
|
+
await chmod(launcher, 0o700)
|
|
17
|
+
const directory = path.join(profileDirectory, "NativeMessagingHosts")
|
|
18
|
+
await mkdir(directory, { recursive: true })
|
|
19
|
+
const hostManifest = path.join(directory, "fun.mjshao.annotate.json")
|
|
20
|
+
try { await copyFile(hostManifest, `${hostManifest}.backup-${Date.now()}`) } catch (error) { if (error.code !== "ENOENT") throw error }
|
|
21
|
+
await writeFile(hostManifest, JSON.stringify({ name: "fun.mjshao.annotate", description: "Paired OpenCode annotation delivery", path: launcher, type: "stdio", allowed_origins: [`chrome-extension://${extensionID}/`] }, null, 2), { mode: 0o600 })
|
|
22
|
+
return { extensionID, extensionDirectory: path.join(root, "browser"), hostManifest, launcher }
|
|
23
|
+
}
|
|
24
|
+
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
25
|
+
if (process.platform !== "darwin") throw new Error("Local installer currently supports macOS only")
|
|
26
|
+
console.log(JSON.stringify(await installBridge(), null, 2))
|
|
27
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { readFile, writeFile, mkdir, realpath, rename, stat } from "node:fs/promises"
|
|
2
|
+
import { fileURLToPath } from "node:url"
|
|
3
|
+
import { createHash } from "node:crypto"
|
|
4
|
+
import path from "node:path"
|
|
5
|
+
import os from "node:os"
|
|
6
|
+
|
|
7
|
+
const root = fileURLToPath(new URL("../", import.meta.url)).replace(/\/$/, "")
|
|
8
|
+
const source = entry => typeof entry === "string" ? entry : entry.package
|
|
9
|
+
const oldEntry = entry => source(entry) === "@nxxxsooo/opencode-annotate" || source(entry)?.startsWith("@nxxxsooo/opencode-annotate@")
|
|
10
|
+
const configPath = path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config"), "opencode/cli.json")
|
|
11
|
+
const filename = await realpath(configPath)
|
|
12
|
+
const bytes = await readFile(filename, "utf8"), config = JSON.parse(bytes)
|
|
13
|
+
let backup
|
|
14
|
+
if (process.argv[2] === "--undo") {
|
|
15
|
+
if (!process.argv[3]) throw new Error("Supply the cli-before.json backup")
|
|
16
|
+
const previous = JSON.parse(await readFile(process.argv[3], "utf8"))
|
|
17
|
+
const old = previous.plugins.filter(oldEntry)
|
|
18
|
+
if (old.length !== 1 || config.plugins.filter(entry => source(entry) === root).length !== 1) throw new Error("Ambiguous plugin rollback; no changes made")
|
|
19
|
+
config.plugins = config.plugins.map(entry => source(entry) === root ? old[0] : entry)
|
|
20
|
+
} else {
|
|
21
|
+
const candidates = config.plugins.filter(oldEntry)
|
|
22
|
+
if (config.plugins.some(entry => source(entry) === root)) { console.log("Local plugin is already configured."); process.exit(0) }
|
|
23
|
+
if (candidates.length !== 1) throw new Error("Expected exactly one existing @nxxxsooo/opencode-annotate entry; no changes made")
|
|
24
|
+
const backupDir = path.join(root, ".local/migration")
|
|
25
|
+
await mkdir(backupDir, { recursive: true, mode: 0o700 })
|
|
26
|
+
backup = path.join(backupDir, `cli-before-${Date.now()}.json`)
|
|
27
|
+
await writeFile(backup, bytes, { mode: 0o600, flag: "wx" })
|
|
28
|
+
config.plugins = config.plugins.map(entry => oldEntry(entry) ? typeof entry === "string" ? root : { ...entry, package: root } : entry)
|
|
29
|
+
}
|
|
30
|
+
if (await readFile(filename, "utf8") !== bytes) throw new Error("CLI configuration changed concurrently; retry")
|
|
31
|
+
const output = `${JSON.stringify(config, null, 2)}\n`, temporary = `${filename}.annotate-${process.pid}`
|
|
32
|
+
await writeFile(temporary, output, { mode: (await stat(filename)).mode & 0o777, flag: "wx" })
|
|
33
|
+
await rename(temporary, filename)
|
|
34
|
+
console.log(JSON.stringify({ configured: root, config: filename, backup, installedSha256: createHash("sha256").update(output).digest("hex"), next: "Reopen the OpenCode terminal client. Do not restart the shared service." }, null, 2))
|