opencode-wordcomplete 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,21 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here.
4
+
5
+ ## [0.1.0]
6
+
7
+ ### Added
8
+
9
+ - Vim-style word completion for the OpenCode TUI prompt: `ctrl+n` and `ctrl+p`
10
+ cycle candidates taken from your own chat history.
11
+ - Vocabulary loaded once at startup from the OpenCode SQLite database, read-only.
12
+ - Palette command **Word completion: reload chat vocabulary**.
13
+
14
+ ### Changed
15
+
16
+ - Completions are accepted with `tab` instead of `ctrl+y`; set `acceptKey` to
17
+ restore the old key.
18
+
19
+ ### Fixed
20
+
21
+ - The vocabulary reload command now appears in the command palette.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pim Snel
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,134 @@
1
- # Temporary Holding Version
1
+ # opencode-wordcomplete
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Vim-style word completion for the OpenCode TUI prompt. Press `ctrl+n` on a partly
4
+ typed word and it suggests words from your own chat history, including the
5
+ prompts you wrote. `ctrl+p` walks back, `tab` accepts.
6
+
7
+ ## How it works
8
+
9
+ The plugin reads the OpenCode SQLite database read-only at startup, collects
10
+ every word of three characters or more from your user prompts and the assistant
11
+ text replies, and keeps a vocabulary in memory with the newest occurrence of each
12
+ word. On every keypress it looks at the word under the cursor and offers the
13
+ matching words, newest first.
14
+
15
+ Nothing leaves your machine and the database is never written to.
16
+
17
+ ## Install
18
+
19
+ Add the published package to `~/.config/opencode/cli.json`, pinned to a version:
20
+
21
+ ```json
22
+ {
23
+ "plugins": ["opencode-wordcomplete@0.1.0"]
24
+ }
25
+ ```
26
+
27
+ The CLI resolves the package from the registry, so a separate install is not
28
+ required. If you prefer to own the installed copy, install it globally first:
29
+
30
+ ```bash
31
+ npm install -g opencode-wordcomplete
32
+ ```
33
+
34
+ Plugin options go in the object form:
35
+
36
+ ```json
37
+ {
38
+ "plugins": [
39
+ {
40
+ "package": "opencode-wordcomplete@0.1.0",
41
+ "options": {}
42
+ }
43
+ ]
44
+ }
45
+ ```
46
+
47
+ To run a local checkout instead, point at the directory:
48
+
49
+ ```json
50
+ {
51
+ "plugins": [
52
+ {
53
+ "package": "/home/you/gh.mipmip/opencode-wordcomplete",
54
+ "options": {}
55
+ }
56
+ ]
57
+ }
58
+ ```
59
+
60
+ Restart is not needed. The TUI reloads `cli.json` and starts the plugin.
61
+
62
+ ## Keys
63
+
64
+ | Key | Action |
65
+ | -------- | ------------------------------------------ |
66
+ | `ctrl+n` | next completion |
67
+ | `ctrl+p` | previous completion |
68
+ | `tab` | accept the shown completion |
69
+ | `escape` | dismiss, or the host's own escape behaviour |
70
+
71
+ The suggestion line appears in the prompt footer, for example
72
+ `tab completion 3/17`.
73
+
74
+ ## Options
75
+
76
+ | Option | Default | Meaning |
77
+ | --------------- | -------- | ------------------------------------------- |
78
+ | `enabled` | `true` | turn the plugin off without removing it |
79
+ | `acceptKey` | `tab` | key that inserts the completion |
80
+ | `nextKey` | `ctrl+n` | key for the next candidate |
81
+ | `prevKey` | `ctrl+p` | key for the previous candidate |
82
+ | `minPrefix` | `2` | shortest prefix that triggers a suggestion |
83
+ | `maxCandidates` | `50` | how many matches are collected per prefix |
84
+ | `debug` | `false` | append diagnostics to `/tmp/opencode-wordcomplete-diag.log` |
85
+
86
+ ## Caveats
87
+
88
+ - OpenCode V2 has no API for reading or writing the prompt. The plugin uses the
89
+ host editor through `renderer.currentFocusedEditor`, which is not part of the
90
+ plugin API and may change between releases.
91
+ - Because of that, completion only works at the end of the prompt text.
92
+ - `ctrl+n` and `ctrl+p` are also the host bindings for the built-in `@` and `/`
93
+ autocomplete. The plugin returns `false` when it has no candidates, so the
94
+ built-in menu keeps working.
95
+ - `tab` is only taken while a completion is shown, so tab indentation is
96
+ unavailable in that moment. Set `acceptKey` to `ctrl+y` for the old key.
97
+ - The vocabulary is loaded at startup. Use the palette command
98
+ **Word completion: reload chat vocabulary** after a long session.
99
+
100
+ ## Development
101
+
102
+ ```bash
103
+ bun install
104
+ bun run build
105
+ bun run typecheck
106
+ bun test
107
+ bun run test:coverage
108
+ bun run check-pack
109
+ nix flake check
110
+ ```
111
+
112
+ `check-pack` reads `npm pack --dry-run --json` and fails when the tarball holds
113
+ anything outside `dist/`, `README.md`, `CHANGELOG.md`, `LICENSE` and
114
+ `package.json`, or misses one of the entry files.
115
+
116
+ `dist/` is committed so the repository can be used as a plugin path straight
117
+ from a checkout.
118
+
119
+ ### Release
120
+
121
+ ```bash
122
+ scripts/release.sh 0.1.0
123
+ ```
124
+
125
+ The script refuses a dirty working copy, a version that is not `x.y.z`, and a
126
+ version without a matching `## [x.y.z]` section in `CHANGELOG.md`. It then runs
127
+ `nix flake check`, sets the version, publishes to npm, commits the bump, moves
128
+ the `main` bookmark, and pushes `main` and the git tag.
129
+
130
+ Preview the steps without changing the tree:
131
+
132
+ ```bash
133
+ scripts/release.sh --dry-run 0.1.0
134
+ ```
package/dist/index.js ADDED
@@ -0,0 +1,10 @@
1
+ // src/index.ts
2
+ import { Plugin } from "@opencode/plugin";
3
+ var index_default = Plugin.define({
4
+ id: "wordcomplete.server",
5
+ setup() {
6
+ }
7
+ });
8
+ export {
9
+ index_default as default
10
+ };
package/dist/tui.js ADDED
@@ -0,0 +1,279 @@
1
+ // src/tui.tsx
2
+ import { Plugin } from "@opencode/plugin/tui";
3
+ import { createSignal, Show } from "solid-js";
4
+ import { appendFileSync } from "node:fs";
5
+
6
+ // src/words.ts
7
+ import { Database } from "bun:sqlite";
8
+ import { existsSync, readdirSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { isAbsolute, join } from "node:path";
11
+ var MAX_MESSAGES = 4e3;
12
+ var MIN_WORD = 3;
13
+ var MAX_WORD = 40;
14
+ var DB_FILE = "opencode.db";
15
+ function dataDir() {
16
+ const xdg = process.env.XDG_DATA_HOME?.trim();
17
+ const base = xdg ? xdg : join(homedir(), ".local", "share");
18
+ return join(base, "opencode");
19
+ }
20
+ function existingDbIn(dir) {
21
+ const preferred = join(dir, DB_FILE);
22
+ if (existsSync(preferred)) return preferred;
23
+ try {
24
+ const candidates = readdirSync(dir).filter((name) => /^opencode-.*\.db$/.test(name)).sort();
25
+ const last = candidates[candidates.length - 1];
26
+ if (last) return join(dir, last);
27
+ } catch {
28
+ return void 0;
29
+ }
30
+ return void 0;
31
+ }
32
+ function databasePath() {
33
+ const override = process.env.OPENCODE_DB?.trim();
34
+ if (override) {
35
+ if (override === ":memory:") return override;
36
+ return isAbsolute(override) ? override : join(dataDir(), override);
37
+ }
38
+ return existingDbIn(dataDir()) ?? join(dataDir(), DB_FILE);
39
+ }
40
+ function tokenize(text) {
41
+ const out = [];
42
+ for (const match of text.matchAll(/[\p{L}\p{N}_]+/gu)) {
43
+ const token = match[0];
44
+ if (token.length >= MIN_WORD && token.length <= MAX_WORD) out.push(token);
45
+ }
46
+ return out;
47
+ }
48
+ function rows(db) {
49
+ const tables = new Set(
50
+ db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(
51
+ (row) => row.name
52
+ )
53
+ );
54
+ if (tables.has("session_message")) {
55
+ return db.query(
56
+ `SELECT type, data, time_created AS time
57
+ FROM session_message
58
+ WHERE type IN ('user', 'assistant')
59
+ ORDER BY time_created DESC
60
+ LIMIT ${MAX_MESSAGES}`
61
+ ).all();
62
+ }
63
+ return db.query(
64
+ `SELECT json_extract(m.data, '$.role') AS type,
65
+ json_object('text', json_extract(p.data, '$.text')) AS data,
66
+ m.time_created AS time
67
+ FROM message m
68
+ JOIN part p ON p.message_id = m.id
69
+ WHERE json_extract(p.data, '$.type') = 'text'
70
+ ORDER BY m.time_created DESC
71
+ LIMIT ${MAX_MESSAGES}`
72
+ ).all();
73
+ }
74
+ function textOf(row) {
75
+ let parsed;
76
+ try {
77
+ parsed = JSON.parse(row.data);
78
+ } catch {
79
+ return "";
80
+ }
81
+ const data = parsed;
82
+ if (row.type === "user") return typeof data.text === "string" ? data.text : "";
83
+ if (!Array.isArray(data.content)) return "";
84
+ return data.content.filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ");
85
+ }
86
+ function loadWords() {
87
+ let db;
88
+ try {
89
+ db = new Database(databasePath(), { readonly: true });
90
+ } catch {
91
+ return [];
92
+ }
93
+ try {
94
+ const byLower = /* @__PURE__ */ new Map();
95
+ for (const row of rows(db)) {
96
+ for (const token of tokenize(textOf(row))) {
97
+ const lower = token.toLowerCase();
98
+ const known = byLower.get(lower);
99
+ if (known) {
100
+ known.count++;
101
+ if (row.time > known.seen) known.seen = row.time;
102
+ } else {
103
+ byLower.set(lower, { text: token, lower, count: 1, seen: row.time });
104
+ }
105
+ }
106
+ }
107
+ return [...byLower.values()];
108
+ } catch {
109
+ return [];
110
+ } finally {
111
+ db.close();
112
+ }
113
+ }
114
+ function matchPrefix(prefix, words, limit = 100) {
115
+ const lower = prefix.toLowerCase();
116
+ if (lower.length < RESOLVE_MIN) return [];
117
+ return words.filter((word) => word.lower !== lower && word.lower.startsWith(lower)).sort((left, right) => right.seen - left.seen || right.count - left.count).slice(0, limit);
118
+ }
119
+ var RESOLVE_MIN = 2;
120
+ function trailingPrefix(text) {
121
+ const match = text.match(/[\p{L}\p{N}_]+$/u);
122
+ return match ? match[0] : "";
123
+ }
124
+
125
+ // src/tui.tsx
126
+ import { jsx } from "@opentui/solid/jsx-runtime";
127
+ var POLL_MS = 50;
128
+ var LOG = "/tmp/opencode-wordcomplete-diag.log";
129
+ var registryKey = "__opencodeWordcompleteRegistry";
130
+ var registry = globalThis[registryKey] ??= {};
131
+ var normalizeKey = (value, fallback) => typeof value === "string" && value.trim() ? value.trim() : fallback;
132
+ var tui_default = Plugin.define({
133
+ id: "wordcomplete",
134
+ setup(context) {
135
+ const options = context.options ?? {};
136
+ if (options.enabled === false) return;
137
+ const acceptKey = normalizeKey(options.acceptKey, "tab");
138
+ const nextKey = normalizeKey(options.nextKey, "ctrl+n");
139
+ const prevKey = normalizeKey(options.prevKey, "ctrl+p");
140
+ const minPrefix = typeof options.minPrefix === "number" ? options.minPrefix : 2;
141
+ const maxCandidates = typeof options.maxCandidates === "number" ? options.maxCandidates : 50;
142
+ const debug = options.debug === true;
143
+ const log = (message) => {
144
+ if (!debug) return;
145
+ try {
146
+ appendFileSync(LOG, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}
147
+ `);
148
+ } catch {
149
+ }
150
+ };
151
+ let words = loadWords();
152
+ let lastText = "";
153
+ let prefix = "";
154
+ let candidates = [];
155
+ let index = 0;
156
+ let dismissed = "";
157
+ const [label, setLabel] = createSignal("");
158
+ const editor = () => context.renderer.currentFocusedEditor;
159
+ const render = () => {
160
+ if (dismissed === lastText) {
161
+ setLabel("");
162
+ return;
163
+ }
164
+ const word = candidates[index];
165
+ if (!word) {
166
+ setLabel("");
167
+ return;
168
+ }
169
+ const counter = candidates.length > 1 ? ` ${index + 1}/${candidates.length}` : "";
170
+ setLabel(`${acceptKey} ${word.text}${counter}`);
171
+ };
172
+ const refresh = (text) => {
173
+ lastText = text;
174
+ prefix = trailingPrefix(text);
175
+ candidates = prefix.length >= minPrefix ? matchPrefix(prefix, words, maxCandidates) : [];
176
+ index = 0;
177
+ render();
178
+ };
179
+ const poll = () => {
180
+ const text = editor()?.plainText;
181
+ if (typeof text !== "string" || text === lastText) return;
182
+ refresh(text);
183
+ log(`input=${JSON.stringify(text.slice(-40))} prefix=${prefix} candidates=${candidates.length}`);
184
+ };
185
+ const accept = () => {
186
+ const word = candidates[index];
187
+ const target = editor();
188
+ if (!word || !target?.setText) return false;
189
+ const next = lastText.slice(0, lastText.length - prefix.length) + word.text;
190
+ target.setText(next);
191
+ target.gotoBufferEnd?.();
192
+ lastText = next;
193
+ dismissed = next;
194
+ prefix = "";
195
+ candidates = [];
196
+ index = 0;
197
+ setLabel("");
198
+ log(`accept=${word.text}`);
199
+ return;
200
+ };
201
+ const step = (delta) => {
202
+ if (candidates.length === 0) return false;
203
+ dismissed = "";
204
+ index = (index + delta + candidates.length) % candidates.length;
205
+ render();
206
+ log(`step=${delta} index=${index + 1}/${candidates.length}`);
207
+ return;
208
+ };
209
+ const dismiss = () => {
210
+ if (!label()) return false;
211
+ dismissed = lastText;
212
+ setLabel("");
213
+ return;
214
+ };
215
+ const unregister = context.ui.slot({
216
+ prepend: "prompt.footer",
217
+ render: () => /* @__PURE__ */ jsx(Show, { when: label(), children: /* @__PURE__ */ jsx("text", { fg: context.theme.text.muted, children: label() }) })
218
+ });
219
+ context.keymap.layer(() => ({
220
+ mode: "global",
221
+ priority: 20,
222
+ commands: [
223
+ {
224
+ id: "wordcomplete.next",
225
+ title: "Complete word: next",
226
+ group: "Word completion",
227
+ bind: nextKey,
228
+ run: () => step(1)
229
+ },
230
+ {
231
+ id: "wordcomplete.prev",
232
+ title: "Complete word: previous",
233
+ group: "Word completion",
234
+ bind: prevKey,
235
+ run: () => step(-1)
236
+ },
237
+ {
238
+ id: "wordcomplete.accept",
239
+ title: "Complete word: accept",
240
+ group: "Word completion",
241
+ bind: acceptKey,
242
+ run: () => accept()
243
+ },
244
+ {
245
+ id: "wordcomplete.dismiss",
246
+ title: "Complete word: dismiss",
247
+ group: "Word completion",
248
+ bind: "escape",
249
+ run: () => dismiss()
250
+ },
251
+ {
252
+ id: "wordcomplete.reload",
253
+ title: "Word completion: reload chat vocabulary",
254
+ group: "Word completion",
255
+ palette: true,
256
+ run: () => {
257
+ words = loadWords();
258
+ refresh(editor()?.plainText ?? "");
259
+ context.ui.toast.show({ message: `Vocabulary reloaded: ${words.length} words` });
260
+ }
261
+ }
262
+ ],
263
+ bindings: ["wordcomplete.next", "wordcomplete.prev", "wordcomplete.accept", "wordcomplete.dismiss"]
264
+ }));
265
+ const timer = setInterval(poll, POLL_MS);
266
+ log(`setup words=${words.length} accept=${acceptKey} next=${nextKey} prev=${prevKey}`);
267
+ const dispose = () => {
268
+ clearInterval(timer);
269
+ unregister();
270
+ log("dispose");
271
+ };
272
+ registry.dispose?.();
273
+ registry.dispose = dispose;
274
+ return dispose;
275
+ }
276
+ });
277
+ export {
278
+ tui_default as default
279
+ };
package/package.json CHANGED
@@ -1,6 +1,69 @@
1
1
  {
2
2
  "name": "opencode-wordcomplete",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Vim-style word completion for the OpenCode TUI prompt, sourced from your chat history",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/mipmip/opencode-wordcomplete"
9
+ },
10
+ "homepage": "https://github.com/mipmip/opencode-wordcomplete#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/mipmip/opencode-wordcomplete/issues"
13
+ },
14
+ "keywords": [
15
+ "opencode",
16
+ "plugin",
17
+ "tui",
18
+ "completion",
19
+ "autocomplete",
20
+ "vim"
21
+ ],
22
+ "engines": {
23
+ "bun": ">=1.1.0",
24
+ "node": ">=20.0.0"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "CHANGELOG.md",
30
+ "LICENSE"
31
+ ],
32
+ "type": "module",
33
+ "main": "./dist/index.js",
34
+ "exports": {
35
+ ".": {
36
+ "types": "./dist/index.d.ts",
37
+ "default": "./dist/index.js"
38
+ },
39
+ "./tui": {
40
+ "types": "./dist/tui.d.ts",
41
+ "default": "./dist/tui.js"
42
+ }
43
+ },
44
+ "scripts": {
45
+ "build": "esbuild src/index.ts src/tui.tsx --bundle --format=esm --platform=node --jsx=automatic --jsx-import-source=@opentui/solid --outdir=dist --external:@opentui/core --external:@opentui/solid --external:@opentui/keymap --external:solid-js --external:@opencode/plugin --external:bun:sqlite",
46
+ "typecheck": "tsc -p tsconfig.json --noEmit",
47
+ "test": "bun test",
48
+ "test:coverage": "bun test --coverage --coverage-reporter=lcov && bun scripts/coverage-gate.ts",
49
+ "check-pack": "bun scripts/check-pack.ts"
50
+ },
51
+ "peerDependencies": {
52
+ "@opentui/core": ">=0.6.6",
53
+ "@opentui/solid": ">=0.6.6",
54
+ "solid-js": ">=1.9.0"
55
+ },
56
+ "dependencies": {
57
+ "@opencode/plugin": ">=2.3.0"
58
+ },
59
+ "devDependencies": {
60
+ "@opencode/theme": "latest",
61
+ "@opentui/core": "latest",
62
+ "@opentui/solid": "latest",
63
+ "@types/bun": "latest",
64
+ "@types/node": "latest",
65
+ "esbuild": "latest",
66
+ "solid-js": "^1.9.0",
67
+ "typescript": "latest"
68
+ }
69
+ }