opencode-quill 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,20 @@
1
+ # Changelog
2
+
3
+ All notable changes are documented in this file using
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
5
+ [Semantic Versioning](https://semver.org/).
6
+
7
+ ## [0.1.0] - 2026-10-10
8
+
9
+ ### Added
10
+
11
+ - Local word autocomplete and next-word prediction plugin for OpenCode V2.
12
+ - High-frequency English vocabulary prior derived from SUBTLEX word frequencies.
13
+ - Online absolute-discounting n-gram model learning from submitted session prompts.
14
+ - Inline ghost-text rendering at visual cursor with matching Ghost dim level (`0.55`).
15
+ - Safe acceptance (<kbd>Tab</kbd>, <kbd>→</kbd>) and dismissal (<kbd>Esc</kbd>) without draft submission.
16
+ - Prose-aware filtering suppressing suggestions in code, paths, URLs, and shell commands.
17
+ - `/quill` command and command palette action to toggle autocomplete.
18
+ - Local installer script, full test suite, CI workflows, and release tooling.
19
+
20
+ [0.1.0]: https://github.com/ozandogrultan/opencode-quill/releases/tag/v0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ozan Dogrultan
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,221 @@
1
- # Temporary Holding Version
1
+ # opencode-quill
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
+ [![CI](https://github.com/ozandogrultan/opencode-quill/actions/workflows/ci.yml/badge.svg)](https://github.com/ozandogrultan/opencode-quill/actions/workflows/ci.yml)
4
+
5
+ Local word autocomplete and next-word prediction for the **OpenCode V2** prompt
6
+ composer — inspired by [oh-my-pi (OMP)](https://github.com/can1357/oh-my-pi)'s
7
+ n-gram text prediction engine.
8
+
9
+ As you type, Quill predicts the remainder of your current prose word or the next
10
+ word in sequence, shown as dimmed inline ghost text directly at your cursor.
11
+ Press <kbd>Tab</kbd> or <kbd>→</kbd> to accept it, or <kbd>Esc</kbd> to dismiss.
12
+
13
+ ```text
14
+ > can you refactor the test
15
+ s ← dimmed ghost text, Tab or → to accept
16
+ ```
17
+
18
+ ## What it does
19
+
20
+ - **Zero AI, completely local:** Runs entirely on-device without sending prompt
21
+ text to any model, API, or external service. Query latency is under 0.05 ms.
22
+ - **Context-aware ranking:** Blends a high-frequency English vocabulary prior
23
+ with an online absolute-discounting n-gram model (bigrams and trigrams)
24
+ learned dynamically from your submitted prompt history.
25
+ - **Completes words and predicts next words:** Completes the active word
26
+ prefix as you type (`refac` → `tor`) and predicts following words after a space
27
+ (`please run ` → `tests`) when prior evidence supports the sequence.
28
+ - **Ghost-text styling:** Matches [opencode-ghost](https://github.com/ozandogrultan/opencode-ghost)'s
29
+ dimmed appearance (`0.55` opacity over the theme's muted text color),
30
+ rendering seamlessly in the OpenTUI buffer without displacing cursor position.
31
+ - **Safe acceptance:** Inserts editable text into the draft without submitting.
32
+ Supports native undo (<kbd>Ctrl+-</kbd> or <kbd>Cmd+Z</kbd>). Never overwrites
33
+ existing text and never touches the system clipboard.
34
+ - **Coexists with Ghost:** [Ghost](https://github.com/ozandogrultan/opencode-ghost)
35
+ suggests entire next prompts in an *empty* composer using a model; Quill
36
+ predicts words in an *active* draft locally. When both are installed, each
37
+ activates only in its respective domain without key conflicts.
38
+ - **Prose-aware gating:** Automatically suppresses suggestions in code blocks,
39
+ backticks, file paths, URLs, slash commands, shell executions, active selections,
40
+ and modal dialogs.
41
+
42
+ ## Requirements
43
+
44
+ - [OpenCode](https://opencode.ai) ≥ 2.0.26 (V2 TUI plugin runtime).
45
+ - Node.js (for the installer script).
46
+
47
+ ## Install
48
+
49
+ ### From this repository (recommended)
50
+
51
+ ```sh
52
+ git clone https://github.com/ozandogrultan/opencode-quill.git
53
+ cd opencode-quill
54
+ bun install
55
+ ./install.sh
56
+ ```
57
+
58
+ Restart OpenCode to load it. `install.sh` copies the plugin and its local
59
+ vocabulary into `<config>/plugins/opencode-quill/` and registers that directory
60
+ in `<config>/cli.json`. Unrelated plugins and configuration are preserved.
61
+
62
+ To target a specific configuration directory:
63
+
64
+ ```sh
65
+ ./install.sh /path/to/config/opencode
66
+ ```
67
+
68
+ ### Manually
69
+
70
+ Add the plugin directory to `plugins` in `~/.config/opencode/cli.json`:
71
+
72
+ ```jsonc
73
+ {
74
+ "$schema": "https://opencode.ai/v2/cli.json",
75
+ "plugins": [
76
+ "/absolute/path/to/opencode-quill/src"
77
+ ]
78
+ }
79
+ ```
80
+
81
+ To pass custom options:
82
+
83
+ ```jsonc
84
+ {
85
+ "$schema": "https://opencode.ai/v2/cli.json",
86
+ "plugins": [
87
+ {
88
+ "package": "/absolute/path/to/opencode-quill/src",
89
+ "options": {
90
+ "enabled": true,
91
+ "acceptKeys": ["tab", "right"],
92
+ "dismissKeys": ["escape"]
93
+ }
94
+ }
95
+ ]
96
+ }
97
+ ```
98
+
99
+ Restart OpenCode after editing `cli.json`.
100
+
101
+ ## Options
102
+
103
+ | Option | Type | Default | Description |
104
+ | --- | --- | --- | --- |
105
+ | `enabled` | `boolean` | `true` | Enables or disables suggestions; can also be toggled with `/quill`. |
106
+ | `acceptKeys` | `string[]` | `["tab", "right"]` | Keys that accept and insert the active word suggestion. |
107
+ | `dismissKeys` | `string[]` | `["escape"]` | Keys that dismiss the visible suggestion without inserting. |
108
+
109
+ Custom keybindings can also be overridden using OpenCode's standard
110
+ `keybinds` map in `cli.json`:
111
+
112
+ ```jsonc
113
+ {
114
+ "keybinds": {
115
+ "quill.accept": "ctrl+y",
116
+ "quill.dismiss": "ctrl+g"
117
+ }
118
+ }
119
+ ```
120
+
121
+ ## Commands
122
+
123
+ - `/quill` — Toggle word autocomplete on or off (persisted across sessions).
124
+ - **Command Palette (`Ctrl+P`)** — Includes **Word autocomplete: on/off**.
125
+
126
+ ## Learning and Prediction Architecture
127
+
128
+ ### 1. How Quill Learns
129
+
130
+ Quill listens to OpenCode session events in real time:
131
+ - `session.execution.started` (prompt submitted)
132
+ - `session.execution.succeeded` (turn completed)
133
+ - `session.inbox.delivered` (message delivered to a session)
134
+
135
+ When a message is received:
136
+ 1. **Deduplication:** Message IDs (`<sessionID>:<messageID>`) are checked against
137
+ a rolling set of up to 8,000 processed messages so each prompt is ingested once.
138
+ 2. **Prose Sanitization:** Text is stripped of markdown fenced code blocks, inline
139
+ backticks, URLs, file paths (`foo/bar.ts`), camelCase identifiers, slash commands
140
+ (`/command`), shell lines (`$ ...`), and lines indented by 4+ spaces.
141
+ 3. **Sequence Splitting:** Consecutive prose words delimited by spaces or punctuation
142
+ are partitioned into independent grammatical clauses. Punctuation (`.`, `,`, `!`, `?`)
143
+ and code snippets reset the context window so words separated by syntax are never
144
+ learned as adjacent phrases.
145
+ 4. **Vocabulary Hygiene:** New words not present in the base dictionary must appear
146
+ at least **twice** across distinct prompts before becoming suggestible candidates.
147
+ This prevents accidental typos or one-off strings from entering your suggestions.
148
+ Pasted blocks exceeding 4,000 characters or 12 lines are ignored.
149
+
150
+ ### 2. How Predictions Grow
151
+
152
+ The language model consists of two tiers:
153
+
154
+ - **Baseline Prior:** A static unigram frequency table of 20,000 common English words
155
+ derived from the open-source SUBTLEX corpus. Provides instant, high-quality
156
+ spelling completions from your very first keystroke.
157
+ - **Personal N-Gram Model:** Increments frequency counts as you submit prompts:
158
+ - **Unigrams** (`w`): Individual word frequencies.
159
+ - **Bigrams** (`u → w`): Transition frequencies from previous word `u`.
160
+ - **Trigrams** (`u, v → w`): Transition frequencies from two preceding words `u, v`.
161
+
162
+ **Scoring & Interpolation:**
163
+ Candidates are scored using Jelinek-Mercer interpolation combined with absolute
164
+ discounting ($D = 0.5$):
165
+
166
+ $$\text{score}(w \mid u, v) = \max\left(\frac{c(u, v, w) - D}{c(u, v)}, 0\right) + \frac{D \cdot |\{w : c(u, v, w) > 0\}|}{c(u, v)} \cdot \text{score}(w \mid v)$$
167
+
168
+ If strong trigram evidence exists, the contextual prediction dominates. As context
169
+ thins out, the model falls back gracefully to bigram transitions and then unigram
170
+ frequencies.
171
+
172
+ **Prefix-Constrained Posterior:**
173
+ When you type a prefix (e.g. `refac`), all candidates matching the prefix—including
174
+ the prefix itself if it is already a complete word—are ranked. A suggestion is only
175
+ displayed when its calibrated confidence exceeds a quality threshold (30% for prefix
176
+ completions, 55% for next-word predictions). If the typed prefix is already the most
177
+ probable word, no ghost text is shown.
178
+
179
+ **Bounded Capacity:**
180
+ To keep memory and storage footprint minimal, the personal model enforces strict caps:
181
+ - Words: Top 8,000 most frequent entries
182
+ - Bigrams: Top 30,000 transitions
183
+ - Trigrams: Top 30,000 transitions
184
+ - Message deduplication log: 8,000 IDs
185
+
186
+ ### 3. Where State is Stored
187
+
188
+ Quill uses OpenCode V2's durable plugin storage API (`context.storage.store`), which
189
+ persists state as clean JSON files inside your standard XDG state directory:
190
+
191
+ | Setting / Data | File Path |
192
+ | --- | --- |
193
+ | **Learned Model** | `~/.local/state/opencode/<channel>/tui/plugin.quill.learning.json` |
194
+ | **Plugin Settings** | `~/.local/state/opencode/<channel>/tui/plugin.quill.settings.json` |
195
+
196
+ *(On systems with `$XDG_STATE_HOME` set, `$XDG_STATE_HOME/opencode/<channel>/tui/` is used).*
197
+
198
+ **Privacy Guarantee:**
199
+ - The snapshot file stores **only token frequency pairs** (e.g. `["refactor", 12]`, `["run\0tests", 5]`)
200
+ and hashed message IDs.
201
+ - **Raw prompt text is never written to disk or stored in snapshots.**
202
+ - The storage files stay strictly on your local machine and are never tracked in Git
203
+ or included in npm packages.
204
+
205
+ ## Development
206
+
207
+ ```sh
208
+ bun install
209
+ bun run test # Unit tests and changelog checks
210
+ bun run typecheck # Type verification (tsc --noEmit)
211
+ bun run lint:sh # Syntax verification on shell scripts
212
+ ```
213
+
214
+ ## Contributing
215
+
216
+ Contributions are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) and
217
+ [AGENTS.md](AGENTS.md) before submitting a pull request.
218
+
219
+ ## License
220
+
221
+ [MIT](LICENSE) © Ozan Dogrultan
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "opencode-quill",
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": "Local word autocomplete for the OpenCode V2 prompt composer.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Ozan Dogrultan",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/ozandogrultan/opencode-quill.git"
11
+ },
12
+ "homepage": "https://github.com/ozandogrultan/opencode-quill#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/ozandogrultan/opencode-quill/issues"
15
+ },
16
+ "keywords": [
17
+ "opencode",
18
+ "opencode-plugin",
19
+ "tui",
20
+ "autocomplete",
21
+ "autosuggest",
22
+ "ngram",
23
+ "prompt"
24
+ ],
25
+ "exports": {
26
+ "./tui": "./src/tui.tsx"
27
+ },
28
+ "files": [
29
+ "src",
30
+ "tsconfig.json",
31
+ "CHANGELOG.md",
32
+ "LICENSE",
33
+ "README.md"
34
+ ],
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "packageManager": "bun@1.4.2",
39
+ "engines": {
40
+ "opencode": ">=2.0.26"
41
+ },
42
+ "scripts": {
43
+ "prepare": "husky",
44
+ "test": "bun test && bash tests/changelog.sh",
45
+ "test:unit": "bun test",
46
+ "test:changelog": "bash tests/changelog.sh",
47
+ "typecheck": "tsc --noEmit",
48
+ "lint:sh": "for script in install.sh tests/*.sh scripts/*.sh; do bash -n \"$script\" || exit; done",
49
+ "prepublishOnly": "bun run test && bun run typecheck"
50
+ },
51
+ "dependencies": {
52
+ "subtlex-word-frequencies": "2.0.0"
53
+ },
54
+ "peerDependencies": {
55
+ "@opencode/plugin": "*",
56
+ "@opentui/core": ">=0.5.17",
57
+ "@opentui/solid": ">=0.5.17",
58
+ "solid-js": "*"
59
+ },
60
+ "devDependencies": {
61
+ "@commitlint/cli": "^21.2.2",
62
+ "@commitlint/config-conventional": "^21.2.2",
63
+ "@opencode/plugin": "2.0.26",
64
+ "@opentui/core": "^0.5.17",
65
+ "@opentui/solid": "^0.5.17",
66
+ "@types/bun": "^1.4.2",
67
+ "@types/node": "24.12.2",
68
+ "husky": "^9.1.7",
69
+ "solid-js": "1.9.12",
70
+ "typescript": "7.0.2"
71
+ }
72
+ }
@@ -0,0 +1,4 @@
1
+ declare module "subtlex-word-frequencies" {
2
+ const frequencies: readonly { word: string; count: number }[]
3
+ export default frequencies
4
+ }
package/src/ghost.ts ADDED
@@ -0,0 +1,142 @@
1
+ import { RGBA, type CliRenderer, type OptimizedBuffer, type Renderable, type TextareaRenderable } from "@opentui/core"
2
+ import { completionQuery } from "./prose"
3
+ import type { Prediction, WordPredictor } from "./predictor"
4
+
5
+ export type Composer = {
6
+ editor: TextareaRenderable
7
+ normal: boolean
8
+ focused: unknown
9
+ mode: string
10
+ selected: boolean
11
+ enabled: boolean
12
+ }
13
+
14
+ export function dimGhostColor(muted: RGBA): RGBA {
15
+ return RGBA.fromValues(muted.r, muted.g, muted.b, muted.a * 0.55)
16
+ }
17
+
18
+ export function eligibleComposer(view: Composer): boolean {
19
+ const editor = view.editor
20
+ return view.enabled && view.normal && view.mode === "base" && !view.selected &&
21
+ editor === view.focused && editor.focused && editor.visible && !editor.isDestroyed &&
22
+ !!editor.parent && !editor.parent.isDestroyed && !editor.hasSelection() &&
23
+ !editor.traits.capture?.includes("navigate") &&
24
+ editor.extmarks.getAll().length === 0 && editor.plainText.trim().length > 0
25
+ }
26
+
27
+ export function findComposer(marker: Renderable | undefined, isEditor: (node: Renderable) => node is TextareaRenderable): TextareaRenderable | undefined {
28
+ if (!marker || marker.isDestroyed) return
29
+ const editors = (node: Renderable): TextareaRenderable[] => isEditor(node) ? [node] : node.getChildren().flatMap((child) => editors(child as Renderable))
30
+ for (let node = marker.parent; node?.parent; node = node.parent) {
31
+ if (node.isDestroyed) return
32
+ const found = editors(node)
33
+ if (found.length > 1) return
34
+ if (found.length === 1) {
35
+ const editor = found[0]
36
+ return typeof (editor as unknown as { getClipboardText?: unknown }).getClipboardText === "function" ? editor : undefined
37
+ }
38
+ }
39
+ }
40
+
41
+ export class ComposerGhost {
42
+ private shown: { text: string; offset: number; prediction: Prediction } | undefined
43
+ private dismissed: string | undefined
44
+ private memo: { text: string; offset: number; prediction: Prediction | undefined } | undefined
45
+ private disposed = false
46
+ private readonly draw: (buffer: OptimizedBuffer, delta: number) => void
47
+
48
+ constructor(
49
+ readonly editor: TextareaRenderable,
50
+ private readonly predictor: WordPredictor,
51
+ private readonly view: () => Composer,
52
+ private readonly color: () => RGBA,
53
+ private readonly renderer: CliRenderer,
54
+ ) {
55
+ this.draw = (buffer) => { if (!this.disposed) this.paint(buffer) }
56
+ renderer.addPostProcessFn(this.draw)
57
+ }
58
+
59
+ private offset(): number {
60
+ return this.editor.editBuffer.getTextRange(0, this.editor.cursorOffset).length
61
+ }
62
+
63
+ invalidate(): void {
64
+ this.memo = undefined
65
+ this.shown = undefined
66
+ if (!this.editor.isDestroyed) this.editor.requestRender()
67
+ }
68
+
69
+ private prediction(): Prediction | undefined {
70
+ const text = this.editor.plainText
71
+ const offset = this.offset()
72
+ if (this.dismissed !== undefined && this.dismissed !== text) this.dismissed = undefined
73
+ if (!eligibleComposer(this.view()) || this.dismissed === text) return
74
+ if (this.memo?.text === text && this.memo.offset === offset) return this.memo.prediction
75
+ const query = completionQuery(text, offset)
76
+ let prediction = query && this.predictor.complete(query)
77
+ const last = this.shown
78
+ if (query && !query.next && last && text.startsWith(last.text)) {
79
+ const typed = text.slice(last.text.length)
80
+ if (typed && last.prediction.suffix.startsWith(typed) && typed.length < last.prediction.suffix.length) {
81
+ prediction = { ...last.prediction, suffix: last.prediction.suffix.slice(typed.length) }
82
+ }
83
+ }
84
+ this.memo = { text, offset, prediction }
85
+ return prediction
86
+ }
87
+
88
+ private paint(buffer: OptimizedBuffer): void {
89
+ const prediction = this.prediction()
90
+ if (!prediction || this.editor.isDestroyed) {
91
+ this.shown = undefined
92
+ return
93
+ }
94
+ const cursor = this.editor.visualCursor
95
+ const room = this.editor.width - cursor.visualCol
96
+ if (room <= 0 || cursor.visualRow < 0 || cursor.visualRow >= this.editor.height) {
97
+ this.shown = undefined
98
+ return
99
+ }
100
+ const x = this.editor.screenX + cursor.visualCol
101
+ const y = this.editor.screenY + cursor.visualRow
102
+ buffer.pushScissorRect(x, y, room, 1)
103
+ try {
104
+ buffer.drawText(prediction.suffix, x, y, this.color(), this.editor.backgroundColor)
105
+ } finally {
106
+ buffer.popScissorRect()
107
+ }
108
+ this.shown = { text: this.editor.plainText, offset: this.offset(), prediction }
109
+ }
110
+
111
+ accept(): boolean {
112
+ const shown = this.shown
113
+ if (this.disposed || !shown || !eligibleComposer(this.view()) ||
114
+ this.editor.plainText !== shown.text || this.offset() !== shown.offset) return false
115
+ if (!completionQuery(shown.text, shown.offset)) return false
116
+ this.shown = undefined
117
+ this.editor.insertText(shown.prediction.suffix)
118
+ this.editor.requestRender()
119
+ return true
120
+ }
121
+
122
+ dismiss(): boolean {
123
+ if (this.disposed || !this.shown || !eligibleComposer(this.view()) || this.editor.plainText !== this.shown.text) return false
124
+ this.dismissed = this.editor.plainText
125
+ this.shown = undefined
126
+ this.editor.requestRender()
127
+ return true
128
+ }
129
+
130
+ visible(): boolean {
131
+ return !this.disposed && !!this.shown && eligibleComposer(this.view()) &&
132
+ this.editor.plainText === this.shown.text && this.offset() === this.shown.offset
133
+ }
134
+
135
+ dispose(): void {
136
+ this.disposed = true
137
+ this.shown = undefined
138
+ if (!this.renderer.isDestroyed) this.renderer.removePostProcessFn(this.draw)
139
+ if (this.editor.isDestroyed) return
140
+ this.editor.requestRender()
141
+ }
142
+ }
package/src/keymap.ts ADDED
@@ -0,0 +1,27 @@
1
+ import type { KeymapLayer } from "@opencode/plugin/tui/context"
2
+ import type { Options } from "./options"
3
+
4
+ type Suggestion = { visible(): boolean; accept(): boolean; dismiss(): boolean }
5
+
6
+ export function completionLayer(options: Options, suggestion: () => Suggestion | undefined): KeymapLayer {
7
+ return {
8
+ mode: "base",
9
+ priority: 2,
10
+ commands: [
11
+ {
12
+ id: "quill.accept",
13
+ title: "Accept word suggestion",
14
+ bind: options.acceptKeys.length ? options.acceptKeys.join(",") : false,
15
+ enabled: () => suggestion()?.visible() === true,
16
+ run: () => suggestion()?.accept() ? undefined : false,
17
+ },
18
+ {
19
+ id: "quill.dismiss",
20
+ title: "Dismiss word suggestion",
21
+ bind: options.dismissKeys.length ? options.dismissKeys.join(",") : false,
22
+ enabled: () => suggestion()?.visible() === true,
23
+ run: () => suggestion()?.dismiss() ? undefined : false,
24
+ },
25
+ ],
26
+ }
27
+ }
package/src/options.ts ADDED
@@ -0,0 +1,34 @@
1
+ export type Options = { enabled: boolean; acceptKeys: string[]; dismissKeys: string[] }
2
+
3
+ function keys(value: unknown, fallback: string[], name: string): string[] {
4
+ if (value === undefined) return fallback
5
+ if (!Array.isArray(value) || value.some((key) => typeof key !== "string" || !key.trim())) {
6
+ throw new Error(`Quill ${name} must be an array of non-empty keybindings`)
7
+ }
8
+ return [...new Set(value.map((key: string) => key.trim()))]
9
+ }
10
+
11
+ export function resolveOptions(input: Readonly<Record<string, unknown>>): Options {
12
+ if (input.enabled !== undefined && typeof input.enabled !== "boolean") throw new Error("Quill enabled must be a boolean")
13
+ return {
14
+ enabled: input.enabled !== false,
15
+ acceptKeys: keys(input.acceptKeys, ["tab", "right"], "acceptKeys"),
16
+ dismissKeys: keys(input.dismissKeys, ["escape"], "dismissKeys"),
17
+ }
18
+ }
19
+
20
+ export type QuillCommand =
21
+ | { type: "toggle" }
22
+ | { type: "enable"; value: boolean }
23
+ | { type: "clear" }
24
+ | { type: "invalid" }
25
+
26
+ export function parseQuillCommand(input: string | undefined): QuillCommand {
27
+ const raw = input?.trim().toLowerCase() ?? ""
28
+ if (!raw || raw === "toggle") return { type: "toggle" }
29
+ if (raw === "clear" || raw === "reset") return { type: "clear" }
30
+ if (raw === "on") return { type: "enable", value: true }
31
+ if (raw === "off") return { type: "enable", value: false }
32
+ return { type: "invalid" }
33
+ }
34
+
@@ -0,0 +1,182 @@
1
+ import { isWord, leftContext, normalizeWord, proseSequences, proseWords, type CompletionQuery } from "./prose"
2
+
3
+ export type Frequency = { word: string; count: number }
4
+ export type Snapshot = {
5
+ version: 1
6
+ words: [string, number][]
7
+ bigrams: [string, number][]
8
+ trigrams: [string, number][]
9
+ seen: string[]
10
+ }
11
+ export type Prompt = { id: string; text: string }
12
+ export type Prediction = { suffix: string; word: string; confidence: number }
13
+
14
+ const DISCOUNT = 0.5
15
+ const PRIOR_LIMIT = 20_000
16
+ const WORD_LIMIT = 8000
17
+ const CONTEXT_LIMIT = 30_000
18
+ const SEEN_LIMIT = 8000
19
+
20
+ export function emptySnapshot(): Snapshot {
21
+ return { version: 1, words: [], bigrams: [], trigrams: [], seen: [] }
22
+ }
23
+
24
+ function restore(rows: [string, number][], limit: number): Map<string, number> {
25
+ return new Map(rows.slice(0, limit).filter(([word, count]) => typeof word === "string" && word.length <= 100 && Number.isFinite(count) && count > 0))
26
+ }
27
+
28
+ function trim(map: Map<string, number>, limit: number): [string, number][] {
29
+ return [...map].sort((a, b) => b[1] - a[1]).slice(0, limit)
30
+ }
31
+
32
+ function increment(map: Map<string, number>, word: string): void {
33
+ map.set(word, (map.get(word) ?? 0) + 1)
34
+ }
35
+
36
+ export class PersonalModel {
37
+ readonly words: Map<string, number>
38
+ readonly bigrams: Map<string, number>
39
+ readonly trigrams: Map<string, number>
40
+ readonly seen: Set<string>
41
+
42
+ constructor(snapshot: Snapshot = emptySnapshot()) {
43
+ this.words = restore(snapshot.words, WORD_LIMIT)
44
+ this.bigrams = restore(snapshot.bigrams, CONTEXT_LIMIT)
45
+ this.trigrams = restore(snapshot.trigrams, CONTEXT_LIMIT)
46
+ this.seen = new Set(snapshot.seen.slice(-SEEN_LIMIT))
47
+ }
48
+
49
+ observe(prompts: readonly Prompt[]): boolean {
50
+ let changed = false
51
+ for (const prompt of prompts) {
52
+ if (this.seen.has(prompt.id)) continue
53
+ this.seen.add(prompt.id)
54
+ changed = true
55
+ if (prompt.text.length > 4000 || prompt.text.split("\n").length > 12) continue
56
+ for (const sequence of proseSequences(prompt.text)) {
57
+ for (let index = 0; index < sequence.length; index++) {
58
+ increment(this.words, sequence[index])
59
+ if (index > 0) increment(this.bigrams, `${sequence[index - 1]}\0${sequence[index]}`)
60
+ if (index > 1) increment(this.trigrams, `${sequence[index - 2]}\0${sequence[index - 1]}\0${sequence[index]}`)
61
+ }
62
+ }
63
+ }
64
+ return changed
65
+ }
66
+
67
+ snapshot(): Snapshot {
68
+ return {
69
+ version: 1,
70
+ words: trim(this.words, WORD_LIMIT),
71
+ bigrams: trim(this.bigrams, CONTEXT_LIMIT),
72
+ trigrams: trim(this.trigrams, CONTEXT_LIMIT),
73
+ seen: [...this.seen].slice(-SEEN_LIMIT),
74
+ }
75
+ }
76
+ }
77
+
78
+ function totals(counts: Map<string, number>): Map<string, { total: number; types: number }> {
79
+ const result = new Map<string, { total: number; types: number }>()
80
+ for (const [key, count] of counts) {
81
+ const context = key.slice(0, key.lastIndexOf("\0"))
82
+ const entry = result.get(context) ?? { total: 0, types: 0 }
83
+ entry.total += count
84
+ entry.types++
85
+ result.set(context, entry)
86
+ }
87
+ return result
88
+ }
89
+
90
+ function lowerBound(words: readonly string[], prefix: string): number {
91
+ let low = 0
92
+ let high = words.length
93
+ while (low < high) {
94
+ const middle = (low + high) >>> 1
95
+ if (words[middle] < prefix) low = middle + 1
96
+ else high = middle
97
+ }
98
+ return low
99
+ }
100
+
101
+ export class WordPredictor {
102
+ readonly prior = new Map<string, number>()
103
+ private priorTotal = 0
104
+ private personal = new PersonalModel()
105
+ private personalTotal = 0
106
+ private bigramTotals = new Map<string, { total: number; types: number }>()
107
+ private trigramTotals = new Map<string, { total: number; types: number }>()
108
+ private vocabulary: string[] = []
109
+
110
+ constructor(prior: readonly Frequency[]) {
111
+ for (const { word, count } of prior) {
112
+ const key = normalizeWord(word)
113
+ if (!isWord(key) || !Number.isFinite(count) || count <= 0) continue
114
+ this.prior.set(key, (this.prior.get(key) ?? 0) + count)
115
+ this.priorTotal += count
116
+ if (this.prior.size >= PRIOR_LIMIT) break
117
+ }
118
+ this.setPersonal(emptySnapshot())
119
+ }
120
+
121
+ setPersonal(snapshot: Snapshot): void {
122
+ this.personal = new PersonalModel(snapshot)
123
+ this.personalTotal = [...this.personal.words.values()].reduce((sum, count) => sum + count, 0)
124
+ this.bigramTotals = totals(this.personal.bigrams)
125
+ this.trigramTotals = totals(this.personal.trigrams)
126
+ this.vocabulary = [...new Set([...this.prior.keys(), ...[...this.personal.words].filter(([, count]) => count >= 2).map(([word]) => word)])].sort()
127
+ }
128
+
129
+ private score(word: string, context: readonly string[]): number {
130
+ const prior = (this.prior.get(word) ?? 0) / (this.priorTotal || 1)
131
+ const personal = (this.personal.words.get(word) ?? 0) / (this.personalTotal || 1)
132
+ const weight = this.personalTotal / (this.personalTotal + 100)
133
+ let score = weight * personal + (1 - weight) * prior
134
+ const previous = context.at(-1)
135
+ const bigram = previous && this.bigramTotals.get(previous)
136
+ if (bigram) {
137
+ const count = this.personal.bigrams.get(`${previous}\0${word}`) ?? 0
138
+ score = Math.max(count - DISCOUNT, 0) / bigram.total + DISCOUNT * bigram.types / bigram.total * score
139
+ }
140
+ const pair = context.length === 2 ? context.join("\0") : undefined
141
+ const trigram = pair && this.trigramTotals.get(pair)
142
+ if (trigram) {
143
+ const count = this.personal.trigrams.get(`${pair}\0${word}`) ?? 0
144
+ score = Math.max(count - DISCOUNT, 0) / trigram.total + DISCOUNT * trigram.types / trigram.total * score
145
+ }
146
+ return score
147
+ }
148
+
149
+ complete(query: CompletionQuery): Prediction | undefined {
150
+ const prefix = normalizeWord(query.prefix)
151
+ const context = leftContext(query.before)
152
+ const evidence = this.bigramTotals.get(context.at(-1) ?? "")?.total ?? 0
153
+ if (query.next && evidence < 2) return
154
+ if (!query.next && [...prefix].length < 2 && evidence < 2) return
155
+ const local = new Map<string, number>()
156
+ for (const word of proseWords(query.before)) increment(local, word.text)
157
+ const candidates = new Set<string>()
158
+ for (let index = lowerBound(this.vocabulary, prefix); index < this.vocabulary.length; index++) {
159
+ const word = this.vocabulary[index]
160
+ if (!word.startsWith(prefix)) break
161
+ candidates.add(word)
162
+ }
163
+ for (const word of local.keys()) if (word.startsWith(prefix)) candidates.add(word)
164
+ let best = ""
165
+ let bestScore = 0
166
+ let sum = 0
167
+ for (const word of candidates) {
168
+ const score = this.score(word, context) + (query.next ? 0 : 0.003 * Math.min(local.get(word) ?? 0, 3))
169
+ sum += score
170
+ if (score > bestScore) {
171
+ best = word
172
+ bestScore = score
173
+ }
174
+ }
175
+ const confidence = query.next ? bestScore : bestScore / (sum || 1)
176
+ if (!best || best === prefix || confidence < (query.next ? 0.55 : 0.3)) return
177
+ let suffix = best.slice(prefix.length)
178
+ if (query.prefix.length > 1 && query.prefix === query.prefix.toUpperCase()) suffix = suffix.toUpperCase()
179
+ if (query.next && best === "i") suffix = "I"
180
+ return { suffix, word: best, confidence }
181
+ }
182
+ }
package/src/prose.ts ADDED
@@ -0,0 +1,80 @@
1
+ const WORD = /[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*/gu
2
+ const WHOLE_WORD = /^[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*$/u
3
+ const WORD_END = /[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*$/u
4
+
5
+ export type Word = { text: string; start: number; end: number }
6
+ export type CompletionQuery = { before: string; prefix: string; next: boolean }
7
+
8
+ export function normalizeWord(word: string): string {
9
+ return word.normalize("NFC").replaceAll("’", "'").toLowerCase()
10
+ }
11
+
12
+ export function isWord(word: string): boolean {
13
+ return WHOLE_WORD.test(word) && [...word].length <= 32
14
+ }
15
+
16
+ function blank(text: string): string {
17
+ return text.replace(/[^\n]/g, " ")
18
+ }
19
+
20
+ export function maskProse(text: string): string {
21
+ let masked = text.replace(/(^|\n)[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?(?:\n[ \t]*\2[^\n]*(?=\n|$)|$)/g, blank)
22
+ masked = masked.replace(/(`+)[\s\S]*?(?:\1|$)/g, blank)
23
+ masked = masked.replace(/(?:https?:\/\/|www\.)\S+|\[[^\]\n]*\]\([^\)\n]*\)|<[^>\n]+>/g, blank)
24
+ masked = masked.replace(/^[ \t]*(?:[\/!$]|(?:const|let|var|function|class|import|export)\s|(?:Traceback|Error:)\b).*$/gm, blank)
25
+ masked = masked.replace(/^ {4,}.*$/gm, blank)
26
+ masked = masked.replace(/\S+/g, (token) => {
27
+ const core = token.replace(/^["“‘([{]+|["”’),;:!?}\]]+$/g, "")
28
+ if (/[\/_@=\\<>-]|\d|[\p{Ll}][\p{Lu}]/u.test(core) || /^[.~]/.test(core)) return blank(token)
29
+ if (/[^.]+\.[^.]+|\.\.|--/.test(core)) return blank(token)
30
+ return token
31
+ })
32
+ return masked
33
+ }
34
+
35
+ export function proseWords(text: string): Word[] {
36
+ const masked = maskProse(text)
37
+ return [...masked.matchAll(WORD)]
38
+ .filter((match) => isWord(match[0]))
39
+ .map((match) => ({ text: normalizeWord(match[0]), start: match.index, end: match.index + match[0].length }))
40
+ }
41
+
42
+ export function proseSequences(text: string): string[][] {
43
+ const words = proseWords(text)
44
+ const sequences: string[][] = []
45
+ let previous = -1
46
+ for (const word of words) {
47
+ if (previous < 0 || !/^[ \t]+$/.test(text.slice(previous, word.start))) sequences.push([])
48
+ sequences.at(-1)!.push(word.text)
49
+ previous = word.end
50
+ }
51
+ return sequences
52
+ }
53
+
54
+ export function leftContext(before: string): string[] {
55
+ const words = proseWords(before)
56
+ const result: string[] = []
57
+ let end = before.length
58
+ for (let index = words.length - 1; index >= 0 && result.length < 2; index--) {
59
+ const word = words[index]
60
+ if (!/^[ \t]*$/.test(before.slice(word.end, end))) break
61
+ result.unshift(word.text)
62
+ end = word.start
63
+ }
64
+ return result
65
+ }
66
+
67
+ export function completionQuery(text: string, characterOffset: number): CompletionQuery | undefined {
68
+ if (!text.trim() || characterOffset !== text.length || text.length > 16_000) return
69
+ const masked = maskProse(text)
70
+ const prefix = WORD_END.exec(text)?.[0]
71
+ if (prefix) {
72
+ const start = text.length - prefix.length
73
+ if (masked.slice(start) !== prefix || !isWord(prefix)) return
74
+ const preceding = text[start - 1]
75
+ if (preceding && !/[ \t\n"“([{]/.test(preceding)) return
76
+ return { before: text.slice(0, start).slice(-2000), prefix, next: false }
77
+ }
78
+ if (!/[ \t]$/.test(text) || !leftContext(text).length) return
79
+ return { before: text.slice(-2000), prefix: "", next: true }
80
+ }
package/src/tui.tsx ADDED
@@ -0,0 +1,194 @@
1
+ import { Plugin } from "@opencode/plugin/tui"
2
+ import { InputRenderable, TextareaRenderable, type BoxRenderable } from "@opentui/core"
3
+ import { createEffect, createRoot, createSignal, onCleanup, untrack } from "solid-js"
4
+ import frequencies from "subtlex-word-frequencies"
5
+ import { ComposerGhost, dimGhostColor, findComposer } from "./ghost"
6
+ import { completionLayer } from "./keymap"
7
+ import { parseQuillCommand, resolveOptions } from "./options"
8
+ import { emptySnapshot, PersonalModel, WordPredictor } from "./predictor"
9
+
10
+ export default Plugin.define({
11
+ id: "quill",
12
+ setup(context) {
13
+ const options = resolveOptions(context.options)
14
+ const [settings, setSettings] = context.storage.store("settings", {
15
+ initial: { enabled: options.enabled },
16
+ })
17
+ const [learning, setLearning] = context.storage.store("learning", {
18
+ initial: { snapshot: emptySnapshot() },
19
+ })
20
+ const predictor = new WordPredictor(frequencies)
21
+ const composers = new Map<string, { marker: BoxRenderable; normal: () => boolean }>()
22
+ const seeded = new Set<string>()
23
+ const inFlight = new Set<string>()
24
+ const [revision, setRevision] = createSignal(0)
25
+ let ghost: ComposerGhost | undefined
26
+ let disposed = false
27
+ let warned = false
28
+
29
+ const routeKey = () => {
30
+ const route = context.ui.router.current()
31
+ return route.type === "home" ? "home" : route.type === "session" ? route.sessionID : undefined
32
+ }
33
+
34
+ const currentEditor = () => {
35
+ const key = routeKey()
36
+ const composer = key && composers.get(key)
37
+ return composer ? findComposer(composer.marker, (node): node is TextareaRenderable => node instanceof TextareaRenderable && !(node instanceof InputRenderable)) : undefined
38
+ }
39
+
40
+ const syncEditor = () => {
41
+ if (disposed) return
42
+ const editor = currentEditor()
43
+ if (ghost?.editor === editor) return
44
+ ghost?.dispose()
45
+ ghost = editor && new ComposerGhost(editor, predictor, () => {
46
+ const key = routeKey()
47
+ return {
48
+ editor,
49
+ normal: !!key && composers.get(key)?.normal() === true,
50
+ focused: context.renderer.currentFocusedEditor,
51
+ mode: context.keymap.mode.current(),
52
+ selected: context.renderer.hasSelection,
53
+ enabled: !disposed && settings.enabled && currentEditor() === editor,
54
+ }
55
+ }, () => dimGhostColor(context.theme.text.muted), context.renderer)
56
+ }
57
+
58
+ const learn = async (sessionID: string) => {
59
+ if (disposed || !settings.enabled || inFlight.has(sessionID)) return
60
+ inFlight.add(sessionID)
61
+ try {
62
+ await context.data.session.message.sync(sessionID)
63
+ if (disposed || !settings.enabled) return
64
+ const prompts = context.data.session.message.list(sessionID)
65
+ .filter((message) => message.type === "user")
66
+ .slice(-200)
67
+ .map((message) => ({ id: `${sessionID}:${message.id}`, text: message.text }))
68
+ const model = new PersonalModel(learning.snapshot)
69
+ if (!model.observe(prompts)) return
70
+ await setLearning((draft) => {
71
+ const latest = new PersonalModel(draft.snapshot)
72
+ if (latest.observe(prompts)) draft.snapshot = latest.snapshot()
73
+ })
74
+ } catch {
75
+ if (!disposed && !warned) {
76
+ warned = true
77
+ context.ui.toast.show({ title: "Quill", message: "History learning unavailable; vocabulary completion is still active.", variant: "warning" })
78
+ }
79
+ } finally {
80
+ inFlight.delete(sessionID)
81
+ }
82
+ }
83
+
84
+ const disposeEffects = createRoot((dispose) => {
85
+ createEffect(() => {
86
+ predictor.setPersonal(learning.snapshot)
87
+ ghost?.invalidate()
88
+ })
89
+ createEffect(() => {
90
+ revision()
91
+ routeKey()
92
+ settings.enabled
93
+ context.keymap.mode.current()
94
+ syncEditor()
95
+ ghost?.invalidate()
96
+ })
97
+ createEffect(() => {
98
+ if (!settings.enabled) return
99
+ const route = context.ui.router.current()
100
+ if (route.type === "session") untrack(() => { void learn(route.sessionID) })
101
+ for (const session of context.data.session.list().filter((session) => !session.parentID).sort((a, b) => b.time.updated - a.time.updated).slice(0, 8)) {
102
+ if (seeded.has(session.id)) continue
103
+ seeded.add(session.id)
104
+ untrack(() => { void learn(session.id) })
105
+ }
106
+ })
107
+ return dispose
108
+ })
109
+
110
+ const beforeRender = async () => { syncEditor() }
111
+ context.renderer.setFrameCallback(beforeRender)
112
+ const offStarted = context.data.on("session.execution.started", (event) => { void learn(event.data.sessionID) })
113
+ const offSucceeded = context.data.on("session.execution.succeeded", (event) => { void learn(event.data.sessionID) })
114
+ const offDelivered = context.data.on("session.inbox.delivered", (event) => { void learn(event.data.sessionID) })
115
+
116
+ context.keymap.layer(() => completionLayer(options, () => ghost))
117
+ context.keymap.layer(() => ({
118
+ mode: "global",
119
+ commands: [
120
+ {
121
+ id: "quill.toggle",
122
+ title: `Word autocomplete: ${settings.enabled ? "on" : "off"}`,
123
+ description: "Toggle local word suggestions",
124
+ group: "Prompt",
125
+ palette: true,
126
+ slash: { name: "quill", arguments: true },
127
+ run: async (input) => {
128
+ const command = parseQuillCommand(input)
129
+ if (command.type === "clear") {
130
+ predictor.setPersonal(emptySnapshot())
131
+ await setLearning((draft) => { draft.snapshot = emptySnapshot() })
132
+ ghost?.invalidate()
133
+ context.ui.toast.show({ title: "Quill", message: "Word autocomplete history cleared" })
134
+ return
135
+ }
136
+ if (command.type === "invalid") {
137
+ context.ui.toast.show({ title: "Quill", message: "Use /quill, /quill on, /quill off, or /quill clear", variant: "warning" })
138
+ return
139
+ }
140
+ const enabled = command.type === "enable" ? command.value : !settings.enabled
141
+ await setSettings((draft) => { draft.enabled = enabled })
142
+ ghost?.invalidate()
143
+ context.ui.toast.show({ title: "Quill", message: `Word autocomplete: ${enabled ? "on" : "off"}` })
144
+ },
145
+ },
146
+ {
147
+ id: "quill.clear",
148
+ title: "Clear word autocomplete history",
149
+ description: "Reset learned vocabulary, n-grams, and prompt transitions",
150
+ group: "Prompt",
151
+ palette: true,
152
+ run: async () => {
153
+ predictor.setPersonal(emptySnapshot())
154
+ await setLearning((draft) => { draft.snapshot = emptySnapshot() })
155
+ ghost?.invalidate()
156
+ context.ui.toast.show({ title: "Quill", message: "Word autocomplete history cleared" })
157
+ },
158
+ },
159
+ ],
160
+ }))
161
+
162
+ const offComposer = context.ui.slot({
163
+ append: "prompt.footer",
164
+ render(input) {
165
+ const [marker, setMarker] = createSignal<BoxRenderable>()
166
+ createEffect(() => {
167
+ const key = input.sessionID ?? "home"
168
+ const node = marker()
169
+ if (!node) return
170
+ composers.set(key, { marker: node, normal: () => input.mode === "normal" })
171
+ setRevision((value) => value + 1)
172
+ onCleanup(() => {
173
+ if (composers.get(key)?.marker !== node) return
174
+ composers.delete(key)
175
+ setRevision((value) => value + 1)
176
+ })
177
+ })
178
+ return <box width={0} height={0} ref={setMarker} />
179
+ },
180
+ })
181
+
182
+ return () => {
183
+ disposed = true
184
+ context.renderer.removeFrameCallback(beforeRender)
185
+ disposeEffects()
186
+ offStarted()
187
+ offSucceeded()
188
+ offDelivered()
189
+ offComposer()
190
+ ghost?.dispose()
191
+ composers.clear()
192
+ }
193
+ },
194
+ })
package/tsconfig.json ADDED
@@ -0,0 +1,18 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "lib": ["ESNext", "DOM"],
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "jsx": "preserve",
8
+ "jsxImportSource": "@opentui/solid",
9
+ "verbatimModuleSyntax": true,
10
+ "types": ["node"],
11
+ "strict": true,
12
+ "noEmit": true,
13
+ "skipLibCheck": true,
14
+ "forceConsistentCasingInFileNames": true
15
+ },
16
+ "include": ["src", "test"],
17
+ "exclude": ["node_modules"]
18
+ }