opencode-quill 0.5.2 → 0.6.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 +14 -0
- package/README.md +22 -8
- package/package.json +1 -1
- package/src/ghost.ts +20 -12
- package/src/options.ts +8 -1
- package/src/predictor.ts +40 -33
- package/src/prose.ts +67 -18
- package/src/shell.ts +36 -0
- package/src/tui.tsx +67 -22
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.6.1] - 2026-10-22
|
|
8
|
+
|
|
9
|
+
### Fixed
|
|
10
|
+
|
|
11
|
+
- **prediction:** Correct sentence-start casing, trigram scoring, and next-word filtering
|
|
12
|
+
|
|
13
|
+
## [0.6.0] - 2026-10-22
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- **completion:** Learn hyphenated words, brand names, filenames and shell commands
|
|
18
|
+
|
|
7
19
|
## [0.5.2] - 2026-10-22
|
|
8
20
|
|
|
9
21
|
### Fixed
|
|
@@ -127,6 +139,8 @@ All notable changes are documented in this file using
|
|
|
127
139
|
- `/quill` command and command palette action to toggle autocomplete.
|
|
128
140
|
- Local installer script, full test suite, CI workflows, and release tooling.
|
|
129
141
|
|
|
142
|
+
[0.6.1]: https://github.com/ozandogrultan/opencode-quill/compare/v0.6.0...v0.6.1
|
|
143
|
+
[0.6.0]: https://github.com/ozandogrultan/opencode-quill/compare/v0.5.2...v0.6.0
|
|
130
144
|
[0.5.2]: https://github.com/ozandogrultan/opencode-quill/compare/v0.5.1...v0.5.2
|
|
131
145
|
[0.5.1]: https://github.com/ozandogrultan/opencode-quill/compare/v0.5.0...v0.5.1
|
|
132
146
|
[0.5.0]: https://github.com/ozandogrultan/opencode-quill/compare/v0.4.0...v0.5.0
|
package/README.md
CHANGED
|
@@ -41,8 +41,15 @@ Press <kbd>Tab</kbd> or <kbd>→</kbd> to accept it, or <kbd>Esc</kbd> to dismis
|
|
|
41
41
|
predicts words in an *active* draft locally. When both are installed, each
|
|
42
42
|
activates only in its respective domain without key conflicts.
|
|
43
43
|
- **Prose-aware gating:** Automatically suppresses suggestions in code blocks,
|
|
44
|
-
backticks, file paths, URLs, slash commands,
|
|
45
|
-
|
|
44
|
+
backticks, file paths, URLs, slash commands, active selections, and modal
|
|
45
|
+
dialogs. Hyphenated words (`read-only`), brand names (`OpenCode`, `GitHub`)
|
|
46
|
+
and bare filenames with common extensions (`install.sh`) count as prose;
|
|
47
|
+
identifiers (`showSidebar`), flags and `key=value` tokens do not.
|
|
48
|
+
- **Shell mode:** In the prompt's shell mode Quill completes commands,
|
|
49
|
+
subcommands and flags from a separate vocabulary learned from the commands
|
|
50
|
+
you ran, never from prose. Shell completion is case-sensitive, never corrects
|
|
51
|
+
typos, and skips paths, quoted strings, `$` expansions, assignments and any
|
|
52
|
+
command that mentions a token, secret, password, key or credential. Attachment and pasted-text chips are treated as non-prose:
|
|
46
53
|
words are still suggested after them, but never inside them, and typo
|
|
47
54
|
replacements are not offered while a chip is present.
|
|
48
55
|
- **End-of-draft by default:** Suggestions appear on a partial word or after a
|
|
@@ -167,6 +174,7 @@ Restart OpenCode after editing `cli.json`.
|
|
|
167
174
|
| --- | --- | --- | --- |
|
|
168
175
|
| `enabled` | `boolean` | `true` | Initial default for suggestions and learning; a persisted `/quill` toggle takes precedence. |
|
|
169
176
|
| `completeAtLineEnd` | `boolean` | `false` | Also append completions or next words immediately before a newline within a draft. |
|
|
177
|
+
| `completeShell` | `boolean` | `true` | Initial default for shell-mode suggestions and learning; a persisted `/quill shell` toggle takes precedence. |
|
|
170
178
|
| `acceptKeys` | `string[]` | `["tab", "right"]` | Keys that accept and insert the active word suggestion. |
|
|
171
179
|
| `dismissKeys` | `string[]` | `["escape"]` | Keys that dismiss the visible suggestion without inserting. |
|
|
172
180
|
| `cycleNextKeys` | `string[]` | `[]` | Optional keys for the next confident word suggestion. |
|
|
@@ -211,7 +219,9 @@ handlers remain in control. Dialogs and selections also suppress Quill.
|
|
|
211
219
|
|
|
212
220
|
- `/quill` — Toggle word autocomplete on or off (persisted across sessions).
|
|
213
221
|
- `/quill on` / `/quill off` — Set autocomplete explicitly.
|
|
214
|
-
- `/quill
|
|
222
|
+
- `/quill shell on` / `/quill shell off` — Set shell-mode autocomplete explicitly.
|
|
223
|
+
- `/quill clear casing` (alias `/quill reset casing`) — Forget only the learned word casing (`OpenCode`, `GitHub`), keeping the vocabulary and phrases.
|
|
224
|
+
- `/quill clear` (alias `/quill reset`) — Erase everything Quill has learned from your prompts and shell commands.
|
|
215
225
|
- `quill.next` / `quill.previous` — Keymap commands for cycling visible word
|
|
216
226
|
alternatives; no default bindings. Configure the cycle options above or
|
|
217
227
|
OpenCode's `keybinds` map.
|
|
@@ -232,8 +242,11 @@ Quill learns from your own submitted prompts, never from assistant output:
|
|
|
232
242
|
processed IDs, including those of ignored pastes, are retained until
|
|
233
243
|
`/quill clear`.
|
|
234
244
|
- Only prose is learned. Code blocks, inline code, URLs, file paths,
|
|
235
|
-
identifiers, slash commands, shell lines, indented blocks
|
|
236
|
-
pastes are ignored.
|
|
245
|
+
identifiers, slash commands, shell lines, indented blocks that do not
|
|
246
|
+
continue a list item, and very large pastes are ignored.
|
|
247
|
+
- Commands you run in shell mode are learned into a separate shell model from
|
|
248
|
+
the session's shell messages, on the same triggers and with the same
|
|
249
|
+
deduplication. Only plain words and flags are kept.
|
|
237
250
|
- Punctuation, line breaks and code reset the context, so words separated by
|
|
238
251
|
syntax are never learned as adjacent.
|
|
239
252
|
- A word missing from the base vocabulary becomes suggestible only after it
|
|
@@ -279,14 +292,15 @@ state directory (`$XDG_STATE_HOME` when set, otherwise `~/.local/state`):
|
|
|
279
292
|
| Data | File |
|
|
280
293
|
| --- | --- |
|
|
281
294
|
| Learned model | `opencode/<channel>/tui/plugin.quill.learning.json` |
|
|
295
|
+
| Learned shell model | `opencode/<channel>/tui/plugin.quill.shell.json` |
|
|
282
296
|
| Settings | `opencode/<channel>/tui/plugin.quill.settings.json` |
|
|
283
297
|
|
|
284
|
-
The learned
|
|
298
|
+
The learned models hold word, bigram, trigram and word-casing counts plus
|
|
285
299
|
processed message IDs. These include local one-to-three-word fragments from
|
|
286
300
|
your prose, so the model can reveal parts of your prompts. Quill does not store
|
|
287
301
|
raw prompts or full message bodies. These files stay on your machine and are
|
|
288
|
-
never tracked in Git or published to npm. `/quill clear` erases
|
|
289
|
-
|
|
302
|
+
never tracked in Git or published to npm. `/quill clear` erases both learned
|
|
303
|
+
models; the persisted on/off settings are separate.
|
|
290
304
|
|
|
291
305
|
The processed-ID ledger is not pruned: its memory usage, stored size, and full
|
|
292
306
|
serialization cost grow with the number of processed messages. Word and context
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-quill",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.1",
|
|
4
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",
|
package/src/ghost.ts
CHANGED
|
@@ -7,6 +7,7 @@ export type Composer = {
|
|
|
7
7
|
normal: boolean
|
|
8
8
|
focused: unknown
|
|
9
9
|
mode: string
|
|
10
|
+
shell?: boolean
|
|
10
11
|
selected: boolean
|
|
11
12
|
enabled: boolean
|
|
12
13
|
}
|
|
@@ -39,9 +40,9 @@ export function findComposer(marker: Renderable | undefined, isEditor: (node: Re
|
|
|
39
40
|
}
|
|
40
41
|
|
|
41
42
|
export class ComposerGhost {
|
|
42
|
-
private shown: { text: string; offset: number; prediction: Prediction; marks: string; revision: number } | undefined
|
|
43
|
+
private shown: { text: string; offset: number; prediction: Prediction; marks: string; revision: number; predictor: WordPredictor } | undefined
|
|
43
44
|
private dismissed: { text: string; offset: number } | undefined
|
|
44
|
-
private memo: { text: string; offset: number; marks: string; revision: number; predictions: Prediction[]; index: number } | undefined
|
|
45
|
+
private memo: { text: string; offset: number; marks: string; revision: number; predictor: WordPredictor; predictions: Prediction[]; index: number } | undefined
|
|
45
46
|
private disposed = false
|
|
46
47
|
private readonly draw: (buffer: OptimizedBuffer, delta: number) => void
|
|
47
48
|
|
|
@@ -52,11 +53,16 @@ export class ComposerGhost {
|
|
|
52
53
|
private readonly color: () => RGBA,
|
|
53
54
|
private readonly renderer: CliRenderer,
|
|
54
55
|
private readonly completeAtLineEnd = false,
|
|
56
|
+
private readonly shellPredictor?: WordPredictor,
|
|
55
57
|
) {
|
|
56
58
|
this.draw = (buffer) => { if (!this.disposed) this.paint(buffer) }
|
|
57
59
|
renderer.addPostProcessFn(this.draw)
|
|
58
60
|
}
|
|
59
61
|
|
|
62
|
+
private active(): WordPredictor {
|
|
63
|
+
return this.shellPredictor && this.view().shell ? this.shellPredictor : this.predictor
|
|
64
|
+
}
|
|
65
|
+
|
|
60
66
|
private offset(): number {
|
|
61
67
|
return this.editor.editBuffer.getTextRange(0, this.editor.cursorOffset).length
|
|
62
68
|
}
|
|
@@ -96,20 +102,22 @@ export class ComposerGhost {
|
|
|
96
102
|
if (this.dismissed || !eligibleComposer(this.view(), text)) return
|
|
97
103
|
const marks = this.editor.extmarks.getAll()
|
|
98
104
|
const signature = this.marksKey()
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
const
|
|
105
|
+
const predictor = this.active()
|
|
106
|
+
const revision = predictor.modelRevision
|
|
107
|
+
if (this.memo?.text === text && this.memo.offset === offset && this.memo.marks === signature && this.memo.revision === revision && this.memo.predictor === predictor) return this.memo.predictions[this.memo.index]
|
|
108
|
+
const query = completionQuery(text, offset, this.protectedRanges(marks), this.completeAtLineEnd, predictor.grammar)
|
|
109
|
+
const predictions = query ? predictor.candidates(query) : []
|
|
103
110
|
if ((marks.length || offset !== text.length) && predictions[0]?.replace) predictions.length = 0
|
|
104
111
|
else if (marks.length || offset !== text.length) predictions.splice(0, predictions.length, ...predictions.filter((prediction) => !prediction.replace))
|
|
105
112
|
const last = this.shown
|
|
106
|
-
if (query && !query.next && offset === text.length && last && last.offset === last.text.length && this.memo?.index === 0 && last.revision === revision && last.marks === signature && !last.prediction.replace && text.startsWith(last.text)) {
|
|
113
|
+
if (query && !query.next && offset === text.length && last && last.offset === last.text.length && this.memo?.index === 0 && last.revision === revision && last.predictor === predictor && last.marks === signature && !last.prediction.replace && text.startsWith(last.text)) {
|
|
107
114
|
const typed = text.slice(last.text.length)
|
|
108
115
|
if (typed && last.prediction.suffix.startsWith(typed) && typed.length < last.prediction.suffix.length) {
|
|
109
|
-
|
|
116
|
+
const sticky = { ...last.prediction, suffix: last.prediction.suffix.slice(typed.length) }
|
|
117
|
+
predictions.splice(0, predictions.length, sticky, ...predictions.filter((prediction) => prediction.word !== sticky.word))
|
|
110
118
|
}
|
|
111
119
|
}
|
|
112
|
-
this.memo = { text, offset, marks: signature, revision, predictions, index: 0 }
|
|
120
|
+
this.memo = { text, offset, marks: signature, revision, predictor, predictions, index: 0 }
|
|
113
121
|
return predictions[0]
|
|
114
122
|
}
|
|
115
123
|
|
|
@@ -140,14 +148,14 @@ export class ComposerGhost {
|
|
|
140
148
|
} finally {
|
|
141
149
|
buffer.popScissorRect()
|
|
142
150
|
}
|
|
143
|
-
this.shown = { text, offset, prediction, marks: this.memo!.marks, revision: this.memo!.revision }
|
|
151
|
+
this.shown = { text, offset, prediction, marks: this.memo!.marks, revision: this.memo!.revision, predictor: this.memo!.predictor }
|
|
144
152
|
}
|
|
145
153
|
|
|
146
154
|
accept(): boolean {
|
|
147
155
|
const shown = this.shown
|
|
148
156
|
if (!shown || !this.visible()) return false
|
|
149
157
|
const marks = this.editor.extmarks.getAll()
|
|
150
|
-
if (!completionQuery(shown.text, shown.offset, this.protectedRanges(marks), this.completeAtLineEnd)) return false
|
|
158
|
+
if (!completionQuery(shown.text, shown.offset, this.protectedRanges(marks), this.completeAtLineEnd, shown.predictor.grammar)) return false
|
|
151
159
|
if ((marks.length || shown.offset !== shown.text.length) && shown.prediction.replace) return false
|
|
152
160
|
this.shown = undefined
|
|
153
161
|
if (shown.prediction.replace) {
|
|
@@ -171,7 +179,7 @@ export class ComposerGhost {
|
|
|
171
179
|
visible(): boolean {
|
|
172
180
|
return !this.disposed && !!this.shown && eligibleComposer(this.view()) &&
|
|
173
181
|
this.editor.plainText === this.shown.text && this.offset() === this.shown.offset &&
|
|
174
|
-
this.marksKey() === this.shown.marks && this.predictor.modelRevision === this.shown.revision && this.fits(this.shown.prediction)
|
|
182
|
+
this.marksKey() === this.shown.marks && this.active() === this.shown.predictor && this.shown.predictor.modelRevision === this.shown.revision && this.fits(this.shown.prediction)
|
|
175
183
|
}
|
|
176
184
|
|
|
177
185
|
canCycle(): boolean {
|
package/src/options.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type Options = { enabled: boolean; completeAtLineEnd: boolean; acceptKeys: string[]; dismissKeys: string[]; cycleNextKeys: string[]; cyclePreviousKeys: string[] }
|
|
1
|
+
export type Options = { enabled: boolean; completeAtLineEnd: boolean; completeShell: boolean; acceptKeys: string[]; dismissKeys: string[]; cycleNextKeys: string[]; cyclePreviousKeys: string[] }
|
|
2
2
|
|
|
3
3
|
function keys(value: unknown, fallback: string[], name: string): string[] {
|
|
4
4
|
if (value === undefined) return fallback
|
|
@@ -11,9 +11,11 @@ function keys(value: unknown, fallback: string[], name: string): string[] {
|
|
|
11
11
|
export function resolveOptions(input: Readonly<Record<string, unknown>>): Options {
|
|
12
12
|
if (input.enabled !== undefined && typeof input.enabled !== "boolean") throw new Error("Quill enabled must be a boolean")
|
|
13
13
|
if (input.completeAtLineEnd !== undefined && typeof input.completeAtLineEnd !== "boolean") throw new Error("Quill completeAtLineEnd must be a boolean")
|
|
14
|
+
if (input.completeShell !== undefined && typeof input.completeShell !== "boolean") throw new Error("Quill completeShell must be a boolean")
|
|
14
15
|
return {
|
|
15
16
|
enabled: input.enabled !== false,
|
|
16
17
|
completeAtLineEnd: input.completeAtLineEnd === true,
|
|
18
|
+
completeShell: input.completeShell !== false,
|
|
17
19
|
acceptKeys: keys(input.acceptKeys, ["tab", "right"], "acceptKeys"),
|
|
18
20
|
dismissKeys: keys(input.dismissKeys, ["escape"], "dismissKeys"),
|
|
19
21
|
cycleNextKeys: keys(input.cycleNextKeys, [], "cycleNextKeys"),
|
|
@@ -25,13 +27,18 @@ export type QuillCommand =
|
|
|
25
27
|
| { type: "toggle" }
|
|
26
28
|
| { type: "enable"; value: boolean }
|
|
27
29
|
| { type: "clear" }
|
|
30
|
+
| { type: "shell"; value: boolean }
|
|
31
|
+
| { type: "casing" }
|
|
28
32
|
| { type: "invalid" }
|
|
29
33
|
|
|
30
34
|
export function parseQuillCommand(input: string | undefined): QuillCommand {
|
|
31
35
|
const raw = input?.trim().toLowerCase() ?? ""
|
|
32
36
|
if (!raw || raw === "toggle") return { type: "toggle" }
|
|
33
37
|
if (raw === "clear" || raw === "reset") return { type: "clear" }
|
|
38
|
+
if (raw === "clear casing" || raw === "reset casing") return { type: "casing" }
|
|
34
39
|
if (raw === "on") return { type: "enable", value: true }
|
|
35
40
|
if (raw === "off") return { type: "enable", value: false }
|
|
41
|
+
if (raw === "shell on") return { type: "shell", value: true }
|
|
42
|
+
if (raw === "shell off") return { type: "shell", value: false }
|
|
36
43
|
return { type: "invalid" }
|
|
37
44
|
}
|
package/src/predictor.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { leftContext, proseGrammar, proseWords, type CompletionQuery, type Grammar } from "./prose"
|
|
2
2
|
|
|
3
3
|
export type Frequency = { word: string; count: number }
|
|
4
4
|
export type Snapshot = {
|
|
@@ -30,13 +30,13 @@ function sentenceStart(text: string, start: number): boolean {
|
|
|
30
30
|
return index < 0 || /[\n.!?:]/.test(text[index])
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
function restore(rows: [string, number][], limit: number, parts = 1, forms = false): Map<string, number> {
|
|
33
|
+
function restore(rows: [string, number][], limit: number, grammar: Grammar, parts = 1, forms = false): Map<string, number> {
|
|
34
34
|
return new Map(rows.slice(0, limit).filter(([key, count]) => {
|
|
35
35
|
if (typeof key !== "string" || key.length > parts * 64 + parts - 1 || !Number.isFinite(count) || count <= 0) return false
|
|
36
36
|
const words = key.split("\0")
|
|
37
|
-
return words.length === parts && words.every((word) => isWord(word) && (forms
|
|
37
|
+
return words.length === parts && words.every((word) => grammar.isWord(word) && (forms
|
|
38
38
|
? word === word.normalize("NFC").replaceAll("’", "'")
|
|
39
|
-
: word ===
|
|
39
|
+
: word === grammar.normalize(word)))
|
|
40
40
|
}))
|
|
41
41
|
}
|
|
42
42
|
|
|
@@ -60,12 +60,12 @@ export class PersonalModel {
|
|
|
60
60
|
readonly seen: Set<string>
|
|
61
61
|
readonly clearedAt: number | undefined
|
|
62
62
|
|
|
63
|
-
constructor(snapshot: Snapshot = emptySnapshot()) {
|
|
63
|
+
constructor(snapshot: Snapshot = emptySnapshot(), private readonly grammar: Grammar = proseGrammar) {
|
|
64
64
|
this.clearedAt = Number.isFinite(snapshot.clearedAt) ? snapshot.clearedAt : undefined
|
|
65
|
-
this.words = restore(snapshot.words, WORD_LIMIT)
|
|
66
|
-
this.bigrams = restore(snapshot.bigrams, CONTEXT_LIMIT, 2)
|
|
67
|
-
this.trigrams = restore(snapshot.trigrams, CONTEXT_LIMIT, 3)
|
|
68
|
-
this.forms = restore(snapshot.forms ?? [], WORD_LIMIT, 1, true)
|
|
65
|
+
this.words = restore(snapshot.words, WORD_LIMIT, grammar)
|
|
66
|
+
this.bigrams = restore(snapshot.bigrams, CONTEXT_LIMIT, grammar, 2)
|
|
67
|
+
this.trigrams = restore(snapshot.trigrams, CONTEXT_LIMIT, grammar, 3)
|
|
68
|
+
this.forms = restore(snapshot.forms ?? [], WORD_LIMIT, grammar, 1, true)
|
|
69
69
|
this.seen = new Set(snapshot.seen)
|
|
70
70
|
}
|
|
71
71
|
|
|
@@ -76,13 +76,14 @@ export class PersonalModel {
|
|
|
76
76
|
this.seen.add(prompt.id)
|
|
77
77
|
changed = true
|
|
78
78
|
if (prompt.text.length > 4000 || prompt.text.split("\n").length > 12) continue
|
|
79
|
-
|
|
79
|
+
const masked = this.grammar.prose ? this.grammar.mask(prompt.text) : prompt.text
|
|
80
|
+
for (const sequence of this.grammar.sequences(prompt.text)) {
|
|
80
81
|
const words = sequence.map((word) => word.text)
|
|
81
82
|
for (let index = 0; index < words.length; index++) {
|
|
82
83
|
const { start, end } = sequence[index]
|
|
83
84
|
increment(this.words, words[index])
|
|
84
85
|
const form = prompt.text.slice(start, end).normalize("NFC").replaceAll("’", "'")
|
|
85
|
-
if (form !== words[index] && !sentenceStart(
|
|
86
|
+
if (this.grammar.prose && form !== words[index] && !sentenceStart(masked, start)) increment(this.forms, form)
|
|
86
87
|
if (index > 0) increment(this.bigrams, `${words[index - 1]}\0${words[index]}`)
|
|
87
88
|
if (index > 1) increment(this.trigrams, `${words[index - 2]}\0${words[index - 1]}\0${words[index]}`)
|
|
88
89
|
}
|
|
@@ -114,13 +115,16 @@ export class PersonalModel {
|
|
|
114
115
|
}
|
|
115
116
|
}
|
|
116
117
|
|
|
117
|
-
|
|
118
|
-
|
|
118
|
+
type Totals = { total: number; types: number; max: number }
|
|
119
|
+
|
|
120
|
+
function totals(counts: Map<string, number>): Map<string, Totals> {
|
|
121
|
+
const result = new Map<string, Totals>()
|
|
119
122
|
for (const [key, count] of counts) {
|
|
120
123
|
const context = key.slice(0, key.lastIndexOf("\0"))
|
|
121
|
-
const entry = result.get(context) ?? { total: 0, types: 0 }
|
|
124
|
+
const entry = result.get(context) ?? { total: 0, types: 0, max: 0 }
|
|
122
125
|
entry.total += count
|
|
123
126
|
entry.types++
|
|
127
|
+
entry.max = Math.max(entry.max, count)
|
|
124
128
|
result.set(context, entry)
|
|
125
129
|
}
|
|
126
130
|
return result
|
|
@@ -205,15 +209,15 @@ export class WordPredictor {
|
|
|
205
209
|
private priorTotal = 0
|
|
206
210
|
private personal = new PersonalModel()
|
|
207
211
|
private personalTotal = 0
|
|
208
|
-
private bigramTotals = new Map<string,
|
|
209
|
-
private trigramTotals = new Map<string,
|
|
212
|
+
private bigramTotals = new Map<string, Totals>()
|
|
213
|
+
private trigramTotals = new Map<string, Totals>()
|
|
210
214
|
private vocabulary: string[] = []
|
|
211
215
|
private forms = new Map<string, string>()
|
|
212
216
|
|
|
213
|
-
constructor(prior: readonly Frequency[]) {
|
|
217
|
+
constructor(prior: readonly Frequency[], readonly grammar: Grammar = proseGrammar) {
|
|
214
218
|
for (const { word, count } of prior) {
|
|
215
|
-
const key =
|
|
216
|
-
if (!isWord(key) || !Number.isFinite(count) || count <= 0) continue
|
|
219
|
+
const key = grammar.normalize(word)
|
|
220
|
+
if (!grammar.isWord(key) || !Number.isFinite(count) || count <= 0) continue
|
|
217
221
|
this.prior.set(key, (this.prior.get(key) ?? 0) + count)
|
|
218
222
|
this.priorTotal += count
|
|
219
223
|
if (this.prior.size >= PRIOR_LIMIT) break
|
|
@@ -223,7 +227,7 @@ export class WordPredictor {
|
|
|
223
227
|
|
|
224
228
|
setPersonal(snapshot: Snapshot): void {
|
|
225
229
|
this.revision++
|
|
226
|
-
this.personal = new PersonalModel(snapshot)
|
|
230
|
+
this.personal = new PersonalModel(snapshot, this.grammar)
|
|
227
231
|
this.personalTotal = [...this.personal.words.values()].reduce((sum, count) => sum + count, 0)
|
|
228
232
|
this.bigramTotals = totals(this.personal.bigrams)
|
|
229
233
|
this.trigramTotals = totals(this.personal.trigrams)
|
|
@@ -234,7 +238,7 @@ export class WordPredictor {
|
|
|
234
238
|
const word = learned[index]
|
|
235
239
|
if (this.prior.has(word)) continue
|
|
236
240
|
for (let next = index + 1; next < learned.length && learned[next].startsWith(word); next++) {
|
|
237
|
-
if (learned[next][word.length]
|
|
241
|
+
if (!"/-.".includes(learned[next][word.length]) && counts.get(learned[next])! >= counts.get(word)!) {
|
|
238
242
|
fragments.add(word)
|
|
239
243
|
break
|
|
240
244
|
}
|
|
@@ -243,7 +247,7 @@ export class WordPredictor {
|
|
|
243
247
|
this.vocabulary = [...new Set([...this.prior.keys(), ...learned.filter((word) => !fragments.has(word))])].sort()
|
|
244
248
|
const forms = new Map<string, [string, number]>()
|
|
245
249
|
for (const [form, count] of this.personal.forms) {
|
|
246
|
-
const word =
|
|
250
|
+
const word = this.grammar.normalize(form)
|
|
247
251
|
if ((forms.get(word)?.[1] ?? 0) < count) forms.set(word, [form, count])
|
|
248
252
|
}
|
|
249
253
|
this.forms = new Map([...forms].filter(([word, [, count]]) => count * 2 > (counts.get(word) ?? 0)).map(([word, [form]]) => [word, form]))
|
|
@@ -278,12 +282,14 @@ export class WordPredictor {
|
|
|
278
282
|
const trigram = pair && this.trigramTotals.get(pair)
|
|
279
283
|
if (trigram && trigram.total >= 2) {
|
|
280
284
|
const count = this.personal.trigrams.get(`${pair}\0${word}`) ?? 0
|
|
281
|
-
|
|
285
|
+
const discounted = Math.max(count - DISCOUNT, 0) / trigram.total + DISCOUNT * trigram.types / trigram.total * score
|
|
286
|
+
score = trigram.max >= 2 ? discounted : Math.max(score, discounted)
|
|
282
287
|
}
|
|
283
288
|
return score
|
|
284
289
|
}
|
|
285
290
|
|
|
286
291
|
private resolveContext(raw: readonly string[], local: ReadonlyMap<string, number>): string[] {
|
|
292
|
+
if (!this.grammar.prose) return [...raw]
|
|
287
293
|
const resolved: string[] = []
|
|
288
294
|
for (const word of raw) {
|
|
289
295
|
if (this.prior.has(word) || (this.personal.words.get(word) ?? 0) >= 2 || (local.get(word) ?? 0) >= 2 || word.length < 3) {
|
|
@@ -316,8 +322,8 @@ export class WordPredictor {
|
|
|
316
322
|
candidates(query: CompletionQuery, limit = 5): Prediction[] {
|
|
317
323
|
const maximum = Number.isFinite(limit) ? Math.max(0, Math.min(5, Math.floor(limit))) : 5
|
|
318
324
|
if (!maximum) return []
|
|
319
|
-
const prefix =
|
|
320
|
-
const words = query.words ?? proseWords(query.before)
|
|
325
|
+
const prefix = this.grammar.normalize(query.prefix)
|
|
326
|
+
const words = query.words ?? (this.grammar.prose ? proseWords(query.before) : [])
|
|
321
327
|
const local = new Map<string, number>()
|
|
322
328
|
for (const word of words) increment(local, word.text)
|
|
323
329
|
const context = this.resolveContext(leftContext(query.before, words), local)
|
|
@@ -327,15 +333,16 @@ export class WordPredictor {
|
|
|
327
333
|
if (query.next && evidence < 2) return []
|
|
328
334
|
if (!query.next && [...prefix].length < 2 && evidence < 2) return []
|
|
329
335
|
const slash = prefix.includes("/")
|
|
336
|
+
const followed = (word: string) => (previous ? this.personal.bigrams.get(`${previous}\0${word}`) ?? 0 : 0) >= 2 ||
|
|
337
|
+
(pair ? this.personal.trigrams.get(`${pair}\0${word}`) ?? 0 : 0) >= 2
|
|
338
|
+
const eligible = (word: string) => !query.next || followed(word)
|
|
330
339
|
const candidates = new Map<string, number>()
|
|
331
340
|
for (let index = lowerBound(this.vocabulary, prefix); index < this.vocabulary.length; index++) {
|
|
332
341
|
const word = this.vocabulary[index]
|
|
333
342
|
if (!word.startsWith(prefix)) break
|
|
334
|
-
if (query.next || slash === word.includes("/")) candidates.set(word, 1)
|
|
343
|
+
if ((query.next || slash === word.includes("/")) && eligible(word)) candidates.set(word, 1)
|
|
335
344
|
}
|
|
336
|
-
for (const word of local.keys()) if (!word.includes("/") && word.startsWith(prefix) && (query.next || !slash)) candidates.set(word, 1)
|
|
337
|
-
const followed = (word: string) => (previous ? this.personal.bigrams.get(`${previous}\0${word}`) ?? 0 : 0) >= 2 ||
|
|
338
|
-
(pair ? this.personal.trigrams.get(`${pair}\0${word}`) ?? 0 : 0) >= 2
|
|
345
|
+
for (const word of local.keys()) if (!word.includes("/") && word.startsWith(prefix) && (query.next || !slash) && eligible(word)) candidates.set(word, 1)
|
|
339
346
|
const suggest = (): Prediction[] => {
|
|
340
347
|
const ranked: { word: string; score: number; weight: number }[] = []
|
|
341
348
|
let sum = 0
|
|
@@ -350,17 +357,17 @@ export class WordPredictor {
|
|
|
350
357
|
const predictions: Prediction[] = []
|
|
351
358
|
for (const { word: best, score: bestScore, weight: bestWeight } of ranked) {
|
|
352
359
|
const confidence = bestWeight < 1 ? typoConfidence(bestScore, sum) : query.next ? bestScore : bestScore / (sum || 1)
|
|
353
|
-
if (!bestScore || best === prefix || confidence === undefined || (
|
|
360
|
+
if (!bestScore || best === prefix || confidence === undefined || (bestWeight === 1 && confidence < 0.3)) {
|
|
354
361
|
if (!predictions.length) return []
|
|
355
362
|
continue
|
|
356
363
|
}
|
|
357
364
|
const form = this.forms.get(best) ?? best
|
|
358
|
-
const shouting = query.prefix.length > 1 && query.prefix === query.prefix.toUpperCase()
|
|
365
|
+
const shouting = this.grammar.prose && query.prefix.length > 1 && query.prefix === query.prefix.toUpperCase()
|
|
359
366
|
if (bestWeight < 1 || (!query.next && best.startsWith("i'") && query.prefix[0] === "i") ||
|
|
360
367
|
(!query.next && !shouting && form !== best && !form.startsWith(query.prefix))) {
|
|
361
368
|
predictions.push({ suffix: applyCase(query.prefix, form), word: best, confidence, replace: query.prefix.length })
|
|
362
369
|
} else if (query.next) {
|
|
363
|
-
predictions.push({ suffix: applyCase("", form), word: best, confidence })
|
|
370
|
+
predictions.push({ suffix: this.grammar.prose ? applyCase("", form) : form, word: best, confidence })
|
|
364
371
|
} else {
|
|
365
372
|
const suffix = form.slice(prefix.length)
|
|
366
373
|
predictions.push({ suffix: shouting ? suffix.toUpperCase() : suffix, word: best, confidence })
|
|
@@ -369,7 +376,7 @@ export class WordPredictor {
|
|
|
369
376
|
return predictions
|
|
370
377
|
}
|
|
371
378
|
const completion = suggest()
|
|
372
|
-
if (completion.length || query.next || prefix.length < 3 || slash || candidates.has(prefix)) return completion
|
|
379
|
+
if (completion.length || query.next || prefix.length < 3 || slash || candidates.has(prefix) || !this.grammar.prose) return completion
|
|
373
380
|
for (const word of this.nearbyWords(prefix)) {
|
|
374
381
|
if (candidates.has(word)) continue
|
|
375
382
|
const weight = typoWeight(prefix, word)
|
package/src/prose.ts
CHANGED
|
@@ -1,11 +1,30 @@
|
|
|
1
1
|
const PART = "[\\p{L}\\p{M}]+(?:['’][\\p{L}\\p{M}]+)*"
|
|
2
|
-
const
|
|
3
|
-
const
|
|
4
|
-
const
|
|
5
|
-
const
|
|
2
|
+
const HYPHENATED = `${PART}(?:-${PART})*`
|
|
3
|
+
const EXTENSION = "(?:sh|md|json|jsonc|ts|tsx|js|jsx|mjs|cjs|yml|yaml|toml|lock|html|css|py|txt|rs|go|sql)"
|
|
4
|
+
const FILE = `${HYPHENATED}\\.${EXTENSION}`
|
|
5
|
+
const PREFIX = `(?:${FILE}|${HYPHENATED}-?(?:\\/(?:${HYPHENATED}-?)?)?)`
|
|
6
|
+
const WORD = new RegExp(`(?:${FILE}(?![\\p{L}\\p{M}\\p{N}])|${HYPHENATED}(?:\\/${HYPHENATED})?)`, "gu")
|
|
7
|
+
const WHOLE_WORD = new RegExp(`^(?:${FILE}|${HYPHENATED}(?:\\/${HYPHENATED})?)$`, "u")
|
|
8
|
+
const WORD_PREFIX = new RegExp(`^${PREFIX}$`, "u")
|
|
9
|
+
const WORD_END = new RegExp(`${PREFIX}$`, "u")
|
|
10
|
+
const FILE_NAME = new RegExp(`^${FILE}$`, "u")
|
|
11
|
+
const BRAND = /^(?:\p{Lu}\p{Ll}+(?:\p{Lu}\p{Ll}+|\p{Lu}{2,})|\p{Ll}\p{Lu}\p{Ll}+|macOS|iOS|iPadOS|tvOS|watchOS|visionOS)$/u
|
|
12
|
+
const LIST_MARKER = /^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]/
|
|
13
|
+
const INDENTED = /^(?: {4}| {0,3}\t)/
|
|
6
14
|
|
|
7
15
|
export type Word = { text: string; start: number; end: number }
|
|
8
16
|
export type CompletionQuery = { before: string; prefix: string; next: boolean; words?: readonly Word[] }
|
|
17
|
+
export type Grammar = {
|
|
18
|
+
prose: boolean
|
|
19
|
+
normalize(word: string): string
|
|
20
|
+
isWord(word: string): boolean
|
|
21
|
+
isPrefix(prefix: string): boolean
|
|
22
|
+
mask(text: string): string
|
|
23
|
+
words(text: string, masked?: string): Word[]
|
|
24
|
+
sequences(text: string): Word[][]
|
|
25
|
+
wordEnd: RegExp
|
|
26
|
+
boundary: RegExp
|
|
27
|
+
}
|
|
9
28
|
|
|
10
29
|
export function normalizeWord(word: string): string {
|
|
11
30
|
return word.normalize("NFC").replaceAll("’", "'").toLowerCase()
|
|
@@ -19,10 +38,14 @@ function isPrefix(prefix: string): boolean {
|
|
|
19
38
|
return WORD_PREFIX.test(prefix) && [...prefix].length <= 32
|
|
20
39
|
}
|
|
21
40
|
|
|
22
|
-
function blank(text: string): string {
|
|
41
|
+
export function blank(text: string): string {
|
|
23
42
|
return text.replace(/[^\n]/g, " ")
|
|
24
43
|
}
|
|
25
44
|
|
|
45
|
+
function brandOrPlain(segment: string): boolean {
|
|
46
|
+
return !/[\p{Ll}][\p{Lu}]/u.test(segment) || BRAND.test(segment.replace(/['’]s$/, ""))
|
|
47
|
+
}
|
|
48
|
+
|
|
26
49
|
export function maskProse(text: string): string {
|
|
27
50
|
let fence: string | undefined
|
|
28
51
|
let masked = text.replace(/[^\n]+/g, (line) => {
|
|
@@ -41,12 +64,23 @@ export function maskProse(text: string): string {
|
|
|
41
64
|
masked = masked.replace(/(`+)[\s\S]*?(?:\1|$)/g, blank)
|
|
42
65
|
masked = masked.replace(/(?:https?:\/\/|www\.)\S+|\[[^\]\n]*\]\([^\)\n]*\)|<[^>\n]+>/g, blank)
|
|
43
66
|
masked = masked.replace(/^[ \t]*(?:[!$]|(?:const|let|var|function|class|import|export)\s|(?:Traceback|Error:)\b).*$/gm, blank)
|
|
44
|
-
|
|
67
|
+
let list = false
|
|
68
|
+
masked = masked.replace(/[^\n]+/g, (line) => {
|
|
69
|
+
if (!line.trim()) return line
|
|
70
|
+
if (!INDENTED.test(line)) {
|
|
71
|
+
list = LIST_MARKER.test(line)
|
|
72
|
+
return line
|
|
73
|
+
}
|
|
74
|
+
return list ? line : blank(line)
|
|
75
|
+
})
|
|
45
76
|
masked = masked.replace(/\S+/g, (token) => {
|
|
46
77
|
const core = token.replace(/^["“‘([{]+|["”’),;:!?}\]]+$/g, "")
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
if (/[
|
|
78
|
+
const bare = core.endsWith(".") ? core.slice(0, -1) : core
|
|
79
|
+
const named = FILE_NAME.test(bare)
|
|
80
|
+
if (/[_@=\\<>]|\d/.test(core) || /^[.~]/.test(core) || !bare.split(/[-/]/).every(brandOrPlain)) return blank(token)
|
|
81
|
+
if (core.includes("-") && !WORD_PREFIX.test(bare)) return blank(token)
|
|
82
|
+
if (core.includes("/") && !(core.endsWith(".") ? WHOLE_WORD.test(bare) : WORD_PREFIX.test(core))) return blank(token)
|
|
83
|
+
if (!named && /[^.]+\.[^.]+|\.\.|--/.test(core)) return blank(token)
|
|
50
84
|
return token
|
|
51
85
|
})
|
|
52
86
|
return masked
|
|
@@ -54,12 +88,11 @@ export function maskProse(text: string): string {
|
|
|
54
88
|
|
|
55
89
|
export function proseWords(text: string, masked = maskProse(text)): Word[] {
|
|
56
90
|
return [...masked.matchAll(WORD)]
|
|
57
|
-
.filter((match) => isWord(match[0]) && masked[match.index + match[0].length]
|
|
91
|
+
.filter((match) => isWord(match[0]) && !/[/-]/.test(masked[match.index + match[0].length] ?? ""))
|
|
58
92
|
.map((match) => ({ text: normalizeWord(match[0]), start: match.index, end: match.index + match[0].length }))
|
|
59
93
|
}
|
|
60
94
|
|
|
61
|
-
export function
|
|
62
|
-
const words = proseWords(text)
|
|
95
|
+
export function wordSequences(text: string, words: readonly Word[]): Word[][] {
|
|
63
96
|
const sequences: Word[][] = []
|
|
64
97
|
let previous = -1
|
|
65
98
|
for (const word of words) {
|
|
@@ -70,6 +103,22 @@ export function proseSequences(text: string): Word[][] {
|
|
|
70
103
|
return sequences
|
|
71
104
|
}
|
|
72
105
|
|
|
106
|
+
export function proseSequences(text: string): Word[][] {
|
|
107
|
+
return wordSequences(text, proseWords(text))
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export const proseGrammar: Grammar = {
|
|
111
|
+
prose: true,
|
|
112
|
+
normalize: normalizeWord,
|
|
113
|
+
isWord,
|
|
114
|
+
isPrefix,
|
|
115
|
+
mask: maskProse,
|
|
116
|
+
words: proseWords,
|
|
117
|
+
sequences: proseSequences,
|
|
118
|
+
wordEnd: WORD_END,
|
|
119
|
+
boundary: /[ \t\n"“([{]/,
|
|
120
|
+
}
|
|
121
|
+
|
|
73
122
|
export function leftContext(before: string, words: readonly Word[] = proseWords(before)): string[] {
|
|
74
123
|
const result: string[] = []
|
|
75
124
|
let end = before.length
|
|
@@ -92,23 +141,23 @@ function blankRanges(text: string, ranges: readonly TextRange[]): string {
|
|
|
92
141
|
return result
|
|
93
142
|
}
|
|
94
143
|
|
|
95
|
-
export function completionQuery(draft: string, characterOffset: number, protectedRanges: readonly TextRange[] = [], completeAtLineEnd = false): CompletionQuery | undefined {
|
|
144
|
+
export function completionQuery(draft: string, characterOffset: number, protectedRanges: readonly TextRange[] = [], completeAtLineEnd = false, grammar: Grammar = proseGrammar): CompletionQuery | undefined {
|
|
96
145
|
if (!draft.trim() || draft.length > 16_000 || characterOffset < 0 || characterOffset > draft.length ||
|
|
97
146
|
(characterOffset !== draft.length && (!completeAtLineEnd || draft[characterOffset] !== "\n"))) return
|
|
98
|
-
const masked =
|
|
147
|
+
const masked = grammar.mask(protectedRanges.length ? blankRanges(draft, protectedRanges) : draft).slice(0, characterOffset)
|
|
99
148
|
const text = draft.slice(0, characterOffset)
|
|
100
|
-
const prefix =
|
|
149
|
+
const prefix = grammar.wordEnd.exec(text)?.[0]
|
|
101
150
|
let end = text.length
|
|
102
151
|
if (prefix) {
|
|
103
152
|
const start = text.length - prefix.length
|
|
104
|
-
if (masked.slice(start) !== prefix || !isPrefix(prefix)) return
|
|
153
|
+
if (masked.slice(start) !== prefix || !grammar.isPrefix(prefix)) return
|
|
105
154
|
const preceding = text[start - 1]
|
|
106
|
-
if (preceding &&
|
|
155
|
+
if (preceding && !grammar.boundary.test(preceding)) return
|
|
107
156
|
end = start
|
|
108
157
|
} else if (!/[ \t]$/.test(text)) return
|
|
109
158
|
const start = Math.max(0, end - 2000)
|
|
110
159
|
const before = text.slice(start, end)
|
|
111
|
-
const words =
|
|
160
|
+
const words = grammar.words(before, masked.slice(start, end))
|
|
112
161
|
if (!prefix && !leftContext(before, words).length) return
|
|
113
162
|
return { before, prefix: prefix ?? "", next: !prefix, words }
|
|
114
163
|
}
|
package/src/shell.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { blank, wordSequences, type Grammar, type Word } from "./prose"
|
|
2
|
+
|
|
3
|
+
const NAME = "-{0,2}[A-Za-z][A-Za-z0-9._+:-]*"
|
|
4
|
+
const PIECE = new RegExp(`^(?:-{1,2}|${NAME})$`)
|
|
5
|
+
const WORD = /-{0,2}[A-Za-z](?:[A-Za-z0-9._+:-]*[A-Za-z0-9])?/g
|
|
6
|
+
const WHOLE_WORD = /^-{0,2}[A-Za-z](?:[A-Za-z0-9._+:-]*[A-Za-z0-9])?$/
|
|
7
|
+
const OPERATORS = /[|;&<>()]+/
|
|
8
|
+
const SECRET = /token|secret|passw|bearer|authorization|api[-_]?key|credential|private[-_]?key|\bsk-/i
|
|
9
|
+
const QUOTED = /"(?:[^"\\\n]|\\.)*"?|'[^'\n]*'?|`[^`\n]*`?|\$\{[^}\n]*\}?|\$\([^)\n]*\)?|\$[\w@#?*!$-]*/g
|
|
10
|
+
|
|
11
|
+
function plausible(piece: string): boolean {
|
|
12
|
+
return !piece || (PIECE.test(piece) && !(piece.length >= 16 && /\d/.test(piece)))
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function maskShell(text: string): string {
|
|
16
|
+
if (SECRET.test(text)) return blank(text)
|
|
17
|
+
return text.replace(QUOTED, blank).replace(/\S+/g, (token) => token.split(OPERATORS).every(plausible) ? token : blank(token))
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function shellWords(text: string, masked = maskShell(text)): Word[] {
|
|
21
|
+
return [...masked.matchAll(WORD)]
|
|
22
|
+
.filter((match) => WHOLE_WORD.test(match[0]) && match[0].length <= 32 && !/[._+:-]/.test(masked[match.index + match[0].length] ?? ""))
|
|
23
|
+
.map((match) => ({ text: match[0], start: match.index, end: match.index + match[0].length }))
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export const shellGrammar: Grammar = {
|
|
27
|
+
prose: false,
|
|
28
|
+
normalize: (word) => word,
|
|
29
|
+
isWord: (word) => WHOLE_WORD.test(word) && word.length <= 32,
|
|
30
|
+
isPrefix: (prefix) => PIECE.test(prefix) && prefix.length <= 32,
|
|
31
|
+
mask: maskShell,
|
|
32
|
+
words: shellWords,
|
|
33
|
+
sequences: (text) => wordSequences(text, shellWords(text)),
|
|
34
|
+
wordEnd: new RegExp(`(?:-{1,2}|${NAME})$`),
|
|
35
|
+
boundary: /[ \t\n|;&(]/,
|
|
36
|
+
}
|
package/src/tui.tsx
CHANGED
|
@@ -4,23 +4,29 @@ import { InputRenderable, TextareaRenderable, type BoxRenderable } from "@opentu
|
|
|
4
4
|
import { createEffect, createRoot, createSignal, onCleanup, untrack } from "solid-js"
|
|
5
5
|
import { unwrap } from "solid-js/store"
|
|
6
6
|
import frequencies from "subtlex-word-frequencies"
|
|
7
|
+
import { proseGrammar, type Grammar } from "./prose"
|
|
7
8
|
import { ComposerGhost, dimGhostColor, findComposer } from "./ghost"
|
|
8
9
|
import { completionLayer } from "./keymap"
|
|
9
10
|
import { parseQuillCommand, resolveOptions } from "./options"
|
|
10
11
|
import { emptySnapshot, PersonalModel, WordPredictor } from "./predictor"
|
|
12
|
+
import { shellGrammar } from "./shell"
|
|
11
13
|
|
|
12
14
|
export default Plugin.define({
|
|
13
15
|
id: "quill",
|
|
14
16
|
setup(context) {
|
|
15
17
|
const options = resolveOptions(context.options)
|
|
16
18
|
const [settings, setSettings] = context.storage.store("settings", {
|
|
17
|
-
initial: { enabled: options.enabled },
|
|
19
|
+
initial: { enabled: options.enabled, shell: options.completeShell },
|
|
18
20
|
})
|
|
19
21
|
const [learning, setLearning] = context.storage.store("learning", {
|
|
20
22
|
initial: { snapshot: emptySnapshot() },
|
|
21
23
|
})
|
|
24
|
+
const [shellLearning, setShellLearning] = context.storage.store("shell", {
|
|
25
|
+
initial: { snapshot: emptySnapshot() },
|
|
26
|
+
})
|
|
22
27
|
const predictor = new WordPredictor(frequencies)
|
|
23
|
-
const
|
|
28
|
+
const shellPredictor = new WordPredictor([], shellGrammar)
|
|
29
|
+
const composers = new Map<string, { marker: BoxRenderable; mode: () => "normal" | "shell" }>()
|
|
24
30
|
const seeded = new Set<string>()
|
|
25
31
|
const inFlight = new Map<string, { pending: boolean; announce: boolean }>()
|
|
26
32
|
const [revision, setRevision] = createSignal(0)
|
|
@@ -29,6 +35,8 @@ export default Plugin.define({
|
|
|
29
35
|
let warned = false
|
|
30
36
|
let resetVersion = 0
|
|
31
37
|
|
|
38
|
+
const shellEnabled = () => settings.shell !== false
|
|
39
|
+
|
|
32
40
|
const routeKey = () => {
|
|
33
41
|
const route = context.ui.router.current()
|
|
34
42
|
return route.type === "home" ? "home" : route.type === "session" ? route.sessionID : undefined
|
|
@@ -47,15 +55,17 @@ export default Plugin.define({
|
|
|
47
55
|
ghost?.dispose()
|
|
48
56
|
ghost = editor && new ComposerGhost(editor, predictor, () => {
|
|
49
57
|
const key = routeKey()
|
|
58
|
+
const shell = !!key && composers.get(key)?.mode() === "shell"
|
|
50
59
|
return {
|
|
51
60
|
editor,
|
|
52
|
-
normal: !!key && composers.
|
|
61
|
+
normal: !!key && composers.has(key),
|
|
53
62
|
focused: context.renderer.currentFocusedEditor,
|
|
54
63
|
mode: context.keymap.mode.current(),
|
|
64
|
+
shell,
|
|
55
65
|
selected: context.renderer.hasSelection,
|
|
56
|
-
enabled: !disposed && settings.enabled && currentEditor() === editor,
|
|
66
|
+
enabled: !disposed && settings.enabled && (!shell || shellEnabled()) && currentEditor() === editor,
|
|
57
67
|
}
|
|
58
|
-
}, () => dimGhostColor(context.theme.text.muted), context.renderer, options.completeAtLineEnd)
|
|
68
|
+
}, () => dimGhostColor(context.theme.text.muted), context.renderer, options.completeAtLineEnd, shellPredictor)
|
|
59
69
|
}
|
|
60
70
|
|
|
61
71
|
const sessionInfo = (sessionID: string) =>
|
|
@@ -85,27 +95,34 @@ export default Plugin.define({
|
|
|
85
95
|
if (disposed || !settings.enabled) return
|
|
86
96
|
if (sessionInfo(sessionID)?.parentID) return
|
|
87
97
|
if (version !== resetVersion) continue
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
if (model.observe(prompts)) {
|
|
101
|
-
await setLearning((draft) => {
|
|
98
|
+
const messages = context.data.session.message.list(sessionID)
|
|
99
|
+
const absorb = async (store: typeof learning, update: typeof setLearning, grammar: Grammar, candidates: { id: string; text: string; created?: number }[]) => {
|
|
100
|
+
const promptsFor = (clearedAt: number | undefined) => candidates
|
|
101
|
+
.filter((prompt) => clearedAt === undefined || (prompt.created !== undefined && prompt.created >= clearedAt))
|
|
102
|
+
.map(({ id, text }) => ({ id, text }))
|
|
103
|
+
const snapshot = unwrap(store.snapshot)
|
|
104
|
+
const seen = new Set(snapshot.seen)
|
|
105
|
+
const prompts = promptsFor(snapshot.clearedAt)
|
|
106
|
+
if (!prompts.some((prompt) => !seen.has(prompt.id))) return
|
|
107
|
+
const model = new PersonalModel(snapshot, grammar)
|
|
108
|
+
if (!model.observe(prompts)) return
|
|
109
|
+
await update((draft) => {
|
|
102
110
|
if (disposed || !settings.enabled || version !== resetVersion) return
|
|
103
111
|
const session = sessionInfo(sessionID)
|
|
104
112
|
if (!session || session.parentID) return
|
|
105
|
-
const latest = new PersonalModel(unwrap(draft.snapshot))
|
|
113
|
+
const latest = new PersonalModel(unwrap(draft.snapshot), grammar)
|
|
106
114
|
if (latest.observe(promptsFor(latest.clearedAt))) draft.snapshot = latest.snapshot()
|
|
107
115
|
})
|
|
108
116
|
}
|
|
117
|
+
await absorb(learning, setLearning, proseGrammar, messages
|
|
118
|
+
.filter((message) => message.type === "user")
|
|
119
|
+
.slice(-200)
|
|
120
|
+
.map((message) => ({ id: `${sessionID}:${message.id}`, text: message.text, created: message.time?.created })))
|
|
121
|
+
if (shellEnabled()) {
|
|
122
|
+
await absorb(shellLearning, setShellLearning, shellGrammar, messages
|
|
123
|
+
.flatMap((message) => message.type === "shell" ? [{ id: `${sessionID}:${message.id}`, text: message.command, created: message.time.created }] : [])
|
|
124
|
+
.slice(-200))
|
|
125
|
+
}
|
|
109
126
|
} catch (error) {
|
|
110
127
|
if (shouldAnnounce && !disposed && version === resetVersion && !warned) {
|
|
111
128
|
warned = true
|
|
@@ -126,11 +143,21 @@ export default Plugin.define({
|
|
|
126
143
|
}
|
|
127
144
|
const cleared = { ...emptySnapshot(), clearedAt: Date.now() }
|
|
128
145
|
predictor.setPersonal(cleared)
|
|
146
|
+
shellPredictor.setPersonal(cleared)
|
|
129
147
|
await setLearning((draft) => { draft.snapshot = cleared })
|
|
148
|
+
await setShellLearning((draft) => { draft.snapshot = cleared })
|
|
130
149
|
ghost?.invalidate()
|
|
131
150
|
context.ui.toast.show({ title: "Quill", message: "Word autocomplete history cleared" })
|
|
132
151
|
}
|
|
133
152
|
|
|
153
|
+
const clearCasing = async () => {
|
|
154
|
+
const next = { ...unwrap(learning.snapshot), forms: [] }
|
|
155
|
+
predictor.setPersonal(next)
|
|
156
|
+
await setLearning((draft) => { draft.snapshot = { ...unwrap(draft.snapshot), forms: [] } })
|
|
157
|
+
ghost?.invalidate()
|
|
158
|
+
context.ui.toast.show({ title: "Quill", message: "Learned word casing cleared" })
|
|
159
|
+
}
|
|
160
|
+
|
|
134
161
|
const disposeEffects = createRoot((dispose) => {
|
|
135
162
|
createEffect(() => {
|
|
136
163
|
const snapshot = learning.snapshot
|
|
@@ -139,10 +166,18 @@ export default Plugin.define({
|
|
|
139
166
|
predictor.setPersonal(unwrap(snapshot))
|
|
140
167
|
ghost?.invalidate()
|
|
141
168
|
})
|
|
169
|
+
createEffect(() => {
|
|
170
|
+
const snapshot = shellLearning.snapshot
|
|
171
|
+
snapshot.seen.length
|
|
172
|
+
snapshot.seen.at(-1)
|
|
173
|
+
shellPredictor.setPersonal(unwrap(snapshot))
|
|
174
|
+
ghost?.invalidate()
|
|
175
|
+
})
|
|
142
176
|
createEffect(() => {
|
|
143
177
|
revision()
|
|
144
178
|
routeKey()
|
|
145
179
|
settings.enabled
|
|
180
|
+
settings.shell
|
|
146
181
|
context.keymap.mode.current()
|
|
147
182
|
syncEditor()
|
|
148
183
|
ghost?.invalidate()
|
|
@@ -184,8 +219,18 @@ export default Plugin.define({
|
|
|
184
219
|
await clearHistory()
|
|
185
220
|
return
|
|
186
221
|
}
|
|
222
|
+
if (command.type === "casing") {
|
|
223
|
+
await clearCasing()
|
|
224
|
+
return
|
|
225
|
+
}
|
|
226
|
+
if (command.type === "shell") {
|
|
227
|
+
await setSettings((draft) => { draft.shell = command.value })
|
|
228
|
+
ghost?.invalidate()
|
|
229
|
+
context.ui.toast.show({ title: "Quill", message: `Shell autocomplete: ${command.value ? "on" : "off"}` })
|
|
230
|
+
return
|
|
231
|
+
}
|
|
187
232
|
if (command.type === "invalid") {
|
|
188
|
-
context.ui.toast.show({ title: "Quill", message: "Use /quill, /quill on, /quill off, or /quill clear", variant: "warning" })
|
|
233
|
+
context.ui.toast.show({ title: "Quill", message: "Use /quill, /quill on, /quill off, /quill shell on, /quill shell off, /quill clear, or /quill clear casing", variant: "warning" })
|
|
189
234
|
return
|
|
190
235
|
}
|
|
191
236
|
const enabled = command.type === "enable" ? command.value : !settings.enabled
|
|
@@ -213,7 +258,7 @@ export default Plugin.define({
|
|
|
213
258
|
const key = input.sessionID ?? "home"
|
|
214
259
|
const node = marker()
|
|
215
260
|
if (!node) return
|
|
216
|
-
composers.set(key, { marker: node,
|
|
261
|
+
composers.set(key, { marker: node, mode: () => input.mode })
|
|
217
262
|
setRevision((value) => value + 1)
|
|
218
263
|
onCleanup(() => {
|
|
219
264
|
if (composers.get(key)?.marker !== node) return
|