opencode-quill 0.1.5 → 0.2.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 CHANGED
@@ -4,6 +4,18 @@ All notable changes are documented in this file using
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and
5
5
  [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## [0.2.1] - 2026-10-13
8
+
9
+ ### Fixed
10
+
11
+ - **prediction:** Guard typo corrections and learning races
12
+
13
+ ## [0.2.0] - 2026-10-13
14
+
15
+ ### Added
16
+
17
+ - **prediction:** Add safe typo correction and context repair
18
+
7
19
  ## [0.1.5] - 2026-10-10
8
20
 
9
21
  ### Fixed
@@ -50,6 +62,8 @@ All notable changes are documented in this file using
50
62
  - `/quill` command and command palette action to toggle autocomplete.
51
63
  - Local installer script, full test suite, CI workflows, and release tooling.
52
64
 
65
+ [0.2.1]: https://github.com/ozandogrultan/opencode-quill/compare/v0.2.0...v0.2.1
66
+ [0.2.0]: https://github.com/ozandogrultan/opencode-quill/compare/v0.1.5...v0.2.0
53
67
  [0.1.5]: https://github.com/ozandogrultan/opencode-quill/compare/v0.1.4...v0.1.5
54
68
  [0.1.4]: https://github.com/ozandogrultan/opencode-quill/compare/v0.1.3...v0.1.4
55
69
  [0.1.3]: https://github.com/ozandogrultan/opencode-quill/compare/v0.1.2...v0.1.3
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # opencode-quill
2
2
 
3
- [![CI](https://github.com/ozandogrultan/opencode-quill/actions/workflows/ci.yml/badge.svg)](https://github.com/ozandogrultan/opencode-quill/actions/workflows/ci.yml)
3
+ [![CI](https://github.com/ozandogrultan/opencode-quill/actions/workflows/ci.yml/badge.svg)](https://github.com/ozandogrultan/opencode-quill/actions/workflows/ci.yml) [![npm](https://img.shields.io/npm/v/opencode-quill)](https://www.npmjs.com/package/opencode-quill)
4
4
 
5
5
  Local word autocomplete and next-word prediction for the **OpenCode V2** prompt
6
6
  composer — inspired by [oh-my-pi (OMP)](https://github.com/can1357/oh-my-pi)'s
@@ -10,38 +10,66 @@ As you type, Quill predicts the remainder of your current prose word or the next
10
10
  word in sequence, shown as dimmed inline ghost text directly at your cursor.
11
11
  Press <kbd>Tab</kbd> or <kbd>→</kbd> to accept it, or <kbd>Esc</kbd> to dismiss.
12
12
 
13
- ```text
14
- > can you refactor the test
15
- s ← dimmed ghost text, Tab or → to accept
16
- ```
17
-
18
13
  ## What it does
19
14
 
20
15
  - **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.
16
+ text to any model, API, or external service.
17
+ - **Context-aware ranking:** Blends a common-English vocabulary prior with an
18
+ online n-gram model (bigrams and trigrams) learned from your prompt history.
19
+ - **Completes words, fixes typos, and predicts next words:** Completes the active
20
+ prose prefix, offers single-edit corrections, and predicts following words
21
+ when learned evidence supports the sequence.
28
22
  - **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.
23
+ dimmed appearance (the theme's muted text color), rendered in the OpenTUI
24
+ buffer without displacing the cursor.
25
+ - **Safe acceptance:** Inserts or corrects the active word in the draft without
26
+ submitting. Supports native undo (<kbd>Ctrl+-</kbd> or <kbd>Cmd+Z</kbd>). Never
27
+ overwrites unrelated draft text and never touches the system clipboard.
34
28
  - **Coexists with Ghost:** [Ghost](https://github.com/ozandogrultan/opencode-ghost)
35
29
  suggests entire next prompts in an *empty* composer using a model; Quill
36
30
  predicts words in an *active* draft locally. When both are installed, each
37
31
  activates only in its respective domain without key conflicts.
38
32
  - **Prose-aware gating:** Automatically suppresses suggestions in code blocks,
39
33
  backticks, file paths, URLs, slash commands, shell executions, active selections,
40
- and modal dialogs.
34
+ composers holding attachments or pasted-text chips, and modal dialogs.
35
+ - **End-of-draft only:** Suggestions appear when the cursor is at the end of the
36
+ draft, either on a partial word or after a space.
37
+
38
+ ## What suggestions look like
39
+
40
+ The suggestion appears dimmed at the end of the draft. It is not part of the
41
+ editable text until you press <kbd>Tab</kbd> or <kbd>→</kbd>.
42
+
43
+ | Kind | Your draft | Dimmed suggestion | Draft after acceptance |
44
+ | --- | --- | --- | --- |
45
+ | Word completion | `please comp` | `lete` | `please complete` |
46
+ | Typo correction | `please cmplete` | ` → complete` | `please complete` |
47
+ | Next word | `please run ` | `tests` | `please run tests` |
48
+
49
+ A correction looks like this, with only ` → complete` dimmed:
50
+
51
+ ```text
52
+ > please cmplete → complete
53
+ ```
54
+
55
+ - **Completions append** the missing letters or next word.
56
+ - **Corrections replace only the active word**, preserving its initial-capital
57
+ or all-uppercase casing (`Cmplete` → `Complete`, `CMPLETE` → `COMPLETE`).
58
+ First-person contractions use a capital `I` in corrections and next-word
59
+ suggestions (`I'm`, `I'll`, `I've`, `I'd`). Lowercase contraction prefixes
60
+ are replaced on acceptance too (`i'v` → `I've`).
61
+ - **Normal completions take precedence.** For example, `whate` completes to
62
+ `whatever` rather than being corrected to `what`. Typo correction is a
63
+ fallback when no confident prefix completion is available; recognized words
64
+ are not corrected.
65
+ - **Earlier words are never rewritten.** With learned evidence for
66
+ `please run tests`, typing `please rnu ` can suggest `tests`. Accepting it
67
+ produces `please rnu tests`, leaving `rnu` unchanged.
41
68
 
42
69
  ## Requirements
43
70
 
44
- - [OpenCode](https://opencode.ai) ≥ 2.0.26 (V2 TUI plugin runtime).
71
+ - [OpenCode](https://opencode.ai) with the V2 TUI plugin runtime (the supported
72
+ range is `engines.opencode` in `package.json`).
45
73
  - Node.js (for the installer script).
46
74
 
47
75
  ## Install
@@ -54,7 +82,7 @@ Add the package to `plugins` in `~/.config/opencode/cli.json`:
54
82
  {
55
83
  "$schema": "https://opencode.ai/v2/cli.json",
56
84
  "plugins": [
57
- "opencode-quill@0.1.4"
85
+ "opencode-quill"
58
86
  ]
59
87
  }
60
88
  ```
@@ -141,84 +169,66 @@ Custom keybindings can also be overridden using OpenCode's standard
141
169
  - **Command Palette (`Ctrl+P`)** — Includes **Word autocomplete: on/off** and
142
170
  **Clear word autocomplete history**.
143
171
 
144
- ## Learning and Prediction Architecture
145
-
146
- ### 1. How Quill Learns
147
-
148
- Quill listens to OpenCode session events in real time:
149
- - `session.execution.started` (prompt submitted)
150
- - `session.execution.succeeded` (turn completed)
151
- - `session.inbox.delivered` (message delivered to a session)
152
-
153
- When a message is received:
154
- 1. **Deduplication:** Message IDs (`<sessionID>:<messageID>`) are checked against
155
- a rolling set of up to 8,000 processed messages so each prompt is ingested once.
156
- 2. **Prose Sanitization:** Text is stripped of markdown fenced code blocks, inline
157
- backticks, URLs, file paths (`foo/bar.ts`), camelCase identifiers, slash commands
158
- (`/command`), shell lines (`$ ...`), and lines indented by 4+ spaces.
159
- 3. **Sequence Splitting:** Consecutive prose words delimited by spaces or punctuation
160
- are partitioned into independent grammatical clauses. Punctuation (`.`, `,`, `!`, `?`)
161
- and code snippets reset the context window so words separated by syntax are never
162
- learned as adjacent phrases.
163
- 4. **Vocabulary Hygiene:** New words not present in the base dictionary must appear
164
- at least **twice** across distinct prompts before becoming suggestible candidates.
165
- This prevents accidental typos or one-off strings from entering your suggestions.
166
- Pasted blocks exceeding 4,000 characters or 12 lines are ignored.
167
-
168
- ### 2. How Predictions Grow
169
-
170
- The language model consists of two tiers:
171
-
172
- - **Baseline Prior:** A static unigram frequency table of 20,000 common English words
173
- derived from the open-source SUBTLEX corpus. Provides instant, high-quality
174
- spelling completions from your very first keystroke.
175
- - **Personal N-Gram Model:** Increments frequency counts as you submit prompts:
176
- - **Unigrams** (`w`): Individual word frequencies.
177
- - **Bigrams** (`u → w`): Transition frequencies from previous word `u`.
178
- - **Trigrams** (`u, v → w`): Transition frequencies from two preceding words `u, v`.
179
-
180
- **Scoring & Interpolation:**
181
- Candidates are scored using Jelinek-Mercer interpolation combined with absolute
182
- discounting ($D = 0.5$):
183
-
184
- $$\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)$$
185
-
186
- If strong trigram evidence exists, the contextual prediction dominates. As context
187
- thins out, the model falls back gracefully to bigram transitions and then unigram
188
- frequencies.
189
-
190
- **Prefix-Constrained Posterior:**
191
- When you type a prefix (e.g. `refac`), all candidates matching the prefix—including
192
- the prefix itself if it is already a complete word—are ranked. A suggestion is only
193
- displayed when its calibrated confidence exceeds a quality threshold (30% for prefix
194
- completions, 55% for next-word predictions). If the typed prefix is already the most
195
- probable word, no ghost text is shown.
196
-
197
- **Bounded Capacity:**
198
- To keep memory and storage footprint minimal, the personal model enforces strict caps:
199
- - Words: Top 8,000 most frequent entries
200
- - Bigrams: Top 30,000 transitions
201
- - Trigrams: Top 30,000 transitions
202
- - Message deduplication log: 8,000 IDs
203
-
204
- ### 3. Where State is Stored
205
-
206
- Quill uses OpenCode V2's durable plugin storage API (`context.storage.store`), which
207
- persists state as clean JSON files inside your standard XDG state directory:
208
-
209
- | Setting / Data | File Path |
172
+ ## How it works
173
+
174
+ ### Learning
175
+
176
+ Quill learns from your own submitted prompts, never from assistant output:
177
+
178
+ - It listens to session events (`session.execution.started`,
179
+ `session.execution.succeeded`, `session.inbox.delivered`).
180
+ - On startup and when you open a session, it also backfills from the user
181
+ messages of the current and most recently updated sessions.
182
+ - Each message is ingested once, tracked by `<sessionID>:<messageID>`.
183
+ - Only prose is learned. Code blocks, inline code, URLs, file paths,
184
+ identifiers, slash commands, shell lines, indented blocks and very large
185
+ pastes are ignored.
186
+ - Punctuation, line breaks and code reset the context, so words separated by
187
+ syntax are never learned as adjacent.
188
+ - A word missing from the base vocabulary becomes suggestible only after it
189
+ has been seen more than once.
190
+
191
+ ### Prediction
192
+
193
+ - **Baseline prior:** a bundled English word-frequency table (SUBTLEX) gives
194
+ useful completions from the first keystroke.
195
+ - **Personal model:** unigram, bigram and trigram counts from your prompts.
196
+ Context evidence falls back from trigram to bigram to unigram as it thins out.
197
+ - **Current draft:** words already in the draft get a small boost.
198
+ - **Confidence gating:** a suggestion is shown only when it clears a
199
+ confidence threshold, which is stricter for next-word predictions than for
200
+ prefix completions. If the typed prefix is already the most likely word,
201
+ nothing is shown.
202
+ - **Typo fallback:** when prefix completion is not confident enough, nearby
203
+ words are ranked with an edit penalty and a stricter confidence threshold.
204
+ Correction confidence is the edit-penalized model score. Suggestions must
205
+ clear an absolute evidence floor and a separate candidate-dominance check.
206
+ Corrections require at least three typed letters. Short words are eligible
207
+ only for whole-word letter swaps that preserve the first letter; other edits
208
+ and mistyped longer prefixes require at least five letters, except for
209
+ apostrophe contractions, including missing apostrophes. Deletions repair only
210
+ doubled letters, not arbitrary extra characters or word endings.
211
+ Unknown tokens such as `json`, `yaml`, `bool`, `opts`,
212
+ and `enum` are left unchanged, and uncertain typos such as `fucn` can produce
213
+ no suggestion. Context repair uses the same edit guards and confidence checks
214
+ and requires repeated learned continuation evidence; not every typo produces
215
+ a suggestion.
216
+ - **Bounded size:** the personal model is pruned to its most frequent entries
217
+ when saved.
218
+
219
+ ### Storage
220
+
221
+ Quill uses OpenCode's durable plugin storage, which writes JSON under the XDG
222
+ state directory (`$XDG_STATE_HOME` when set, otherwise `~/.local/state`):
223
+
224
+ | Data | File |
210
225
  | --- | --- |
211
- | **Learned Model** | `~/.local/state/opencode/<channel>/tui/plugin.quill.learning.json` |
212
- | **Plugin Settings** | `~/.local/state/opencode/<channel>/tui/plugin.quill.settings.json` |
213
-
214
- *(On systems with `$XDG_STATE_HOME` set, `$XDG_STATE_HOME/opencode/<channel>/tui/` is used).*
226
+ | Learned model | `opencode/<channel>/tui/plugin.quill.learning.json` |
227
+ | Settings | `opencode/<channel>/tui/plugin.quill.settings.json` |
215
228
 
216
- **Privacy Guarantee:**
217
- - The snapshot file stores **only token frequency pairs** (e.g. `["refactor", 12]`, `["run\0tests", 5]`)
218
- and the IDs of processed messages (`<sessionID>:<messageID>`).
219
- - **Raw prompt text is never written to disk or stored in snapshots.**
220
- - The storage files stay strictly on your local machine and are never tracked in Git
221
- or included in npm packages.
229
+ The learned model holds only word, bigram and trigram counts plus processed
230
+ message IDs. Raw prompt text is never written to disk. These files stay on your
231
+ machine and are never tracked in Git or published to npm.
222
232
 
223
233
  ## Development
224
234
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-quill",
3
- "version": "0.1.5",
4
- "description": "Local word autocomplete for the OpenCode V2 prompt composer.",
3
+ "version": "0.2.1",
4
+ "description": "OpenCode prompt autocomplete: local n-gram word and next-word prediction shown as inline ghost text in the TUI composer, accepted with Tab.",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Ozan Dogrultan",
@@ -20,7 +20,9 @@
20
20
  "autocomplete",
21
21
  "autosuggest",
22
22
  "ngram",
23
- "prompt"
23
+ "prompt",
24
+ "word-prediction",
25
+ "opencode-tui"
24
26
  ],
25
27
  "exports": {
26
28
  "./tui": "./src/tui.tsx"
package/src/ghost.ts CHANGED
@@ -75,7 +75,7 @@ export class ComposerGhost {
75
75
  const query = completionQuery(text, offset)
76
76
  let prediction = query && this.predictor.complete(query)
77
77
  const last = this.shown
78
- if (query && !query.next && last && text.startsWith(last.text)) {
78
+ if (query && !query.next && last && !last.prediction.replace && text.startsWith(last.text)) {
79
79
  const typed = text.slice(last.text.length)
80
80
  if (typed && last.prediction.suffix.startsWith(typed) && typed.length < last.prediction.suffix.length) {
81
81
  prediction = { ...last.prediction, suffix: last.prediction.suffix.slice(typed.length) }
@@ -99,9 +99,10 @@ export class ComposerGhost {
99
99
  }
100
100
  const x = this.editor.screenX + cursor.visualCol
101
101
  const y = this.editor.screenY + cursor.visualRow
102
+ const ghost = prediction.replace ? ` → ${prediction.suffix}` : prediction.suffix
102
103
  buffer.pushScissorRect(x, y, room, 1)
103
104
  try {
104
- buffer.drawText(prediction.suffix, x, y, this.color(), this.editor.backgroundColor)
105
+ buffer.drawText(ghost, x, y, this.color(), this.editor.backgroundColor)
105
106
  } finally {
106
107
  buffer.popScissorRect()
107
108
  }
@@ -114,13 +115,19 @@ export class ComposerGhost {
114
115
  this.editor.plainText !== shown.text || this.offset() !== shown.offset) return false
115
116
  if (!completionQuery(shown.text, shown.offset)) return false
116
117
  this.shown = undefined
117
- this.editor.insertText(shown.prediction.suffix)
118
+ if (shown.prediction.replace) {
119
+ this.editor.replaceText(shown.text.slice(0, shown.text.length - shown.prediction.replace) + shown.prediction.suffix)
120
+ this.editor.gotoBufferEnd()
121
+ } else {
122
+ this.editor.insertText(shown.prediction.suffix)
123
+ }
118
124
  this.editor.requestRender()
119
125
  return true
120
126
  }
121
127
 
122
128
  dismiss(): boolean {
123
- if (this.disposed || !this.shown || !eligibleComposer(this.view()) || this.editor.plainText !== this.shown.text) return false
129
+ if (this.disposed || !this.shown || !eligibleComposer(this.view()) ||
130
+ this.editor.plainText !== this.shown.text || this.offset() !== this.shown.offset) return false
124
131
  this.dismissed = this.editor.plainText
125
132
  this.shown = undefined
126
133
  this.editor.requestRender()
package/src/predictor.ts CHANGED
@@ -9,9 +9,10 @@ export type Snapshot = {
9
9
  seen: string[]
10
10
  }
11
11
  export type Prompt = { id: string; text: string }
12
- export type Prediction = { suffix: string; word: string; confidence: number }
12
+ export type Prediction = { suffix: string; word: string; confidence: number; replace?: number }
13
13
 
14
14
  const DISCOUNT = 0.5
15
+ const MIN_TYPO_SCORE = 0.000001
15
16
  const PRIOR_LIMIT = 20_000
16
17
  const WORD_LIMIT = 8000
17
18
  const CONTEXT_LIMIT = 30_000
@@ -98,6 +99,65 @@ function lowerBound(words: readonly string[], prefix: string): number {
98
99
  return low
99
100
  }
100
101
 
102
+ function editKind(source: string, target: string, targetLength = target.length): "transpose" | "insert" | "delete" | "substitute" | undefined {
103
+ const sourceLength = source.length
104
+ if (Math.abs(sourceLength - targetLength) > 1) return
105
+ let i = 0
106
+ while (i < sourceLength && i < targetLength && source.charCodeAt(i) === target.charCodeAt(i)) i++
107
+ if (i === sourceLength && i === targetLength) return
108
+ if (sourceLength === targetLength) {
109
+ if (i + 1 < sourceLength && source.charCodeAt(i) === target.charCodeAt(i + 1) && source.charCodeAt(i + 1) === target.charCodeAt(i)) {
110
+ for (let j = i + 2; j < sourceLength; j++) if (source.charCodeAt(j) !== target.charCodeAt(j)) return
111
+ return "transpose"
112
+ }
113
+ for (let j = i + 1; j < sourceLength; j++) if (source.charCodeAt(j) !== target.charCodeAt(j)) return
114
+ return "substitute"
115
+ }
116
+ if (sourceLength < targetLength) {
117
+ for (let j = i; j < sourceLength; j++) if (source.charCodeAt(j) !== target.charCodeAt(j + 1)) return
118
+ return "insert"
119
+ }
120
+ for (let j = i; j < targetLength; j++) if (source.charCodeAt(j + 1) !== target.charCodeAt(j)) return
121
+ const doubled = (i > 0 && source.charCodeAt(i) === source.charCodeAt(i - 1)) || (i + 1 < sourceLength && source.charCodeAt(i) === source.charCodeAt(i + 1))
122
+ return doubled ? "delete" : undefined
123
+ }
124
+
125
+ function typoWeight(prefix: string, word: string, wholeWord = false): number {
126
+ const prefixLength = prefix.length
127
+ const wordLength = word.length
128
+ if (prefixLength < 3) return 0
129
+ const sameHead = prefix[0] === word[0]
130
+ const swappedHead = prefixLength >= 5 && prefix[0] === word[1] && prefix[1] === word[0]
131
+ if (!sameHead && !swappedHead) return 0
132
+ const full = editKind(prefix, word)
133
+ if (wholeWord && !full) return 0
134
+ if (full === "transpose") return 0.25
135
+ if (full && prefixLength < 5 && !word.includes("'")) return 0
136
+ if (full === "insert" || full === "delete") return 0.06
137
+ if (full === "substitute") return 0.04
138
+ if (prefixLength < 5 || wordLength <= prefixLength) return 0
139
+ const partial = editKind(prefix, word, prefixLength)
140
+ if (partial === "transpose") return 0.06
141
+ if (partial === "substitute") return 0.02
142
+ if (wordLength > prefixLength + 1 && editKind(prefix, word, prefixLength + 1) === "insert") return 0.03
143
+ if (editKind(prefix, word, prefixLength - 1) === "delete") return 0.02
144
+ return 0
145
+ }
146
+
147
+ function typoConfidence(score: number, total: number): number | undefined {
148
+ if (score < MIN_TYPO_SCORE || score / (total || 1) < 0.45) return
149
+ return score
150
+ }
151
+
152
+ function applyCase(source: string, word: string): string {
153
+ if (source.length > 1 && source === source.toUpperCase()) return word.toUpperCase()
154
+ const first = source[0]
155
+ if (first && first === first.toUpperCase() && first !== first.toLowerCase()) {
156
+ return word[0].toUpperCase() + word.slice(1)
157
+ }
158
+ return word === "i" || word.startsWith("i'") ? `I${word.slice(1)}` : word
159
+ }
160
+
101
161
  export class WordPredictor {
102
162
  readonly prior = new Map<string, number>()
103
163
  private priorTotal = 0
@@ -126,6 +186,19 @@ export class WordPredictor {
126
186
  this.vocabulary = [...new Set([...this.prior.keys(), ...[...this.personal.words].filter(([, count]) => count >= 2).map(([word]) => word)])].sort()
127
187
  }
128
188
 
189
+ private *nearbyWords(prefix: string, wholeWord = false): IterableIterator<string> {
190
+ const heads = [prefix[0]]
191
+ if (prefix.length >= 5 && prefix[0] !== prefix[1]) heads.push(prefix[1] + prefix[0])
192
+ const maxLength = wholeWord || prefix.length < 5 ? prefix.length + 1 : Infinity
193
+ for (const head of heads) {
194
+ for (let index = lowerBound(this.vocabulary, head); index < this.vocabulary.length; index++) {
195
+ const word = this.vocabulary[index]
196
+ if (!word.startsWith(head)) break
197
+ if (word.length >= prefix.length - 1 && word.length <= maxLength) yield word
198
+ }
199
+ }
200
+ }
201
+
129
202
  private score(word: string, context: readonly string[]): number {
130
203
  const prior = (this.prior.get(word) ?? 0) / (this.priorTotal || 1)
131
204
  const personal = (this.personal.words.get(word) ?? 0) / (this.personalTotal || 1)
@@ -146,37 +219,85 @@ export class WordPredictor {
146
219
  return score
147
220
  }
148
221
 
222
+ private resolveContext(raw: readonly string[], local: ReadonlyMap<string, number>): string[] {
223
+ const resolved: string[] = []
224
+ for (const word of raw) {
225
+ if (this.prior.has(word) || (this.personal.words.get(word) ?? 0) >= 2 || (local.get(word) ?? 0) >= 2 || word.length < 3) {
226
+ resolved.push(word)
227
+ continue
228
+ }
229
+ let best = word
230
+ let bestScore = 0
231
+ let sum = 0
232
+ for (const candidate of this.nearbyWords(word, true)) {
233
+ if ((this.bigramTotals.get(candidate)?.total ?? 0) < 2) continue
234
+ const weight = typoWeight(word, candidate, true)
235
+ if (!weight) continue
236
+ const score = this.score(candidate, resolved) * weight
237
+ sum += score
238
+ if (score > bestScore) {
239
+ best = candidate
240
+ bestScore = score
241
+ }
242
+ }
243
+ resolved.push(typoConfidence(bestScore, sum) === undefined ? word : best)
244
+ }
245
+ return resolved
246
+ }
247
+
149
248
  complete(query: CompletionQuery): Prediction | undefined {
150
249
  const prefix = normalizeWord(query.prefix)
151
- const context = leftContext(query.before)
250
+ const words = query.words ?? proseWords(query.before)
251
+ const local = new Map<string, number>()
252
+ for (const word of words) increment(local, word.text)
253
+ const context = this.resolveContext(leftContext(query.before, words), local)
152
254
  const evidence = this.bigramTotals.get(context.at(-1) ?? "")?.total ?? 0
153
255
  if (query.next && evidence < 2) return
154
256
  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>()
257
+ const candidates = new Map<string, number>()
158
258
  for (let index = lowerBound(this.vocabulary, prefix); index < this.vocabulary.length; index++) {
159
259
  const word = this.vocabulary[index]
160
260
  if (!word.startsWith(prefix)) break
161
- candidates.add(word)
261
+ candidates.set(word, 1)
162
262
  }
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
263
+ for (const word of local.keys()) if (word.startsWith(prefix)) candidates.set(word, 1)
264
+ const suggest = (): Prediction | undefined => {
265
+ let best = ""
266
+ let bestScore = 0
267
+ let bestWeight = 1
268
+ let sum = 0
269
+ for (const [word, weight] of candidates) {
270
+ const base = this.score(word, context) + (query.next ? 0 : 0.003 * Math.min(local.get(word) ?? 0, 3))
271
+ const score = base * weight
272
+ sum += score
273
+ if (score > bestScore) {
274
+ best = word
275
+ bestScore = score
276
+ bestWeight = weight
277
+ }
173
278
  }
279
+ const confidence = bestWeight < 1 ? typoConfidence(bestScore, sum) : query.next ? bestScore : bestScore / (sum || 1)
280
+ if (!best || best === prefix || confidence === undefined || (bestWeight === 1 && confidence < (query.next ? 0.55 : 0.3))) return
281
+ if (bestWeight < 1 || (!query.next && best.startsWith("i'") && query.prefix[0] === "i")) {
282
+ return { suffix: applyCase(query.prefix, best), word: best, confidence, replace: query.prefix.length }
283
+ }
284
+ let suffix = best.slice(prefix.length)
285
+ if (query.prefix.length > 1 && query.prefix === query.prefix.toUpperCase()) suffix = suffix.toUpperCase()
286
+ if (query.next) suffix = applyCase("", best)
287
+ return { suffix, word: best, confidence }
288
+ }
289
+ const completion = suggest()
290
+ if (completion || query.next || prefix.length < 3 || candidates.has(prefix)) return completion
291
+ for (const word of this.nearbyWords(prefix)) {
292
+ if (candidates.has(word)) continue
293
+ const weight = typoWeight(prefix, word)
294
+ if (weight > 0) candidates.set(word, weight)
295
+ }
296
+ for (const word of local.keys()) {
297
+ if (candidates.has(word)) continue
298
+ const weight = typoWeight(prefix, word)
299
+ if (weight > 0) candidates.set(word, weight)
174
300
  }
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 }
301
+ return suggest()
181
302
  }
182
303
  }
package/src/prose.ts CHANGED
@@ -3,7 +3,7 @@ const WHOLE_WORD = /^[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*$/u
3
3
  const WORD_END = /[\p{L}\p{M}]+(?:['’][\p{L}\p{M}]+)*$/u
4
4
 
5
5
  export type Word = { text: string; start: number; end: number }
6
- export type CompletionQuery = { before: string; prefix: string; next: boolean }
6
+ export type CompletionQuery = { before: string; prefix: string; next: boolean; words?: readonly Word[] }
7
7
 
8
8
  export function normalizeWord(word: string): string {
9
9
  return word.normalize("NFC").replaceAll("’", "'").toLowerCase()
@@ -32,8 +32,7 @@ export function maskProse(text: string): string {
32
32
  return masked
33
33
  }
34
34
 
35
- export function proseWords(text: string): Word[] {
36
- const masked = maskProse(text)
35
+ export function proseWords(text: string, masked = maskProse(text)): Word[] {
37
36
  return [...masked.matchAll(WORD)]
38
37
  .filter((match) => isWord(match[0]))
39
38
  .map((match) => ({ text: normalizeWord(match[0]), start: match.index, end: match.index + match[0].length }))
@@ -51,8 +50,7 @@ export function proseSequences(text: string): string[][] {
51
50
  return sequences
52
51
  }
53
52
 
54
- export function leftContext(before: string): string[] {
55
- const words = proseWords(before)
53
+ export function leftContext(before: string, words: readonly Word[] = proseWords(before)): string[] {
56
54
  const result: string[] = []
57
55
  let end = before.length
58
56
  for (let index = words.length - 1; index >= 0 && result.length < 2; index--) {
@@ -68,13 +66,17 @@ export function completionQuery(text: string, characterOffset: number): Completi
68
66
  if (!text.trim() || characterOffset !== text.length || text.length > 16_000) return
69
67
  const masked = maskProse(text)
70
68
  const prefix = WORD_END.exec(text)?.[0]
69
+ let end = text.length
71
70
  if (prefix) {
72
71
  const start = text.length - prefix.length
73
72
  if (masked.slice(start) !== prefix || !isWord(prefix)) return
74
73
  const preceding = text[start - 1]
75
74
  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 }
75
+ end = start
76
+ } else if (!/[ \t]$/.test(text)) return
77
+ const start = Math.max(0, end - 2000)
78
+ const before = text.slice(start, end)
79
+ const words = proseWords(before, masked.slice(start, end))
80
+ if (!prefix && !leftContext(before, words).length) return
81
+ return { before, prefix: prefix ?? "", next: !prefix, words }
80
82
  }
package/src/tui.tsx CHANGED
@@ -21,11 +21,12 @@ export default Plugin.define({
21
21
  const predictor = new WordPredictor(frequencies)
22
22
  const composers = new Map<string, { marker: BoxRenderable; normal: () => boolean }>()
23
23
  const seeded = new Set<string>()
24
- const inFlight = new Set<string>()
24
+ const inFlight = new Map<string, { pending: boolean; announce: boolean }>()
25
25
  const [revision, setRevision] = createSignal(0)
26
26
  let ghost: ComposerGhost | undefined
27
27
  let disposed = false
28
28
  let warned = false
29
+ let resetVersion = 0
29
30
 
30
31
  const routeKey = () => {
31
32
  const route = context.ui.router.current()
@@ -57,31 +58,63 @@ export default Plugin.define({
57
58
  }
58
59
 
59
60
  const learn = async (sessionID: string, announce = true) => {
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 (error) {
76
- if (announce && !disposed && !warned) {
77
- warned = true
78
- context.ui.toast.show({ title: "Quill", message: `History learning unavailable (${sessionID}: ${error instanceof Error ? error.message : String(error)}); vocabulary completion is still active.`, variant: "warning" })
61
+ if (disposed || !settings.enabled) return
62
+ const active = inFlight.get(sessionID)
63
+ if (active) {
64
+ if (announce) {
65
+ active.pending = true
66
+ active.announce = true
79
67
  }
68
+ return
69
+ }
70
+ const state = { pending: false, announce }
71
+ inFlight.set(sessionID, state)
72
+ try {
73
+ do {
74
+ state.pending = false
75
+ const version = resetVersion
76
+ const shouldAnnounce = state.announce
77
+ state.announce = false
78
+ try {
79
+ await context.data.session.message.sync(sessionID)
80
+ if (disposed || !settings.enabled) return
81
+ if (version !== resetVersion) continue
82
+ const prompts = context.data.session.message.list(sessionID)
83
+ .filter((message) => message.type === "user")
84
+ .slice(-200)
85
+ .map((message) => ({ id: `${sessionID}:${message.id}`, text: message.text }))
86
+ const model = new PersonalModel(learning.snapshot)
87
+ if (model.observe(prompts)) {
88
+ await setLearning((draft) => {
89
+ if (disposed || !settings.enabled || version !== resetVersion) return
90
+ const latest = new PersonalModel(draft.snapshot)
91
+ if (latest.observe(prompts)) draft.snapshot = latest.snapshot()
92
+ })
93
+ }
94
+ } catch (error) {
95
+ if (shouldAnnounce && !disposed && version === resetVersion && !warned) {
96
+ warned = true
97
+ context.ui.toast.show({ title: "Quill", message: `History learning unavailable (${sessionID}: ${error instanceof Error ? error.message : String(error)}); vocabulary completion is still active.`, variant: "warning" })
98
+ }
99
+ }
100
+ } while (state.pending && !disposed && settings.enabled)
80
101
  } finally {
81
102
  inFlight.delete(sessionID)
82
103
  }
83
104
  }
84
105
 
106
+ const clearHistory = async () => {
107
+ resetVersion++
108
+ for (const state of inFlight.values()) {
109
+ state.pending = false
110
+ state.announce = false
111
+ }
112
+ predictor.setPersonal(emptySnapshot())
113
+ await setLearning((draft) => { draft.snapshot = emptySnapshot() })
114
+ ghost?.invalidate()
115
+ context.ui.toast.show({ title: "Quill", message: "Word autocomplete history cleared" })
116
+ }
117
+
85
118
  const disposeEffects = createRoot((dispose) => {
86
119
  createEffect(() => {
87
120
  predictor.setPersonal(learning.snapshot)
@@ -128,10 +161,7 @@ export default Plugin.define({
128
161
  run: async (input) => {
129
162
  const command = parseQuillCommand(input)
130
163
  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" })
164
+ await clearHistory()
135
165
  return
136
166
  }
137
167
  if (command.type === "invalid") {
@@ -150,12 +180,7 @@ export default Plugin.define({
150
180
  description: "Reset learned vocabulary, n-grams, and prompt transitions",
151
181
  group: "Prompt",
152
182
  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
- },
183
+ run: clearHistory,
159
184
  },
160
185
  ],
161
186
  }))