opencode-quill 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/README.md +220 -2
- package/package.json +84 -4
- package/src/frequencies.d.ts +4 -0
- package/src/ghost.ts +142 -0
- package/src/keymap.ts +27 -0
- package/src/options.ts +34 -0
- package/src/predictor.ts +182 -0
- package/src/prose.ts +80 -0
- package/src/tui.tsx +195 -0
- package/tsconfig.json +18 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
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.1] - 2026-10-10
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- **ci:** Handle root commit in commitlint range
|
|
12
|
+
- Add `@jsxImportSource @opentui/solid` pragma to the TUI entrypoint so npm cache compilation doesn't fall back to React.
|
|
13
|
+
- Constrain `@opentui/core` and `@opentui/solid` peer dependencies to `<0.6.0` with `peerDependenciesMeta` set to optional, preventing conflicting nested OpenTUI versions.
|
|
14
|
+
- Support `/quill clear` and `/quill reset` to wipe learned vocabulary and n-gram state.
|
|
15
|
+
|
|
16
|
+
## [0.1.0] - 2026-10-10
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
|
|
20
|
+
- Local word autocomplete and next-word prediction plugin for OpenCode V2.
|
|
21
|
+
- High-frequency English vocabulary prior derived from SUBTLEX word frequencies.
|
|
22
|
+
- Online absolute-discounting n-gram model learning from submitted session prompts.
|
|
23
|
+
- Inline ghost-text rendering at visual cursor with matching Ghost dim level (`0.55`).
|
|
24
|
+
- Safe acceptance (<kbd>Tab</kbd>, <kbd>→</kbd>) and dismissal (<kbd>Esc</kbd>) without draft submission.
|
|
25
|
+
- Prose-aware filtering suppressing suggestions in code, paths, URLs, and shell commands.
|
|
26
|
+
- `/quill` command and command palette action to toggle autocomplete.
|
|
27
|
+
- Local installer script, full test suite, CI workflows, and release tooling.
|
|
28
|
+
|
|
29
|
+
[0.1.1]: https://github.com/ozandogrultan/opencode-quill/compare/v0.1.0...v0.1.1
|
|
30
|
+
[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
|
-
#
|
|
1
|
+
# opencode-quill
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](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,86 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-quill",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
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 <0.6.0",
|
|
57
|
+
"@opentui/solid": ">=0.5.17 <0.6.0",
|
|
58
|
+
"solid-js": "*"
|
|
59
|
+
},
|
|
60
|
+
"peerDependenciesMeta": {
|
|
61
|
+
"@opencode/plugin": {
|
|
62
|
+
"optional": true
|
|
63
|
+
},
|
|
64
|
+
"@opentui/core": {
|
|
65
|
+
"optional": true
|
|
66
|
+
},
|
|
67
|
+
"@opentui/solid": {
|
|
68
|
+
"optional": true
|
|
69
|
+
},
|
|
70
|
+
"solid-js": {
|
|
71
|
+
"optional": true
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
"devDependencies": {
|
|
75
|
+
"@commitlint/cli": "^21.2.2",
|
|
76
|
+
"@commitlint/config-conventional": "^21.2.2",
|
|
77
|
+
"@opencode/plugin": "2.0.26",
|
|
78
|
+
"@opentui/core": "^0.5.17",
|
|
79
|
+
"@opentui/solid": "^0.5.17",
|
|
80
|
+
"@types/bun": "^1.4.2",
|
|
81
|
+
"@types/node": "26.6.4",
|
|
82
|
+
"husky": "^9.1.7",
|
|
83
|
+
"solid-js": "1.9.12",
|
|
84
|
+
"typescript": "7.0.2"
|
|
85
|
+
}
|
|
86
|
+
}
|
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
|
+
|
package/src/predictor.ts
ADDED
|
@@ -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,195 @@
|
|
|
1
|
+
/** @jsxImportSource @opentui/solid */
|
|
2
|
+
import { Plugin } from "@opencode/plugin/tui"
|
|
3
|
+
import { InputRenderable, TextareaRenderable, type BoxRenderable } from "@opentui/core"
|
|
4
|
+
import { createEffect, createRoot, createSignal, onCleanup, untrack } from "solid-js"
|
|
5
|
+
import frequencies from "subtlex-word-frequencies"
|
|
6
|
+
import { ComposerGhost, dimGhostColor, findComposer } from "./ghost"
|
|
7
|
+
import { completionLayer } from "./keymap"
|
|
8
|
+
import { parseQuillCommand, resolveOptions } from "./options"
|
|
9
|
+
import { emptySnapshot, PersonalModel, WordPredictor } from "./predictor"
|
|
10
|
+
|
|
11
|
+
export default Plugin.define({
|
|
12
|
+
id: "quill",
|
|
13
|
+
setup(context) {
|
|
14
|
+
const options = resolveOptions(context.options)
|
|
15
|
+
const [settings, setSettings] = context.storage.store("settings", {
|
|
16
|
+
initial: { enabled: options.enabled },
|
|
17
|
+
})
|
|
18
|
+
const [learning, setLearning] = context.storage.store("learning", {
|
|
19
|
+
initial: { snapshot: emptySnapshot() },
|
|
20
|
+
})
|
|
21
|
+
const predictor = new WordPredictor(frequencies)
|
|
22
|
+
const composers = new Map<string, { marker: BoxRenderable; normal: () => boolean }>()
|
|
23
|
+
const seeded = new Set<string>()
|
|
24
|
+
const inFlight = new Set<string>()
|
|
25
|
+
const [revision, setRevision] = createSignal(0)
|
|
26
|
+
let ghost: ComposerGhost | undefined
|
|
27
|
+
let disposed = false
|
|
28
|
+
let warned = false
|
|
29
|
+
|
|
30
|
+
const routeKey = () => {
|
|
31
|
+
const route = context.ui.router.current()
|
|
32
|
+
return route.type === "home" ? "home" : route.type === "session" ? route.sessionID : undefined
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const currentEditor = () => {
|
|
36
|
+
const key = routeKey()
|
|
37
|
+
const composer = key && composers.get(key)
|
|
38
|
+
return composer ? findComposer(composer.marker, (node): node is TextareaRenderable => node instanceof TextareaRenderable && !(node instanceof InputRenderable)) : undefined
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const syncEditor = () => {
|
|
42
|
+
if (disposed) return
|
|
43
|
+
const editor = currentEditor()
|
|
44
|
+
if (ghost?.editor === editor) return
|
|
45
|
+
ghost?.dispose()
|
|
46
|
+
ghost = editor && new ComposerGhost(editor, predictor, () => {
|
|
47
|
+
const key = routeKey()
|
|
48
|
+
return {
|
|
49
|
+
editor,
|
|
50
|
+
normal: !!key && composers.get(key)?.normal() === true,
|
|
51
|
+
focused: context.renderer.currentFocusedEditor,
|
|
52
|
+
mode: context.keymap.mode.current(),
|
|
53
|
+
selected: context.renderer.hasSelection,
|
|
54
|
+
enabled: !disposed && settings.enabled && currentEditor() === editor,
|
|
55
|
+
}
|
|
56
|
+
}, () => dimGhostColor(context.theme.text.muted), context.renderer)
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const learn = async (sessionID: string) => {
|
|
60
|
+
if (disposed || !settings.enabled || inFlight.has(sessionID)) return
|
|
61
|
+
inFlight.add(sessionID)
|
|
62
|
+
try {
|
|
63
|
+
await context.data.session.message.sync(sessionID)
|
|
64
|
+
if (disposed || !settings.enabled) return
|
|
65
|
+
const prompts = context.data.session.message.list(sessionID)
|
|
66
|
+
.filter((message) => message.type === "user")
|
|
67
|
+
.slice(-200)
|
|
68
|
+
.map((message) => ({ id: `${sessionID}:${message.id}`, text: message.text }))
|
|
69
|
+
const model = new PersonalModel(learning.snapshot)
|
|
70
|
+
if (!model.observe(prompts)) return
|
|
71
|
+
await setLearning((draft) => {
|
|
72
|
+
const latest = new PersonalModel(draft.snapshot)
|
|
73
|
+
if (latest.observe(prompts)) draft.snapshot = latest.snapshot()
|
|
74
|
+
})
|
|
75
|
+
} catch {
|
|
76
|
+
if (!disposed && !warned) {
|
|
77
|
+
warned = true
|
|
78
|
+
context.ui.toast.show({ title: "Quill", message: "History learning unavailable; vocabulary completion is still active.", variant: "warning" })
|
|
79
|
+
}
|
|
80
|
+
} finally {
|
|
81
|
+
inFlight.delete(sessionID)
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const disposeEffects = createRoot((dispose) => {
|
|
86
|
+
createEffect(() => {
|
|
87
|
+
predictor.setPersonal(learning.snapshot)
|
|
88
|
+
ghost?.invalidate()
|
|
89
|
+
})
|
|
90
|
+
createEffect(() => {
|
|
91
|
+
revision()
|
|
92
|
+
routeKey()
|
|
93
|
+
settings.enabled
|
|
94
|
+
context.keymap.mode.current()
|
|
95
|
+
syncEditor()
|
|
96
|
+
ghost?.invalidate()
|
|
97
|
+
})
|
|
98
|
+
createEffect(() => {
|
|
99
|
+
if (!settings.enabled) return
|
|
100
|
+
const route = context.ui.router.current()
|
|
101
|
+
if (route.type === "session") untrack(() => { void learn(route.sessionID) })
|
|
102
|
+
for (const session of context.data.session.list().filter((session) => !session.parentID).sort((a, b) => b.time.updated - a.time.updated).slice(0, 8)) {
|
|
103
|
+
if (seeded.has(session.id)) continue
|
|
104
|
+
seeded.add(session.id)
|
|
105
|
+
untrack(() => { void learn(session.id) })
|
|
106
|
+
}
|
|
107
|
+
})
|
|
108
|
+
return dispose
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
const beforeRender = async () => { syncEditor() }
|
|
112
|
+
context.renderer.setFrameCallback(beforeRender)
|
|
113
|
+
const offStarted = context.data.on("session.execution.started", (event) => { void learn(event.data.sessionID) })
|
|
114
|
+
const offSucceeded = context.data.on("session.execution.succeeded", (event) => { void learn(event.data.sessionID) })
|
|
115
|
+
const offDelivered = context.data.on("session.inbox.delivered", (event) => { void learn(event.data.sessionID) })
|
|
116
|
+
|
|
117
|
+
context.keymap.layer(() => completionLayer(options, () => ghost))
|
|
118
|
+
context.keymap.layer(() => ({
|
|
119
|
+
mode: "global",
|
|
120
|
+
commands: [
|
|
121
|
+
{
|
|
122
|
+
id: "quill.toggle",
|
|
123
|
+
title: `Word autocomplete: ${settings.enabled ? "on" : "off"}`,
|
|
124
|
+
description: "Toggle local word suggestions",
|
|
125
|
+
group: "Prompt",
|
|
126
|
+
palette: true,
|
|
127
|
+
slash: { name: "quill", arguments: true },
|
|
128
|
+
run: async (input) => {
|
|
129
|
+
const command = parseQuillCommand(input)
|
|
130
|
+
if (command.type === "clear") {
|
|
131
|
+
predictor.setPersonal(emptySnapshot())
|
|
132
|
+
await setLearning((draft) => { draft.snapshot = emptySnapshot() })
|
|
133
|
+
ghost?.invalidate()
|
|
134
|
+
context.ui.toast.show({ title: "Quill", message: "Word autocomplete history cleared" })
|
|
135
|
+
return
|
|
136
|
+
}
|
|
137
|
+
if (command.type === "invalid") {
|
|
138
|
+
context.ui.toast.show({ title: "Quill", message: "Use /quill, /quill on, /quill off, or /quill clear", variant: "warning" })
|
|
139
|
+
return
|
|
140
|
+
}
|
|
141
|
+
const enabled = command.type === "enable" ? command.value : !settings.enabled
|
|
142
|
+
await setSettings((draft) => { draft.enabled = enabled })
|
|
143
|
+
ghost?.invalidate()
|
|
144
|
+
context.ui.toast.show({ title: "Quill", message: `Word autocomplete: ${enabled ? "on" : "off"}` })
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
id: "quill.clear",
|
|
149
|
+
title: "Clear word autocomplete history",
|
|
150
|
+
description: "Reset learned vocabulary, n-grams, and prompt transitions",
|
|
151
|
+
group: "Prompt",
|
|
152
|
+
palette: true,
|
|
153
|
+
run: async () => {
|
|
154
|
+
predictor.setPersonal(emptySnapshot())
|
|
155
|
+
await setLearning((draft) => { draft.snapshot = emptySnapshot() })
|
|
156
|
+
ghost?.invalidate()
|
|
157
|
+
context.ui.toast.show({ title: "Quill", message: "Word autocomplete history cleared" })
|
|
158
|
+
},
|
|
159
|
+
},
|
|
160
|
+
],
|
|
161
|
+
}))
|
|
162
|
+
|
|
163
|
+
const offComposer = context.ui.slot({
|
|
164
|
+
append: "prompt.footer",
|
|
165
|
+
render(input) {
|
|
166
|
+
const [marker, setMarker] = createSignal<BoxRenderable>()
|
|
167
|
+
createEffect(() => {
|
|
168
|
+
const key = input.sessionID ?? "home"
|
|
169
|
+
const node = marker()
|
|
170
|
+
if (!node) return
|
|
171
|
+
composers.set(key, { marker: node, normal: () => input.mode === "normal" })
|
|
172
|
+
setRevision((value) => value + 1)
|
|
173
|
+
onCleanup(() => {
|
|
174
|
+
if (composers.get(key)?.marker !== node) return
|
|
175
|
+
composers.delete(key)
|
|
176
|
+
setRevision((value) => value + 1)
|
|
177
|
+
})
|
|
178
|
+
})
|
|
179
|
+
return <box width={0} height={0} ref={setMarker} />
|
|
180
|
+
},
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
return () => {
|
|
184
|
+
disposed = true
|
|
185
|
+
context.renderer.removeFrameCallback(beforeRender)
|
|
186
|
+
disposeEffects()
|
|
187
|
+
offStarted()
|
|
188
|
+
offSucceeded()
|
|
189
|
+
offDelivered()
|
|
190
|
+
offComposer()
|
|
191
|
+
ghost?.dispose()
|
|
192
|
+
composers.clear()
|
|
193
|
+
}
|
|
194
|
+
},
|
|
195
|
+
})
|
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
|
+
}
|