@nxxxsooo/opencode-annotate 0.14.0 → 0.16.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 +30 -0
- package/README.md +34 -82
- package/agy/receiver.test.mjs +2 -2
- package/agy/skills/annotate/SKILL.md +3 -3
- package/bridge/native-host.mjs +5 -2
- package/bridge/receiver.mjs +38 -12
- package/browser/UPSTREAM.md +3 -1
- package/browser/manifest.json +1 -1
- package/browser/panel.css +25 -8
- package/browser/panel.html +9 -5
- package/browser/panel.mjs +206 -86
- package/browser/protocol.mjs +22 -7
- package/browser/worker.mjs +148 -40
- package/package.json +1 -8
- package/review.mjs +28 -42
- package/scripts/install-bridge.mjs +27 -6
- package/scripts/migrate-page-context.mjs +3 -3
- package/server.ts +0 -2
- package/targets.mjs +1 -2
- package/tui/bin/darwin-arm64/annotate-tui +0 -0
- package/tui/bin/darwin-x64/annotate-tui +0 -0
- package/tui/bin/linux-arm64/annotate-tui +0 -0
- package/tui/bin/linux-x64/annotate-tui +0 -0
- package/tui/bin/win32-x64/annotate-tui.exe +0 -0
- package/tui.ts +8 -35
- package/web-review.mjs +88 -30
- package/reference-command.mjs +0 -207
- package/reference-comment.tsx +0 -65
- package/server-history.mjs +0 -58
- package/session-reference.mjs +0 -119
- package/session-tools.mjs +0 -55
package/tui.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { Plugin } from "@opencode/plugin/tui"
|
|
2
2
|
import { createReviewCommand } from "./review.mjs"
|
|
3
3
|
import { createAsciiHold, createInputSource } from "./input-source.mjs"
|
|
4
|
-
import { createReferenceCommand } from "./reference-command.mjs"
|
|
5
|
-
import { promptReferenceComment } from "./reference-comment.tsx"
|
|
6
4
|
import { createAutoReview } from "./auto-review.mjs"
|
|
7
5
|
import { watchConfiguration } from "./configuration.mjs"
|
|
6
|
+
import { installBridge } from "./scripts/install-bridge.mjs"
|
|
8
7
|
|
|
9
8
|
export default Plugin.define({
|
|
10
9
|
id: "opencode-annotate",
|
|
@@ -17,20 +16,21 @@ export default Plugin.define({
|
|
|
17
16
|
const configuration = watchConfiguration(context, updated => {
|
|
18
17
|
const changed = options.autoAnnotate !== updated.autoAnnotate
|
|
19
18
|
|| options.autoAnnotateThreshold !== updated.autoAnnotateThreshold
|
|
19
|
+
|| options.browser !== updated.browser
|
|
20
20
|
options = updated
|
|
21
21
|
if (changed) restartAutoReview?.()
|
|
22
22
|
})
|
|
23
23
|
await configuration.ready
|
|
24
|
+
if (process.platform === "darwin") void installBridge().catch(error => {
|
|
25
|
+
context.ui.toast.show({ title: "Annotate", message: `Browser auto-setup failed: ${error.message}. Run npm run install:bridge to repair it.`, variant: "error", duration: 15000 })
|
|
26
|
+
})
|
|
24
27
|
const inputSource = createInputSource(context.options.inputSource)
|
|
25
|
-
const review = createReviewCommand(context, { inputSource, web: { browser: options.browser } })
|
|
28
|
+
const review = createReviewCommand(context, { inputSource, web: { autoRegister: true, browser: options.browser } })
|
|
26
29
|
restartAutoReview = () => {
|
|
27
30
|
stopAutoReview()
|
|
28
31
|
stopAutoReview = createAutoReview(context, review)
|
|
29
32
|
}
|
|
30
33
|
restartAutoReview()
|
|
31
|
-
const reference = createReferenceCommand(context, {
|
|
32
|
-
review, promptComment: (options, signal) => promptReferenceComment(context, options, signal),
|
|
33
|
-
})
|
|
34
34
|
// Permission prompts answer with single letters, which an input method swallows.
|
|
35
35
|
const hold = createAsciiHold(inputSource)
|
|
36
36
|
const stopAsked = context.data.on("permission.asked", event => hold.enter(event.data.id))
|
|
@@ -43,22 +43,12 @@ export default Plugin.define({
|
|
|
43
43
|
mode: "global",
|
|
44
44
|
commands: [{
|
|
45
45
|
id: "opencode-annotate.annotate",
|
|
46
|
-
title: "Annotate reply or
|
|
47
|
-
description: "The latest completed reply, or a
|
|
46
|
+
title: "Annotate reply, document or webpage",
|
|
47
|
+
description: "The latest completed reply, a file path, or a webpage URL",
|
|
48
48
|
group: "Annotate",
|
|
49
49
|
palette: true,
|
|
50
50
|
slash: { name: "annotate", arguments: true },
|
|
51
51
|
run: review.run,
|
|
52
|
-
}, {
|
|
53
|
-
id: "opencode-annotate.annotate-last",
|
|
54
|
-
title: "Annotate last reply (TUI)",
|
|
55
|
-
description: "Annotate the latest completed reply; q sends and returns",
|
|
56
|
-
group: "Annotate",
|
|
57
|
-
palette: true,
|
|
58
|
-
// Keep slash submission with a trailing space local to the command.
|
|
59
|
-
// Any supplied argument is deliberately ignored: this always means latest.
|
|
60
|
-
slash: { name: "annotate-last", arguments: true },
|
|
61
|
-
run: () => review.run(),
|
|
62
52
|
}, {
|
|
63
53
|
id: "opencode-annotate.annotate-pick",
|
|
64
54
|
title: "Annotate earlier text (TUI)",
|
|
@@ -75,22 +65,6 @@ export default Plugin.define({
|
|
|
75
65
|
palette: true,
|
|
76
66
|
slash: { name: "annotate-selection", arguments: true },
|
|
77
67
|
run: () => review.selection(),
|
|
78
|
-
}, {
|
|
79
|
-
id: "opencode-annotate.annotate-web",
|
|
80
|
-
title: "Annotate webpage (browser)",
|
|
81
|
-
description: "Pair Chrome (creates a session if needed), open a URL or HTML file, or off",
|
|
82
|
-
group: "Annotate",
|
|
83
|
-
palette: true,
|
|
84
|
-
slash: { name: "annotate-web", arguments: true },
|
|
85
|
-
run: review.web,
|
|
86
|
-
}, {
|
|
87
|
-
id: "opencode-annotate.ref",
|
|
88
|
-
title: "Reference another conversation",
|
|
89
|
-
description: "Attach a past conversation with a comment or TUI annotations; --all searches across projects",
|
|
90
|
-
group: "Annotate",
|
|
91
|
-
palette: true,
|
|
92
|
-
slash: { name: "ref", arguments: true },
|
|
93
|
-
run: reference.run,
|
|
94
68
|
}],
|
|
95
69
|
}))
|
|
96
70
|
return null
|
|
@@ -102,7 +76,6 @@ export default Plugin.define({
|
|
|
102
76
|
configuration.dispose()
|
|
103
77
|
stopAutoReview()
|
|
104
78
|
review.dispose()
|
|
105
|
-
reference.dispose()
|
|
106
79
|
unmount()
|
|
107
80
|
}
|
|
108
81
|
},
|
package/web-review.mjs
CHANGED
|
@@ -8,49 +8,107 @@ export function homeSession(context) {
|
|
|
8
8
|
return { location, model: selected && { providerID: selected.providerID, id: selected.modelID, variant: selected.variant } }
|
|
9
9
|
}
|
|
10
10
|
export function createWebReview(context, options = {}) {
|
|
11
|
-
const receivers = new Map()
|
|
11
|
+
const receivers = new Map(), registrations = new Map(), deleted = new Set()
|
|
12
12
|
let disposed = false
|
|
13
|
+
async function register(sessionID, session) {
|
|
14
|
+
session ??= await context.client.session.get({ sessionID })
|
|
15
|
+
if (disposed || deleted.has(sessionID)) return
|
|
16
|
+
const receiver = await createReceiver({ sessionID, title: session.title || sessionID, directory: session.location?.directory || "", client: context.client,
|
|
17
|
+
createSession: () => newSession(sessionID), ...options.receiver })
|
|
18
|
+
if (disposed || deleted.has(sessionID)) { await receiver.close(); return }
|
|
19
|
+
receivers.set(sessionID, receiver)
|
|
20
|
+
return receiver
|
|
21
|
+
}
|
|
22
|
+
function ensure(sessionID, session) {
|
|
23
|
+
if (disposed || deleted.has(sessionID)) return Promise.resolve()
|
|
24
|
+
if (receivers.has(sessionID)) return Promise.resolve(receivers.get(sessionID))
|
|
25
|
+
if (registrations.has(sessionID)) return registrations.get(sessionID)
|
|
26
|
+
const registration = register(sessionID, session).finally(() => registrations.delete(sessionID))
|
|
27
|
+
registrations.set(sessionID, registration)
|
|
28
|
+
return registration
|
|
29
|
+
}
|
|
30
|
+
async function close(sessionID) {
|
|
31
|
+
deleted.add(sessionID)
|
|
32
|
+
await registrations.get(sessionID)?.catch(() => {})
|
|
33
|
+
const receiver = receivers.get(sessionID)
|
|
34
|
+
receivers.delete(sessionID)
|
|
35
|
+
await receiver?.close()
|
|
36
|
+
}
|
|
37
|
+
const home = () => homeSession(context)
|
|
38
|
+
async function create(input, route, signal) {
|
|
39
|
+
if (!input.location?.directory) throw new Error("Can't determine the working directory for a new session.")
|
|
40
|
+
if (disposed) throw new Error("Annotation plugin is closed")
|
|
41
|
+
signal?.throwIfAborted()
|
|
42
|
+
const session = await context.client.session.create(input, { signal })
|
|
43
|
+
if (disposed || signal?.aborted) throw new Error("Annotation session creation was interrupted; reopen the new session in OpenCode.")
|
|
44
|
+
const receiver = await ensure(session.id, session)
|
|
45
|
+
if (!receiver || disposed) throw new Error("Annotation plugin is closed")
|
|
46
|
+
if (context.ui.router.current() === route) {
|
|
47
|
+
context.ui.dialog.clear()
|
|
48
|
+
context.ui.router.navigate({ type: "session", sessionID: session.id })
|
|
49
|
+
}
|
|
50
|
+
return receiver
|
|
51
|
+
}
|
|
52
|
+
async function newSession(sessionID) {
|
|
53
|
+
// Capture the source before awaiting. The browser cannot supply an arbitrary path/model.
|
|
54
|
+
const route = context.ui.router.current()
|
|
55
|
+
const input = sessionID ? await context.client.session.get({ sessionID }) : home()
|
|
56
|
+
if (!sessionID && route.type !== "home") throw new Error("OpenCode home is no longer open; choose a session instead.")
|
|
57
|
+
const focus = sessionID && (route.type !== "session" || route.sessionID !== sessionID) ? undefined : route
|
|
58
|
+
const receiver = await create({ location: input.location, ...(input.model ? { model: input.model } : {}) }, focus)
|
|
59
|
+
return receiver.info()
|
|
60
|
+
}
|
|
61
|
+
const route = context.ui.router.current()
|
|
62
|
+
const automatic = options.autoRegister === true
|
|
63
|
+
// A home workspace is discoverable without creating a session or starting a model.
|
|
64
|
+
const workspace = automatic ? createReceiver({ title: "OpenCode home", provider: "opencode", ...options.receiver,
|
|
65
|
+
getInfo: () => context.ui.router.current().type === "home" ? { directory: home().location?.directory || "" } : null,
|
|
66
|
+
createSession: () => newSession(),
|
|
67
|
+
}).then(async receiver => { if (disposed) await receiver.close(); return receiver }) : Promise.resolve()
|
|
68
|
+
const ready = Promise.all([workspace, automatic && route.type === "session" ? ensure(route.sessionID) : undefined])
|
|
69
|
+
ready.catch(error => {
|
|
70
|
+
if (!disposed) context.ui.toast.show({ title: "Annotate", message: `Browser connection failed: ${error.message}`, variant: "error" })
|
|
71
|
+
})
|
|
72
|
+
const onSession = event => {
|
|
73
|
+
const route = context.ui.router.current()
|
|
74
|
+
// Session events are service-wide; only expose the session active in this TUI.
|
|
75
|
+
if (route.type === "session" && route.sessionID === event.data.sessionID) void ensure(route.sessionID).catch(() => {})
|
|
76
|
+
}
|
|
77
|
+
const stops = automatic && context.data.on ? [
|
|
78
|
+
context.data.on("session.execution.started", onSession),
|
|
79
|
+
context.data.on("session.deleted", event => { void close(event.data.sessionID).catch(() => {}) }),
|
|
80
|
+
] : []
|
|
13
81
|
return {
|
|
82
|
+
ready: async () => { await ready; await Promise.all([...registrations.values()]) },
|
|
14
83
|
async run(input, sessionID, signal) {
|
|
15
|
-
if (input.trim() === "web off") {
|
|
16
|
-
await receivers.get(sessionID)?.close(); receivers.delete(sessionID)
|
|
17
|
-
context.ui.toast.show({ title: "Annotate web", message: "Browser pairing revoked for this session." })
|
|
18
|
-
return true
|
|
19
|
-
}
|
|
20
84
|
// Home has no session until the first prompt. Capture its location/model before
|
|
21
85
|
// awaiting, then create an empty destination without sending a prompt.
|
|
22
86
|
const route = context.ui.router.current()
|
|
23
|
-
const
|
|
24
|
-
const
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
if (!target) return false
|
|
87
|
+
const initial = sessionID ? undefined : home()
|
|
88
|
+
const session = sessionID ? await context.client.session.get({ sessionID }, { signal }) : undefined
|
|
89
|
+
const target = await browserTarget(input, session ? session.location?.directory : initial.location?.directory)
|
|
90
|
+
if (!target) throw new Error("Use a webpage URL or an HTML file.")
|
|
91
|
+
await ready
|
|
29
92
|
if (disposed) throw new Error("Annotation plugin is closed")
|
|
30
93
|
signal?.throwIfAborted()
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
if (disposed || signal?.aborted) return true
|
|
35
|
-
sessionID = session.id
|
|
36
|
-
// A tab switch during creation must not steal focus back from the user.
|
|
37
|
-
if (context.ui.router.current() === route) {
|
|
38
|
-
context.ui.dialog.clear()
|
|
39
|
-
context.ui.router.navigate({ type: "session", sessionID })
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
if (!receivers.has(sessionID)) {
|
|
43
|
-
const receiver = await createReceiver({ sessionID, title: session.title || sessionID, directory: session.location?.directory || "", client: context.client, ...options.receiver })
|
|
44
|
-
if (disposed) { await receiver.close(); return true }
|
|
45
|
-
receivers.set(sessionID, receiver)
|
|
46
|
-
}
|
|
94
|
+
const receiver = session ? await ensure(sessionID, session) : await create(initial, route, signal)
|
|
95
|
+
if (!receiver) throw new Error("This annotation session is no longer available")
|
|
96
|
+
if (disposed) return true
|
|
47
97
|
if (target.url) {
|
|
48
98
|
if (options.open) await options.open(target.url)
|
|
49
99
|
else await openInBrowser(target.url, options)
|
|
50
100
|
}
|
|
51
|
-
context.ui.toast.show({ title: "Annotate
|
|
101
|
+
context.ui.toast.show({ title: "Annotate", message: `Page opened. Choose ${receiver.target.title} in the Annotate extension.`, duration: 10000 })
|
|
52
102
|
return true
|
|
53
103
|
},
|
|
54
|
-
async dispose() {
|
|
104
|
+
async dispose() {
|
|
105
|
+
disposed = true
|
|
106
|
+
for (const stop of stops) stop()
|
|
107
|
+
await Promise.allSettled([...registrations.values()])
|
|
108
|
+
const homeReceiver = await workspace.catch(() => undefined)
|
|
109
|
+
await homeReceiver?.close()
|
|
110
|
+
await Promise.all([...receivers.values()].map(receiver => receiver.close()))
|
|
111
|
+
receivers.clear()
|
|
112
|
+
},
|
|
55
113
|
}
|
|
56
114
|
}
|
package/reference-command.mjs
DELETED
|
@@ -1,207 +0,0 @@
|
|
|
1
|
-
import { randomUUID } from "node:crypto"
|
|
2
|
-
import { readSession, referenceMarkdown, searchSessions } from "./session-reference.mjs"
|
|
3
|
-
import { feedbackInput } from "./delivery.mjs"
|
|
4
|
-
import { homeSession } from "./web-review.mjs"
|
|
5
|
-
|
|
6
|
-
const DIRECTORY_CAP = 28
|
|
7
|
-
const TOGGLE_SCOPE = Symbol("toggle-scope")
|
|
8
|
-
const wide = /[\u1100-\u115F\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6\u{1F300}-\u{1FAFF}\u{20000}-\u{3FFFD}]/u
|
|
9
|
-
const zeroWidth = /[\p{Mark}\u200D\uFE0F]/u
|
|
10
|
-
const characterWidth = character => zeroWidth.test(character) ? 0 : wide.test(character) ? 2 : 1
|
|
11
|
-
const textWidth = text => Array.from(text).reduce((width, character) => width + characterWidth(character), 0)
|
|
12
|
-
|
|
13
|
-
function truncateLeft(text, width) {
|
|
14
|
-
if (textWidth(text) <= width) return text
|
|
15
|
-
let result = "", used = 0
|
|
16
|
-
for (const character of Array.from(text).reverse()) {
|
|
17
|
-
const next = characterWidth(character)
|
|
18
|
-
if (used + next > width - 1) break
|
|
19
|
-
result = character + result
|
|
20
|
-
used += next
|
|
21
|
-
}
|
|
22
|
-
return `…${result}`
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
// The native footer owns a right-aligned directory column, leaving the title
|
|
26
|
-
// all remaining cells instead of reserving a fixed percentage in plugin code.
|
|
27
|
-
|
|
28
|
-
function directoryTail(directory, depth = 3) {
|
|
29
|
-
const separator = directory.includes("\\") && !directory.includes("/") ? "\\" : "/"
|
|
30
|
-
const parts = directory.split(/[\\/]/).filter(Boolean)
|
|
31
|
-
if (parts.length <= depth && textWidth(directory) <= DIRECTORY_CAP) return directory
|
|
32
|
-
const kept = parts.slice(-depth)
|
|
33
|
-
while (kept.length > 1 && textWidth(kept.join(separator)) > DIRECTORY_CAP) {
|
|
34
|
-
let widest = 0
|
|
35
|
-
for (let index = 1; index < kept.length - 1; index++) {
|
|
36
|
-
if (textWidth(kept[index]) > textWidth(kept[widest])) widest = index
|
|
37
|
-
}
|
|
38
|
-
kept.splice(widest, 1)
|
|
39
|
-
}
|
|
40
|
-
return truncateLeft(kept.join(separator), DIRECTORY_CAP)
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
export function createReferenceCommand(context, { review, promptComment }) {
|
|
44
|
-
let active
|
|
45
|
-
let disposed = false
|
|
46
|
-
const notice = (message, variant = "info") => context.ui.toast.show({
|
|
47
|
-
title: "Annotate reference", message, variant, duration: variant === "error" ? 15000 : 5000,
|
|
48
|
-
})
|
|
49
|
-
|
|
50
|
-
async function choose(current, query, allProjects, signal) {
|
|
51
|
-
let cursor
|
|
52
|
-
const seen = new Set()
|
|
53
|
-
do {
|
|
54
|
-
const page = await searchSessions(context.client, current, { query, allProjects, cursor }, signal)
|
|
55
|
-
signal.throwIfAborted()
|
|
56
|
-
const options = page.sessions.map(session => ({
|
|
57
|
-
title: session.title, value: session.sessionID,
|
|
58
|
-
footer: directoryTail(session.directory),
|
|
59
|
-
}))
|
|
60
|
-
if (page.nextCursor) options.push({ title: "More conversations…", value: "more", description: "Load the next page" })
|
|
61
|
-
if (!options.length) {
|
|
62
|
-
notice(allProjects ? "No matching conversations." : "No matching conversations in this project. Use /ref --all to search across projects.")
|
|
63
|
-
return
|
|
64
|
-
}
|
|
65
|
-
let toggle = false
|
|
66
|
-
let annotate
|
|
67
|
-
const selection = context.ui.dialog.select({
|
|
68
|
-
title: `Reference a conversation · ${allProjects ? "All projects" : "This project"}`,
|
|
69
|
-
options,
|
|
70
|
-
actions: [{
|
|
71
|
-
bind: "ctrl+a", title: allProjects ? "This project" : "All projects", selection: "none",
|
|
72
|
-
onTrigger: () => { toggle = true; context.ui.dialog.clear() },
|
|
73
|
-
}, ...(review ? [{
|
|
74
|
-
bind: "ctrl+t", title: "Annotate in TUI",
|
|
75
|
-
onTrigger: value => {
|
|
76
|
-
if (value === "more") return
|
|
77
|
-
annotate = value
|
|
78
|
-
context.ui.dialog.clear()
|
|
79
|
-
},
|
|
80
|
-
}] : [])],
|
|
81
|
-
})
|
|
82
|
-
context.ui.dialog.set({ size: "xlarge" })
|
|
83
|
-
const chosen = await selection
|
|
84
|
-
signal.throwIfAborted()
|
|
85
|
-
if (toggle) return TOGGLE_SCOPE
|
|
86
|
-
if (annotate) return { sessionID: annotate, tui: true }
|
|
87
|
-
if (chosen !== "more") return page.sessions.find(session => session.sessionID === chosen)?.sessionID
|
|
88
|
-
cursor = page.nextCursor
|
|
89
|
-
if (seen.has(cursor)) throw new Error("Session search returned a repeated page cursor.")
|
|
90
|
-
seen.add(cursor)
|
|
91
|
-
} while (cursor)
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
const attach = (sessionID, id, text, reference, resume, signal) => context.client.session.prompt(feedbackInput({
|
|
95
|
-
sessionID, id, resume,
|
|
96
|
-
text,
|
|
97
|
-
metadata: { annotateReference: { sessionID: reference.source.sessionID, capturedAt: reference.capturedAt } },
|
|
98
|
-
}), { signal })
|
|
99
|
-
|
|
100
|
-
// Before the first user message there is nothing to continue: references wait as
|
|
101
|
-
// context for that message, so several can be attached first.
|
|
102
|
-
async function destination(route, signal) {
|
|
103
|
-
if (route.type === "home") {
|
|
104
|
-
const initial = homeSession(context)
|
|
105
|
-
const directory = initial.location?.directory
|
|
106
|
-
if (!directory) throw new Error("Can't determine the working directory for a new session.")
|
|
107
|
-
const location = await context.client.location.get({ location: { directory } }, { signal })
|
|
108
|
-
return {
|
|
109
|
-
current: { projectID: location.project.id }, title: "New session", directory, fresh: true,
|
|
110
|
-
async open() {
|
|
111
|
-
const session = await context.client.session.create({ location: initial.location, ...(initial.model ? { model: initial.model } : {}) }, { signal })
|
|
112
|
-
if (context.ui.router.current().type === "home") context.ui.router.navigate({ type: "session", sessionID: session.id })
|
|
113
|
-
return session.id
|
|
114
|
-
},
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
const sessionID = route.sessionID
|
|
118
|
-
const [current, spoken] = await Promise.all([
|
|
119
|
-
context.client.session.get({ sessionID }, { signal }),
|
|
120
|
-
context.client.message.list({ sessionID, type: "user", limit: 1, order: "desc" }, { signal, headers: { "accept-encoding": "identity" } }),
|
|
121
|
-
])
|
|
122
|
-
return { current, sessionID, title: current.title ?? sessionID, fresh: !spoken.data.length, open: async () => sessionID }
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
async function run(input = "") {
|
|
126
|
-
if (disposed) return
|
|
127
|
-
if (active) return notice("A reference is already being selected.")
|
|
128
|
-
// Capture before awaiting the search; a tab change must not redirect the attachment.
|
|
129
|
-
const route = context.ui.router.current()
|
|
130
|
-
if (route.type !== "session" && route.type !== "home") return notice("Open a session first.")
|
|
131
|
-
const sessionID = route.type === "session" ? route.sessionID : undefined
|
|
132
|
-
const controller = new AbortController()
|
|
133
|
-
active = controller
|
|
134
|
-
const { signal } = controller
|
|
135
|
-
try {
|
|
136
|
-
let query = input.trim()
|
|
137
|
-
let allProjects = false
|
|
138
|
-
let tui = false
|
|
139
|
-
let flags = true
|
|
140
|
-
while (flags) {
|
|
141
|
-
if (/^--all(?:\s|$)/.test(query)) {
|
|
142
|
-
allProjects = true
|
|
143
|
-
query = query.replace(/^--all\s*/, "")
|
|
144
|
-
} else if (/^--tui(?:\s|$)/.test(query)) {
|
|
145
|
-
tui = true
|
|
146
|
-
query = query.replace(/^--tui\s*/, "")
|
|
147
|
-
} else flags = false
|
|
148
|
-
}
|
|
149
|
-
const target = await destination(route, signal)
|
|
150
|
-
const { current, fresh } = target
|
|
151
|
-
let picked
|
|
152
|
-
do {
|
|
153
|
-
picked = /^ses_\S+$/.test(query) ? query : await choose(current, query, allProjects, signal)
|
|
154
|
-
if (picked === TOGGLE_SCOPE) allProjects = !allProjects
|
|
155
|
-
} while (picked === TOGGLE_SCOPE)
|
|
156
|
-
signal.throwIfAborted()
|
|
157
|
-
if (!picked) return
|
|
158
|
-
const sourceID = typeof picked === "object" ? picked.sessionID : picked
|
|
159
|
-
tui ||= typeof picked === "object" && picked.tui
|
|
160
|
-
if (sourceID === sessionID) return notice("Choose a different conversation to reference.")
|
|
161
|
-
const reference = await readSession(context.client, { sessionID: sourceID }, signal)
|
|
162
|
-
signal.throwIfAborted()
|
|
163
|
-
if (!reference.messages.length) return notice("No completed user or assistant text in this history range. Use annotate.session_read to inspect older pages.")
|
|
164
|
-
const comment = await promptComment({
|
|
165
|
-
title: "Comment on reference (optional)",
|
|
166
|
-
placeholder: "How should the assistant use this conversation?",
|
|
167
|
-
}, signal)
|
|
168
|
-
signal.throwIfAborted()
|
|
169
|
-
if (comment == null) return
|
|
170
|
-
const outcome = fresh ? "Write your message to start the conversation." : "Continuing the conversation."
|
|
171
|
-
const label = { confirm: fresh ? "Attach" : "Attach and continue", cancel: "Cancel" }
|
|
172
|
-
const deliver = async (id, text) => attach(await target.open(), id, text, reference, !fresh, signal)
|
|
173
|
-
if (tui) {
|
|
174
|
-
if (!review) throw new Error("TUI annotation is unavailable.")
|
|
175
|
-
return await review.snapshot(sessionID ?? null, {
|
|
176
|
-
text: referenceMarkdown(reference, { comment }), snapshot: "referenced-conversation.md",
|
|
177
|
-
}, {
|
|
178
|
-
title: target.title,
|
|
179
|
-
text: annotations => referenceMarkdown(reference, { comment, annotations }),
|
|
180
|
-
confirm: ({ count, title }) => ({
|
|
181
|
-
title: "Attach annotated reference?",
|
|
182
|
-
message: `Attach ${count} ${count === 1 ? "annotation" : "annotations"} to "${title}"${fresh ? "? The assistant reads it with your first message." : " and let the assistant continue?"}`,
|
|
183
|
-
label,
|
|
184
|
-
}),
|
|
185
|
-
deliver: ({ id, text }) => deliver(id, text),
|
|
186
|
-
success: count => `Attached ${count} reference ${count === 1 ? "annotation" : "annotations"}. ${outcome}`,
|
|
187
|
-
})
|
|
188
|
-
}
|
|
189
|
-
const shortened = reference.nextCursor || reference.messages.some(message => message.nextOffset !== null)
|
|
190
|
-
const confirmed = await context.ui.dialog.confirm({
|
|
191
|
-
title: "Attach conversation reference?",
|
|
192
|
-
message: `From: ${reference.source.title}\n${reference.source.directory}\nTo: ${target.title}${target.directory ? `\n${target.directory}` : ""}\n${reference.messages.length} text messages${shortened ? " (excerpt; more history available)" : ""}. ${fresh ? "Attach this reference? The assistant reads it with your first message." : "Attach this reference and let the assistant continue?"}`,
|
|
193
|
-
label,
|
|
194
|
-
})
|
|
195
|
-
signal.throwIfAborted()
|
|
196
|
-
if (confirmed !== true) return
|
|
197
|
-
await deliver(`msg_${randomUUID().replaceAll("-", "")}`, referenceMarkdown(reference, { comment }))
|
|
198
|
-
if (!disposed) notice(`Attached “${reference.source.title}” to “${target.title}”. ${outcome}`, "success")
|
|
199
|
-
} catch (error) {
|
|
200
|
-
if (!disposed) notice(error instanceof Error ? error.message : String(error), "error")
|
|
201
|
-
} finally {
|
|
202
|
-
active = undefined
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
return { run, dispose() { disposed = true; active?.abort() } }
|
|
207
|
-
}
|
package/reference-comment.tsx
DELETED
|
@@ -1,65 +0,0 @@
|
|
|
1
|
-
import type { TextareaRenderable } from "@opentui/core"
|
|
2
|
-
import { useTerminalDimensions } from "@opentui/solid"
|
|
3
|
-
import { onMount } from "solid-js"
|
|
4
|
-
import type { Context, DialogPromptOptions } from "@opencode/plugin/tui/context"
|
|
5
|
-
|
|
6
|
-
export function promptReferenceComment(context: Context, options: DialogPromptOptions, signal: AbortSignal) {
|
|
7
|
-
signal.throwIfAborted()
|
|
8
|
-
return new Promise<string | undefined>(resolve => {
|
|
9
|
-
let settled = false
|
|
10
|
-
const finish = (value?: string, close = false) => {
|
|
11
|
-
if (settled) return
|
|
12
|
-
settled = true
|
|
13
|
-
signal.removeEventListener("abort", abort)
|
|
14
|
-
resolve(value)
|
|
15
|
-
if (close) context.ui.dialog.clear()
|
|
16
|
-
}
|
|
17
|
-
const abort = () => finish(undefined, true)
|
|
18
|
-
context.ui.dialog.show(() => {
|
|
19
|
-
let input: TextareaRenderable
|
|
20
|
-
const dimensions = useTerminalDimensions()
|
|
21
|
-
const limit = () => Math.max(1, Math.min(18, dimensions().height - 14))
|
|
22
|
-
const theme = context.theme
|
|
23
|
-
onMount(() => input.focus())
|
|
24
|
-
context.keymap.layer(() => ({
|
|
25
|
-
mode: "global",
|
|
26
|
-
target: () => input,
|
|
27
|
-
commands: [{ bind: "ctrl+c", run: () => finish(undefined, true) }],
|
|
28
|
-
}))
|
|
29
|
-
return (
|
|
30
|
-
<box paddingLeft={2} paddingRight={2} paddingBottom={1} gap={1}>
|
|
31
|
-
<text fg={theme.text.base}>{options.title}</text>
|
|
32
|
-
<box backgroundColor={theme.background.raised.high} paddingLeft={1} paddingRight={1}>
|
|
33
|
-
<textarea
|
|
34
|
-
ref={node => { input = node }}
|
|
35
|
-
initialValue={options.value ?? ""}
|
|
36
|
-
placeholder={options.placeholder}
|
|
37
|
-
height="auto"
|
|
38
|
-
minHeight={Math.min(3, limit())}
|
|
39
|
-
maxHeight={limit()}
|
|
40
|
-
flexShrink={1}
|
|
41
|
-
wrapMode="word"
|
|
42
|
-
textColor={theme.text.base}
|
|
43
|
-
backgroundColor={theme.background.raised.high}
|
|
44
|
-
focusedBackgroundColor={theme.background.raised.high}
|
|
45
|
-
placeholderColor={theme.text.muted}
|
|
46
|
-
cursorColor={theme.text.base}
|
|
47
|
-
keyBindings={[
|
|
48
|
-
{ name: "return", action: "submit" },
|
|
49
|
-
{ name: "return", shift: true, action: "newline" },
|
|
50
|
-
]}
|
|
51
|
-
onSubmit={() => finish(input.plainText, true)}
|
|
52
|
-
/>
|
|
53
|
-
</box>
|
|
54
|
-
<box flexDirection="row" flexWrap="wrap" gap={2}>
|
|
55
|
-
<text fg={theme.text.action.primary.selected} onMouseUp={() => finish(input.plainText, true)}>enter continue</text>
|
|
56
|
-
<text fg={theme.text.muted}>shift+enter newline</text>
|
|
57
|
-
<text fg={theme.text.muted} onMouseUp={() => finish(undefined, true)}>esc cancel</text>
|
|
58
|
-
</box>
|
|
59
|
-
</box>
|
|
60
|
-
)
|
|
61
|
-
}, () => finish())
|
|
62
|
-
context.ui.dialog.set({ size: "large", centered: false })
|
|
63
|
-
signal.addEventListener("abort", abort, { once: true })
|
|
64
|
-
})
|
|
65
|
-
}
|
package/server-history.mjs
DELETED
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
import { spawn } from "node:child_process"
|
|
2
|
-
import { mkdtemp, open, readFile, rm, stat } from "node:fs/promises"
|
|
3
|
-
import os from "node:os"
|
|
4
|
-
import path from "node:path"
|
|
5
|
-
|
|
6
|
-
async function execute(binary, args, { signal }) {
|
|
7
|
-
const directory = await mkdtemp(path.join(os.tmpdir(), "annotate-session-api-"))
|
|
8
|
-
const filename = path.join(directory, "response.json")
|
|
9
|
-
try {
|
|
10
|
-
// OpenCode 2.2 exits before a pipe drains past 256 KiB. A regular output file
|
|
11
|
-
// avoids truncated JSON; it stays private and is removed after every read.
|
|
12
|
-
const output = await open(filename, "wx", 0o600)
|
|
13
|
-
try {
|
|
14
|
-
await new Promise((resolve, reject) => {
|
|
15
|
-
const child = spawn(binary, args, { signal, timeout: 30000, stdio: ["ignore", output.fd, "pipe"] })
|
|
16
|
-
let errorText = ""
|
|
17
|
-
child.stderr.on("data", chunk => { errorText = (errorText + chunk).slice(-16000) })
|
|
18
|
-
child.once("error", reject)
|
|
19
|
-
child.once("close", (code, termination) => {
|
|
20
|
-
if (code === 0) resolve()
|
|
21
|
-
else reject(new Error(`OpenCode history request failed (${termination ?? code}): ${errorText.trim()}`))
|
|
22
|
-
})
|
|
23
|
-
})
|
|
24
|
-
} finally {
|
|
25
|
-
await output.close()
|
|
26
|
-
}
|
|
27
|
-
signal?.throwIfAborted()
|
|
28
|
-
if ((await stat(filename)).size > 32 * 1024 * 1024) throw new Error("History page exceeds 32 MiB. Read a specific message instead.")
|
|
29
|
-
return { stdout: await readFile(filename, "utf8") }
|
|
30
|
-
} finally {
|
|
31
|
-
await rm(directory, { recursive: true, force: true })
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
// V2.2's plugin context lacks message.list/get; session.context loses pre-compaction
|
|
36
|
-
// history. The official CLI supplies authenticated HTTP access without reading the DB.
|
|
37
|
-
// Fail closed for standalone/embedded servers rather than discovering another server.
|
|
38
|
-
export async function serverHistoryClient(context, signal, { run = execute, processID = process.pid } = {}) {
|
|
39
|
-
async function get(route, request = {}) {
|
|
40
|
-
const { stdout } = await run("opencode", ["api", "get", route, "--header", "Accept-Encoding:identity"], {
|
|
41
|
-
signal: request.signal ?? signal,
|
|
42
|
-
})
|
|
43
|
-
return JSON.parse(stdout)
|
|
44
|
-
}
|
|
45
|
-
const server = await get("/api/info")
|
|
46
|
-
if (server.pid !== processID) {
|
|
47
|
-
throw new Error("Full-history tools require this plugin to run in the managed OpenCode service. The discovered server is a different process; use /ref in the connected TUI instead.")
|
|
48
|
-
}
|
|
49
|
-
return {
|
|
50
|
-
session: {
|
|
51
|
-
get: (input, options) => context.session.get(input, options),
|
|
52
|
-
message: { get: async ({ sessionID, messageID }, options) =>
|
|
53
|
-
(await get(`/api/session/${encodeURIComponent(sessionID)}/message/${encodeURIComponent(messageID)}`, options)).data },
|
|
54
|
-
},
|
|
55
|
-
message: { list: ({ sessionID, ...query }, options) =>
|
|
56
|
-
get(`/api/session/${encodeURIComponent(sessionID)}/message?${new URLSearchParams(query)}`, options) },
|
|
57
|
-
}
|
|
58
|
-
}
|