grayling 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.
Files changed (55) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +268 -2
  3. package/dist/index.d.ts +290 -0
  4. package/dist/index.js +50 -0
  5. package/dist/node/archive.d.ts +4 -0
  6. package/dist/node/archive.js +115 -0
  7. package/dist/node/client.d.ts +188 -0
  8. package/dist/node/client.js +669 -0
  9. package/dist/node/connection.d.ts +56 -0
  10. package/dist/node/connection.js +240 -0
  11. package/dist/node/errors.d.ts +14 -0
  12. package/dist/node/errors.js +13 -0
  13. package/dist/node/handler.d.ts +56 -0
  14. package/dist/node/handler.js +208 -0
  15. package/dist/node/index.d.ts +15 -0
  16. package/dist/node/index.js +14 -0
  17. package/dist/node/paths.d.ts +51 -0
  18. package/dist/node/paths.js +115 -0
  19. package/dist/node/program.d.ts +74 -0
  20. package/dist/node/program.js +385 -0
  21. package/dist/node/state.d.ts +7 -0
  22. package/dist/node/state.js +12 -0
  23. package/dist/node/suggest.d.ts +13 -0
  24. package/dist/node/suggest.js +87 -0
  25. package/dist/node/types.d.ts +142 -0
  26. package/dist/node/types.js +13 -0
  27. package/dist/node/version.d.ts +10 -0
  28. package/dist/node/version.js +50 -0
  29. package/dist/node/wire.d.ts +32 -0
  30. package/dist/node/wire.js +44 -0
  31. package/dist/react/index.d.ts +121 -0
  32. package/dist/react/index.js +205 -0
  33. package/dist/web/announce.d.ts +51 -0
  34. package/dist/web/announce.js +141 -0
  35. package/dist/web/attach.d.ts +77 -0
  36. package/dist/web/attach.js +89 -0
  37. package/dist/web/box.d.ts +57 -0
  38. package/dist/web/box.js +150 -0
  39. package/dist/web/dom.d.ts +80 -0
  40. package/dist/web/dom.js +265 -0
  41. package/dist/web/index.d.ts +8 -0
  42. package/dist/web/index.js +8 -0
  43. package/dist/web/logic.d.ts +308 -0
  44. package/dist/web/logic.js +467 -0
  45. package/dist/web/overlay.d.ts +56 -0
  46. package/dist/web/overlay.js +211 -0
  47. package/dist/web/style.css +193 -0
  48. package/dist/web/suggester.d.ts +189 -0
  49. package/dist/web/suggester.js +696 -0
  50. package/dist/web/ui.d.ts +65 -0
  51. package/dist/web/ui.js +32 -0
  52. package/dist/web/usage.d.ts +39 -0
  53. package/dist/web/usage.js +84 -0
  54. package/package.json +89 -4
  55. package/program.json +35 -0
package/README.md CHANGED
@@ -1,3 +1,269 @@
1
- # Temporary Holding Version
1
+ # grayling (npm)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Word suggestions for text boxes. The rest of the word you are typing shows in grey after the caret, and the next word
4
+ a little dimmer. **Tab** takes it, **→** at the end takes it and the next word, **Esc** hides it. Inside a text, the
5
+ word shows on a small chip over the caret. A word typed wrong gets a mark and a chip with the right one.
6
+
7
+ This package is the text-box part: the code that draws and handles the keys. It asks an engine for the words
8
+ (the [Grayling](https://github.com/algoprog/grayling) engine, or a server of your own).
9
+
10
+ - `grayling`: the types and limits (`SuggestRequest`, `SuggestResponse`, `SuggestSettings`, …).
11
+ - `grayling/web`: plain JavaScript: `attach(box, options)`, the rules (`Suggester`, `logic`), `UsageBatch`.
12
+ - `grayling/react`: `createSuggest(options)` with `useTextareaSuggest`, and the pieces it draws.
13
+ - `grayling/node`: for a Node server: `connect()` to the Grayling engine on this computer, `handler()` for the text box's POSTs, `findProgram()` and `installProgram()`.
14
+ - `grayling/web/style.css`: the default look.
15
+
16
+ No runtime dependencies. React is optional (18 or newer). `grayling` and `grayling/web` load in Node without a DOM; `grayling/node` needs Node 20 or newer.
17
+
18
+ ## Install
19
+
20
+ ```sh
21
+ npm install grayling
22
+ ```
23
+
24
+ ## Plain JavaScript
25
+
26
+ ```js
27
+ import { attach } from 'grayling/web';
28
+ import 'grayling/web/style.css'; // or import it with a <link>
29
+
30
+ const textarea = document.querySelector('textarea');
31
+ const { detach } = attach(textarea, { url: '/api/suggest' });
32
+ // later: detach();
33
+ ```
34
+
35
+ `attach` works on a `<textarea>` and on an `<input type="text">`. It draws a layer over the box that has the box's own font
36
+ and wrapping, so the grey words sit exactly after the caret. Chips are added to the page's `<body>`.
37
+ `detach()` takes everything away again: the listeners, the layers, the chips and the class.
38
+
39
+ Options (all optional, but you need `url` or `send`):
40
+
41
+ | Option | What it does |
42
+ |---|---|
43
+ | `url` | A POST endpoint. It takes a `SuggestRequest` as JSON and answers a `SuggestResponse`, or `204` for nothing. `headers` and `credentials` go with it. |
44
+ | `send(req, signal)` | Your own way to get an answer (instead of `url`). Return a `SuggestResponse` or `null`. `signal` aborts when the answer is no longer wanted. |
45
+ | `place` | `'other'` (default), `'chat'`, `'docs'` or `'notes'`. Decides what is sent and which switch of `gate` counts. |
46
+ | `context()` | What goes with the text: `{ reply, prev, doc, session }`. Read when a request goes out. |
47
+ | `midText`, `fixTypos`, `enabled` | Simple switches (all on by default): words inside a text, words typed wrong, on or off (a boolean or a function). |
48
+ | `gate()` | Instead of the simple switches: a function that returns a `Gate` (enabled, state, where, midText, fixTypos). `subscribe(cb)` tells the box the switches changed; `refresh()` on the result does the same by hand. |
49
+ | `warm()` | Called when the box gets the focus (start your engine here). |
50
+ | `announce` | Tell a screen reader about a suggestion that has stood for 1.2 s, in a polite live region (default `true`; `false` turns it off). See "Labels and theming". |
51
+ | `labels`, `classes`, `attributes`, `kbd` | Words, class names, extra attributes, and the key element. See "Labels and theming". |
52
+ | `onCount`, `onJudge`, `onKeep` | Counts of what suggestions did, guesses judged by how sure they were, and words kept as typed. Never any text except the kept word. |
53
+
54
+ ## React
55
+
56
+ ```jsx
57
+ import { useRef, useState } from 'react';
58
+ import { createSuggest, newClientId } from 'grayling/react';
59
+ import 'grayling/web/style.css';
60
+
61
+ const { useTextareaSuggest } = createSuggest({
62
+ send: (req, signal) => fetch('/api/suggest', { method: 'POST', body: JSON.stringify(req), signal, headers: { 'content-type': 'application/json' } })
63
+ .then((r) => (r.status === 204 ? null : r.json())),
64
+ gate: () => ({ enabled: true, state: 'ready', where: { chat: true, docs: true, notes: true, other: true }, browser: true, midText: true, fixTypos: true }),
65
+ client: newClientId(),
66
+ });
67
+
68
+ function Note() {
69
+ const ref = useRef(null);
70
+ const [value, setValue] = useState('');
71
+ const sg = useTextareaSuggest(ref, { place: 'notes', value });
72
+ return (
73
+ <div style={{ position: 'relative' }}> {/* the layers are positioned in this box */}
74
+ <textarea ref={ref} value={value} onChange={(e) => setValue(e.target.value)} onKeyDown={(e) => sg.onKeyDown(e)} />
75
+ {sg.overlay}
76
+ </div>
77
+ );
78
+ }
79
+ ```
80
+
81
+ `onKeyDown` returns `true` when it took the key (Tab, → or Esc), so your own handling can skip it. `createSuggest` also takes
82
+ `subscribe(cb)` (your switches changed; return what unsubscribes), `warm()`, `count`, `judge` and `keep`, and gives back
83
+ `makeSuggester(adapter, onView)` for a box that is not a plain textarea (an editor: write the adapter, draw the view) and the chips with
84
+ your look already on them (`FixChip`, `MidChip`, for the editor's own view). `icons: { close }` draws the × that keeps a word with
85
+ your icon set instead of the package's. `announce: false` turns the screen reader live region off (below); a box you draw yourself with
86
+ `makeSuggester` can use `Announcer` (`new Announcer(document, { labels })`, `announcer.show(spokenOf(view, before))` whenever the view
87
+ changes, `announcer.listen(box)` for an input method composing, `announcer.destroy()` when the box goes). The pieces `GreyMirror`, `FixChip`, `MidChip` and `Layer` are exported on their own, as are
88
+ `keepBoxClass` and `isOn` in `grayling/web` (the class `grayling-box` for an editor that is not a textarea).
89
+
90
+ ## A server of your own
91
+
92
+ `attach` and `createSuggest` POST a `SuggestRequest` and want a `SuggestResponse` back (both are typed in `grayling`):
93
+
94
+ ```ts
95
+ import type { SuggestRequest, SuggestResponse } from 'grayling';
96
+ // request: { surface: 'text', text: 'Hello wor', client: 't-3fa9…' }
97
+ // response: { word: 'ld', next: ' is', conf: 0.9, confNext: 0.6, show: true, showNext: true, plan: 'mix' }
98
+ ```
99
+
100
+ `text` is what stands before the caret (the last 2,000 characters), `after` is what stands after it on the same line. A response
101
+ with `show: false` shows nothing, but its `conf` still lets `onJudge` learn how often a guess that sure is right. A word typed wrong
102
+ comes back as `fix: { back, typed, word, conf }`. The Grayling engine speaks this too, and `grayling/node` is the shortest way
103
+ to put it behind a route.
104
+
105
+ ### With the Grayling engine (`grayling/node`)
106
+
107
+ One engine runs for each person and computer (it holds a lock, and answers on a local socket only that person may open). Your
108
+ server connects to it; when none runs it starts the `grayling` program, detached, and any other program that uses Grayling on this
109
+ computer shares it.
110
+
111
+ ```js
112
+ import { createServer } from 'node:http';
113
+ import { connect, handler } from 'grayling/node';
114
+
115
+ const grayling = await connect({ client: 'my-app' }); // finds the engine, or starts it
116
+ const suggest = handler(grayling, { allowedHosts: ['localhost:4775'] });
117
+
118
+ createServer((req, res) => (req.url === '/api/suggest' ? suggest(req, res) : res.writeHead(404).end())).listen(4775, '127.0.0.1');
119
+ ```
120
+
121
+ ```js
122
+ // the page
123
+ import { attach } from 'grayling/web';
124
+ attach(document.querySelector('textarea'), { url: '/api/suggest', warm: () => fetch('/api/warm', { method: 'POST' }) });
125
+ ```
126
+
127
+ `node examples/server.mjs` (after `npm run build`) is this, whole: a page with a textarea that has suggestions, at
128
+ http://localhost:4775. The first suggestion asked for sets the engine up (about 1.1 GB of downloads); until then the answer is
129
+ `204`, and `grayling.state()` says how far it is.
130
+
131
+ **`handler(grayling, options)`** is a `(req, res) => Promise<void>` for `node:http` and for frameworks (Express: `app.post(path,
132
+ express.json(), handler(g))`; it uses the `req.body` that was parsed; Fastify: `handler(g)(request.raw, reply.raw, request.body)`). A POST of a
133
+ `SuggestRequest` is answered `200` with the `SuggestResponse`, or `204` with nothing to suggest (off, still starting, the engine
134
+ not there). The request is checked as Hydor's server does (`cleanRequest`: at most 4,000 characters a field, the first 600 after the
135
+ caret) and the body is limited (`maxBytes`, 256 KB). When the connection closes before the answer (the person typed on), the
136
+ suggestion is cancelled on the engine. **Only the same origin may ask by default**: a request from another site, one that is not
137
+ `application/json`, or (with `allowedHosts`) one for a name the server does not answer to, is refused with 403/415; `origins` adds
138
+ sites that may ask (with CORS), `sameOrigin: false` turns the check off when something else checks who asks. A server that listens on
139
+ a local address should give `allowedHosts`, or a page of another site that points a name at it could ask.
140
+
141
+ The app's own settings go in `options.settings` (your `SuggestSettings`, or a function that gives them): whether to suggest at all
142
+ (`enabled`, `where`, `midText`, `fixTypos`) and how (`precision`, `nextWord`, `sessionCache`, `switchByLanguage`, `typedWords`,
143
+ `contextWords`) are the app's to say, and go with each request. `options.options(request, http)` does the same at a lower level.
144
+
145
+ **`connect(options)`** rejects (`GraylingError`, its `code` says what) when there is no engine and none can be started. Once
146
+ connected it stays connected: when the engine was replaced, stopped or died it connects again by itself (after 0.2 s, then longer, up to
147
+ 5 s), starting the program if need be, and puts back what it watched, claimed and provided. Requests made while it is away wait up to
148
+ 3 s; then `suggest()` and `warm()` answer `null`, `state()` answers the last state it knew with `status.state: 'failed'`, and the
149
+ others reject with the code `unavailable`.
150
+
151
+ | | |
152
+ |---|---|
153
+ | `suggest(request, { signal, tab })` | a `SuggestResponse`, or `null`. `suggestRaw` gives `{ response, why }` (`starting`, `dropped`, `memory`, `failed`, `off`, `elsewhere`, `unavailable`, `aborted`, `timeout`). `tab` (default `request.client`): a newer request of a tab drops the one before. Aborting `signal` cancels it on the engine. |
154
+ | `warm()`, `state()`, `set(patch)` | the `{ settings, status }`; `set` changes the settings that every program shares (a bad one is the error `bad`, and changes nothing) |
155
+ | `watch(fn)`, `on('state' \| 'claims' \| 'connect' \| 'disconnect', fn)` | events (a `state` that says `failed` comes the moment the engine goes, and the real one when it is back); they return what stops listening. The engine is asked for `state` and `claims` only while someone listens. |
156
+ | `usage(counts, judged)`, `resetUsage()` | add counts of what suggestions did (never any text) to this client's; the usage and thresholds |
157
+ | `keep(word)`, `forgetKept()` | words kept as typed: never offered as a typo again, to any program |
158
+ | `learn('now' \| 'pause' \| 'stop' \| 'forget')` | the learning of the personal model |
159
+ | `session(id, texts, own)` | the earlier text of a chat session, for the session cache |
160
+ | `provide(fn \| null, typedAt)` | says this client has texts to learn from; `fn({ file, since, until, freshSince, signal })` writes them to `file` itself and returns the counts, or returns lines (`{ kind: 'user' \| 'agent' \| 'doc', text, ts }`: an array, an iterable or an async iterable) that the client writes and counts |
161
+ | `claim(apps)` | programs of yours that show suggestions of their own (`{ bundle, exe, wmClass }`): the desktop app leaves them alone |
162
+ | `adopt(what)`, `info()`, `stopHost()`, `close()` | bring in what an earlier version of your app kept (it is copied from, never moved, but for the Python environments, which are moved in the background when they are real folders: docs/protocol.md; `models` is the folder that holds the model folders); the engine's process, folders and clients; ask the engine to end (`stopHost({ ifAlone: true })`: only when no other connection uses it; either way this client ends); end this client (the engine goes on) |
163
+
164
+ Names are camelCase here and snake_case on the wire (one table, in `src/node/wire.ts`). `status` has the shape of `SuggestStatus` and
165
+ `settings` the part of `SuggestSettings` that belongs to the engine (`GRAYLING_SETTING_KEYS`: `llm`, `quant`, `threads`, `personalise`,
166
+ `schedule`, `userWeight`, `trainThreads`, `trainGpu`). What differs: the status has the engine's version too (`engine`); `enabled`,
167
+ `where`, `precision`, `nextWord`, `midText`, `fixTypos`, `typedWords`, `contextWords`, `switchByLanguage`, `sessionCache` and `sources`
168
+ are the app's own and are not in the engine's settings; `suggestState(state, ownSettings)` puts the two together as a `SuggestState`.
169
+
170
+ **The program.** `findProgram()` looks for it in the option, `GRAYLING_BIN`, the platform package (`@algoprog/grayling-linux-x64`,
171
+ `…-darwin-arm64`, `…-win32-x64`, installed with this package where the system fits), and
172
+ `<data>/bin/<version>/grayling`; it gives `null` when it is nowhere. `installProgram({ signal, progress })` downloads it for this
173
+ version from the [GitHub release](https://github.com/algoprog/grayling/releases) (resuming, checking its size and SHA-256 against the
174
+ `program.json` that ships in this package, unpacking atomically into `<data>/bin/<version>`) and gives its path; where no program is
175
+ published (musl, 32-bit) it says so, and you can build one and point `GRAYLING_BIN` at it.
176
+
177
+ **On Windows the program is not run out of `node_modules`**: a running program locks its file, so `npm install` (and an app's own installer) would
178
+ fail while the engine host runs. `findProgram()` keeps saying where the package's own program is, but `connect()` starts a copy of it:
179
+ `startableProgram(path)` copies it to `<data>\bin\<version>\grayling.exe` (a temporary file, then a rename; the copy there is used as it is when its
180
+ size and SHA-256 are the same, and one that cannot be replaced because it runs is fine when it is the same), starts that one, and removes the folders of
181
+ older versions that nothing holds. A program that is not in a package (`GRAYLING_BIN`, the `program` option, what `installProgram()` made) is started where it is,
182
+ and on the other systems nothing is copied.
183
+
184
+ ```js
185
+ const program = findProgram() ?? (await installProgram({ progress: (p) => console.log(p.phase, p.received, p.total) }));
186
+ const grayling = await connect({ client: 'my-app', clientVersion: '1.4.0', program });
187
+ ```
188
+
189
+ `connect` options: `client` (who you are: letters, digits, `.`, `_`, `-`), `instance` (two copies of one client), `clientVersion`, `program`,
190
+ `install` (no program of your own: connect to an engine that already runs, and get the program in the background so that this client can
191
+ start one when that engine ends; with none running, get it first, then start it; `install: { progress }` hears the download;
192
+ `grayling.hasProgram`, `setProgram(path)` and `programError` say how it went),
193
+ `start: false` (never start an engine: connect to the one that runs), `home` (`GRAYLING_HOME`: keep everything in one folder),
194
+ `env`, `engine` and `timeouts` (for tests). `paths()` says where the data, the cache and the socket are. An engine that is older
195
+ than your program is asked to hand over and your program takes its place (the other programs connect again by themselves); a newer
196
+ one is used as it is.
197
+
198
+ ### Counting what suggestions did
199
+
200
+ Give the boxes one `UsageBatch`; with `grayling/node` the route adds the counts to this client's (the engine fits how sure a
201
+ suggestion must be to show from them, for each client):
202
+
203
+ ```js
204
+ import { UsageBatch } from 'grayling/web';
205
+ const usage = new UsageBatch({
206
+ // Return true to try again later (the network failed); false when it got there or was refused.
207
+ send: (piece, leaving) => fetch('/api/suggest/usage', { method: 'POST', body: JSON.stringify(piece), keepalive: true })
208
+ .then((r) => r.status >= 500, () => true),
209
+ });
210
+ attach(box, { url: '/api/suggest', onCount: usage.record, onJudge: usage.recordJudged });
211
+ ```
212
+
213
+ It sends every 15 seconds while there is something to send, and when the page is hidden. On the server (`piece` is the counts, and
214
+ `judged` when there are some):
215
+
216
+ ```js
217
+ app.post('/api/suggest/usage', async (req) => {
218
+ const { judged, ...counts } = req.body;
219
+ return grayling.usage(counts, judged); // { usage, thresholds }; a count that is not one is the error `bad`
220
+ });
221
+ ```
222
+
223
+ ## The class `grayling-box` and `aria-autocomplete`
224
+
225
+ While suggestions are on in a box (the switches allow its place), the box carries the class `grayling-box` and says that it completes
226
+ inline by itself with `aria-autocomplete`, in `attach` and in the React hook alike, focused or not. It is `inline` when the page gave
227
+ none or `none`, `both` when it gave `list`, and what the page gave when that already says inline (`inline`, `both`). Both are taken
228
+ away when suggestions are off or the box is detached (what the page set is put back), put back if something rewrites the box's class
229
+ or the attribute, and a page that changes `aria-autocomplete` meanwhile is followed. Browsers show a box's class list and its
230
+ `aria-autocomplete` to accessibility tools, so the Grayling desktop app leaves that box alone and suggestions show once, not twice.
231
+ Firefox on macOS shows neither, but a box's `id`: a box without one has `grayling-box-…` while suggestions are on.
232
+
233
+ ## Labels and theming
234
+
235
+ **Look.** Import `grayling/web/style.css`. Everything is a CSS custom property: `--grayling-grey`, `--grayling-grey-next`,
236
+ `--grayling-warn`, `--grayling-chip-bg`, `--grayling-chip-line`, `--grayling-chip-fg`, `--grayling-chip-fg-strong`,
237
+ `--grayling-chip-muted`, `--grayling-chip-hover`, `--grayling-chip-shadow`, `--grayling-chip-radius`, `--grayling-kbd-bg`,
238
+ `--grayling-kbd-line`. It is light by default, dark with `prefers-color-scheme: dark`; set `data-grayling-theme="dark"` (or
239
+ `"light"`) on `<html>` to force one. The chip's fade is off with `prefers-reduced-motion`.
240
+
241
+ **Words.** Every visible string and aria-label comes from `labels`, as functions, so you can translate them:
242
+
243
+ ```js
244
+ attach(box, { url, labels: { replace: (w) => `Ersetzen durch ${w}`, keep: () => 'So lassen', complete: (w) => `Mit ${w} beenden`, tab: () => 'Tab' } });
245
+ ```
246
+
247
+ Two of the labels are what a screen reader hears, not what is drawn: `suggestion(word, key)` ("Suggestion: questions. Tab takes it.") and
248
+ `correction(word, typed, key)` ("Correction: definitely for definately. Tab takes it."); `key` is what `tab()` says.
249
+
250
+ **Screen readers.** A web page cannot tell whether a screen reader runs, so a suggestion that has stood for 1.2 s is put in a polite live
251
+ region for everyone: one element for the page, visually hidden the way assistive text is (a clipped 1 px box, not `display: none`, which a
252
+ screen reader would skip), emptied when the suggestion goes, never twice for the same suggestion and not while an input method composes. It
253
+ goes away with the last `detach` (or the last box that unmounts). The grey text and the chips are hidden from screen readers, since the
254
+ box's own text is what is being read. `announce: false` turns it all off: `attach(box, { url, announce: false })`, or
255
+ `createSuggest({ ..., announce: false })`.
256
+
257
+ **Classes.** `classes` gives your own class names for every element (`mirror`, `grey`, `greyNext`, `marks`, `mark`, `layer`,
258
+ `chip`, `chipBox`, `chipBar`, `chipPart`, `chipStrong`, `chipTyped`, `chipRest`, `chipDim`, `kbd`, `chipClose`), for example
259
+ Tailwind classes. `kbd` draws the key beside a word with your own element (a function returning a DOM node in `attach`, a React
260
+ node in `grayling/react`), and `attributes` adds attributes to the grey layer, the marks layer and the chip's wrapper.
261
+
262
+ ## Try it
263
+
264
+ `npm run build`, serve this folder with any static server and open `demo/index.html`: a textarea, a text input and a fake `send`
265
+ that knows a few words. Press the button to switch between the dark and the light look.
266
+
267
+ ## Licence
268
+
269
+ AGPL-3.0-only. See `LICENSE`. Contributions need the contributor agreement (`CLA.md` in the repository).
@@ -0,0 +1,290 @@
1
+ /**
2
+ * Word suggestions: the grey rest of the word after the caret (and the next word, dimmer), from a small model mixed with
3
+ * Qwen3.5-0.8B, both running on the person's own computer. With text after the caret the word shows over the text
4
+ * instead, and a word typed wrong shows with the right one; Tab takes those too.
5
+ *
6
+ * These are the types and limits a text box and its engine agree on: what a box asks (`SuggestRequest`), what comes back
7
+ * (`SuggestResponse`), the settings, and the counts a box reports (never any text).
8
+ */
9
+ /** Where a suggestion is asked for: a message to an agent, a document, or any other text box. */
10
+ export type SuggestSurface = 'chat' | 'doc' | 'text';
11
+ /** What a text box asks for (the body of the POST to a suggest endpoint). */
12
+ export interface SuggestRequest {
13
+ surface: SuggestSurface;
14
+ /** The text before the caret (the client sends at most its last 2,000 characters). */
15
+ text: string;
16
+ /** chat: the agent's last reply (its last 2,000 characters). */
17
+ reply?: string;
18
+ /** chat: the person's previous message in this session (its last 2,000 characters). */
19
+ prev?: string;
20
+ /** doc: the document's text before the caret's paragraph (its last 2,000 characters). */
21
+ doc?: string;
22
+ /** chat: the session's key (its earlier text feeds the session cache). */
23
+ session?: string;
24
+ /** This client's id (one per browser tab): a new request cancels the client's one before. */
25
+ client?: string;
26
+ /**
27
+ * The text after the caret (its first 300 characters), when something stands there on the caret's line, or the caret is in
28
+ * a word: what the word is to fit before, or the rest of the word to check. Not sent at the end of a line.
29
+ */
30
+ after?: string;
31
+ /** The letters right after the caret begin another word (one is being put in before it), though no space is between them yet. */
32
+ apart?: boolean;
33
+ /** all (what it is when left out): the word at the caret, and a fix of a word typed wrong; fix: the fix alone. */
34
+ want?: 'all' | 'fix';
35
+ }
36
+ /** Which models made a suggestion: mix (both), llm (Qwen3.5 alone), slm (the small model alone). */
37
+ export type SuggestPlan = 'mix' | 'llm' | 'slm';
38
+ export declare const SUGGEST_PLANS: readonly ["mix", "llm", "slm"];
39
+ /**
40
+ * A word typed wrong, and the right one: the word at the caret, or the one before it when the caret is past its end. Sent only
41
+ * when it is sure enough to show.
42
+ */
43
+ export interface SuggestFix {
44
+ /** Where the word begins: how many characters before the caret. */
45
+ back: number;
46
+ /** The word as it stands in the text, with its letters after the caret when the caret is inside it. */
47
+ typed: string;
48
+ /** The word to put in its place. */
49
+ word: string;
50
+ /** How sure (0..1). */
51
+ conf: number;
52
+ /** The word is still being typed, so `word` guesses its end too. */
53
+ open?: boolean;
54
+ }
55
+ /**
56
+ * A suggestion. With show false it is not shown, but `word` and `conf` still say what was guessed: the page keeps it
57
+ * unseen, to learn how often a guess that sure is right for this person.
58
+ */
59
+ export interface SuggestResponse {
60
+ /** The rest of the word being typed ('' when the word is complete). */
61
+ word: string;
62
+ /** The word after it, with its leading space ('' when none). */
63
+ next: string;
64
+ /** How sure: the chance that `word` is right (0..1), and that `next` is, given `word`. */
65
+ conf: number;
66
+ confNext: number;
67
+ /** Whether to show `word`, and `next` after it (the confidence against the threshold for the precision set). */
68
+ show: boolean;
69
+ showNext: boolean;
70
+ /** mix: both models; llm: Qwen3.5 alone; slm: the small model alone. */
71
+ plan?: SuggestPlan;
72
+ /** The language guessed (a FLORES code such as eng_Latn), when it was sure. */
73
+ lang?: string;
74
+ /**
75
+ * The small model that answered: `personal` (the one learned from the person's writing: in the languages they write in, and
76
+ * where no language was guessed) or `base` (the one that came with the engine: in every other language). Not there when
77
+ * Qwen3.5 alone answered.
78
+ */
79
+ model?: 'base' | 'personal';
80
+ /** Time taken by the engine (ms). */
81
+ ms?: number;
82
+ /** A word typed wrong (when correcting typos is on): not there when there is none, or it is not sure enough. */
83
+ fix?: SuggestFix;
84
+ }
85
+ export type SuggestLlmMode = 'auto' | 'on' | 'off';
86
+ export type SuggestSchedule = 'nightly' | 'weekly' | 'manual';
87
+ /** The settings, kept by the engine. */
88
+ export interface SuggestSettings {
89
+ /** On or off. On from the start: it sets itself up the first time a text box is used (downloading about 1.1 GB then). */
90
+ enabled: boolean;
91
+ /** Qwen3.5-0.8B beside the small model: auto (when the computer has the memory), on, or off. */
92
+ llm: SuggestLlmMode;
93
+ /** The language model's size: 8-bit (better) or 4-bit (smaller, a little worse). */
94
+ quant: 'q8' | 'q4';
95
+ /** How sure a suggestion must be to show: the share of shown suggestions meant to be right (0.2 more of them … 0.5 surer ones; at most 0.6). */
96
+ precision: number;
97
+ /** Show the next word too, dimmer. */
98
+ nextWord: boolean;
99
+ /** Suggest inside a text too, with more of it after the caret on its line. */
100
+ midText: boolean;
101
+ /** Show the right word for one typed wrong (Tab puts it in). */
102
+ fixTypos: boolean;
103
+ /** Where suggestions show. */
104
+ where: {
105
+ chat: boolean;
106
+ docs: boolean;
107
+ notes: boolean;
108
+ other: boolean;
109
+ };
110
+ /** Words of the typed text read before the caret. */
111
+ typedWords: number;
112
+ /** Words of the agent's last reply (in a message) or of the document before the paragraph (in Docs) read. */
113
+ contextWords: number;
114
+ /** Choose per language between Qwen3.5 alone and the mix (from the language of the text). */
115
+ switchByLanguage: boolean;
116
+ /** Learn from the session's earlier text as it is typed (messages). */
117
+ sessionCache: boolean;
118
+ /** Threads for suggestions (0: chosen from the computer's cores). */
119
+ threads: number;
120
+ /** Personalise the small model on what this person writes. */
121
+ personalise: boolean;
122
+ schedule: SuggestSchedule;
123
+ /** What it learns from. */
124
+ sources: {
125
+ messages: boolean;
126
+ replies: boolean;
127
+ notes: boolean;
128
+ docs: boolean;
129
+ };
130
+ /** How much more the person's own typed words count than the rest (1..16). */
131
+ userWeight: number;
132
+ /** Threads for personalising (0: chosen from the computer's cores). */
133
+ trainThreads: number;
134
+ /** Learn on the graphics card when there is one (an NVIDIA card with 4 GB free, shared with a model server only while it is idle, or a Mac with Apple silicon); else on the processor. */
135
+ trainGpu: boolean;
136
+ }
137
+ export declare const SUGGEST_DEFAULTS: SuggestSettings;
138
+ /** The limits of the numeric settings (inclusive). */
139
+ export declare const SUGGEST_LIMITS: {
140
+ readonly precision: readonly [0.2, 0.6];
141
+ readonly typedWords: readonly [20, 200];
142
+ readonly contextWords: readonly [0, 200];
143
+ readonly threads: readonly [0, 32];
144
+ readonly userWeight: readonly [1, 16];
145
+ readonly trainThreads: readonly [0, 64];
146
+ };
147
+ /**
148
+ * What suggestions did, as counts only (never any text). `shown`: suggestions shown (one grey word at the caret; the
149
+ * next word becoming the grey word is a new one). `taken`: inserted with Tab or → (→ takes the word and the next: two).
150
+ * `typedThrough`: the person typed the whole grey word themselves. Right is taken + typedThrough; `wrong`: something
151
+ * else was typed while it showed (a different letter, Backspace). `saved`: for each Tab or →, the characters inserted
152
+ * minus the key pressed. `typedChars`: what was typed in boxes where suggestions are on (never what Tab inserted).
153
+ * The `mid` ones are the same for suggestions shown inside a text (counted apart, so that neither blurs the other), and the
154
+ * `fix` ones are the words typed wrong: shown with the right one, taken (Tab or a tap), and kept as typed (Esc or ×).
155
+ */
156
+ export interface SuggestCounts {
157
+ shown: number;
158
+ taken: number;
159
+ typedThrough: number;
160
+ wrong: number;
161
+ saved: number;
162
+ typedChars: number;
163
+ midShown: number;
164
+ midTaken: number;
165
+ midThrough: number;
166
+ midWrong: number;
167
+ midSaved: number;
168
+ fixShown: number;
169
+ fixTaken: number;
170
+ fixKept: number;
171
+ }
172
+ export declare const SUGGEST_COUNT_KEYS: readonly ["shown", "taken", "typedThrough", "wrong", "saved", "typedChars", "midShown", "midTaken", "midThrough", "midWrong", "midSaved", "fixShown", "fixTaken", "fixKept"];
173
+ /** The most words kept as typed (Esc on a fix): the oldest go. */
174
+ export declare const SUGGEST_KEPT_MAX = 500;
175
+ /** The most one report of counts may add to each count. */
176
+ export declare const SUGGEST_USAGE_CAP = 5000;
177
+ /** The bins of how sure a guess was (conf 0..1, each 1/40 wide) that judged guesses are counted in. */
178
+ export declare const SUGGEST_BINS = 40;
179
+ /** Judged guesses by how sure they were: how many there were in each bin, and how many of them were right. */
180
+ export interface SuggestBins {
181
+ right: number[];
182
+ total: number[];
183
+ }
184
+ /**
185
+ * Guesses judged against what the person then typed, as counts per plan (never any text): shown or not, so that the
186
+ * thresholds can be fitted to their writing.
187
+ */
188
+ export type SuggestJudged = Partial<Record<SuggestPlan, SuggestBins>>;
189
+ /** The judged answers a plan needs before its threshold is fitted to the person's writing. */
190
+ export declare const SUGGEST_FIT_MIN = 400;
191
+ /**
192
+ * Whether how sure a suggestion must be is fitted to the person's writing: `judged` answers counted (the older ones
193
+ * weigh less as new ones come), of the `needed` a plan needs.
194
+ */
195
+ export interface SuggestThresholds {
196
+ judged: number;
197
+ needed: number;
198
+ fitted: boolean;
199
+ }
200
+ /** How many local days of counts are kept (today and the 30 before). */
201
+ export declare const SUGGEST_USAGE_DAYS = 31;
202
+ /** The counts since `since` (ms), today (the local day) and the last 7 days (today and the 6 before). */
203
+ export interface SuggestUsage {
204
+ since: number;
205
+ total: SuggestCounts;
206
+ today: SuggestCounts;
207
+ week: SuggestCounts;
208
+ }
209
+ /** Where a run of learning is done. */
210
+ export interface TrainDevice {
211
+ kind: 'cpu' | 'cuda' | 'mps';
212
+ /** The graphics card's name (cuda). */
213
+ name?: string;
214
+ }
215
+ /** What word suggestions are doing. */
216
+ export interface SuggestStatus {
217
+ /**
218
+ * off: turned off; waiting: on but never used, so nothing is downloaded yet (it sets itself up the first time a box
219
+ * where it shows gets the focus); setting-up: installing Python libraries and downloading models; starting: loading
220
+ * them; ready; failed.
221
+ */
222
+ state: 'off' | 'waiting' | 'setting-up' | 'starting' | 'ready' | 'failed';
223
+ /** Progress while setting up, or why it failed. */
224
+ detail?: string;
225
+ /** While a download is under way (setting-up): which, and how many bytes of how many (the numbers beside `detail`'s text). */
226
+ setup?: {
227
+ what: 'small' | 'llm' | 'llama';
228
+ done: number;
229
+ total: number;
230
+ };
231
+ /** Resident memory, in MB, of the engine host and of llama-server (0 when it does not run); looked at most every 5 s. */
232
+ memory?: {
233
+ hostMb: number;
234
+ llmMb: number;
235
+ };
236
+ /**
237
+ * Qwen3.5-0.8B: running, not running (and why: turned off, too little memory, failed), or starting. Too little
238
+ * memory: totalMb when the computer itself has too little (needMb: what a computer needs), freeMb when too little is free now (needMb: what it needs free).
239
+ */
240
+ llm: {
241
+ state: 'off' | 'starting' | 'ready' | 'memory' | 'failed';
242
+ detail?: string;
243
+ freeMb?: number;
244
+ totalMb?: number;
245
+ needMb?: number;
246
+ };
247
+ /** The small model in use: the one that came with the engine, or the one personalised on this computer. */
248
+ model: {
249
+ kind: 'base' | 'personal';
250
+ trainedAt?: number;
251
+ tokens?: number;
252
+ languages?: Record<string, number>;
253
+ };
254
+ /**
255
+ * Personalising: idle, waiting for its time (next), running (progress), paused by the person (progress: where it stopped; it
256
+ * does not start again until Resume), or the last one failed.
257
+ */
258
+ training: {
259
+ state: 'idle' | 'waiting' | 'running' | 'paused' | 'failed';
260
+ progress?: {
261
+ done: number;
262
+ total: number;
263
+ };
264
+ startedAt?: number;
265
+ lastAt?: number;
266
+ next?: number;
267
+ detail?: string;
268
+ /** Where the run learns: on the processor, an NVIDIA graphics card (its name) or a Mac's (while running or paused). */
269
+ device?: TrainDevice;
270
+ /** Why the graphics card is not used when the setting is on (for the last run, or the next while it is held back for a day). */
271
+ noGpu?: string;
272
+ };
273
+ /** Requests answered since the worker started, and their time (ms). */
274
+ stats?: {
275
+ requests: number;
276
+ p50Ms?: number;
277
+ p90Ms?: number;
278
+ };
279
+ /** How many keystrokes suggestions saved and how many were right (counts kept by the engine; a reset starts them again). */
280
+ usage: SuggestUsage;
281
+ /** Whether the thresholds are fitted to the person's writing, from the guesses judged (a reset starts them again too). */
282
+ thresholds: SuggestThresholds;
283
+ /** How many words the person kept as they typed them (they are never shown as typed wrong again). */
284
+ kept: number;
285
+ }
286
+ /** The settings and the status together. */
287
+ export interface SuggestState {
288
+ settings: SuggestSettings;
289
+ status: SuggestStatus;
290
+ }
package/dist/index.js ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Word suggestions: the grey rest of the word after the caret (and the next word, dimmer), from a small model mixed with
3
+ * Qwen3.5-0.8B, both running on the person's own computer. With text after the caret the word shows over the text
4
+ * instead, and a word typed wrong shows with the right one; Tab takes those too.
5
+ *
6
+ * These are the types and limits a text box and its engine agree on: what a box asks (`SuggestRequest`), what comes back
7
+ * (`SuggestResponse`), the settings, and the counts a box reports (never any text).
8
+ */
9
+ export const SUGGEST_PLANS = ['mix', 'llm', 'slm'];
10
+ export const SUGGEST_DEFAULTS = {
11
+ enabled: true,
12
+ llm: 'auto',
13
+ quant: 'q8',
14
+ precision: 0.2,
15
+ nextWord: true,
16
+ midText: true,
17
+ fixTypos: true,
18
+ where: { chat: true, docs: true, notes: true, other: true },
19
+ typedWords: 100,
20
+ contextWords: 100,
21
+ switchByLanguage: true,
22
+ sessionCache: true,
23
+ threads: 0,
24
+ personalise: true,
25
+ schedule: 'nightly',
26
+ sources: { messages: true, replies: true, notes: true, docs: true },
27
+ userWeight: 4,
28
+ trainThreads: 0,
29
+ trainGpu: true,
30
+ };
31
+ /** The limits of the numeric settings (inclusive). */
32
+ export const SUGGEST_LIMITS = {
33
+ precision: [0.2, 0.6],
34
+ typedWords: [20, 200],
35
+ contextWords: [0, 200],
36
+ threads: [0, 32],
37
+ userWeight: [1, 16],
38
+ trainThreads: [0, 64],
39
+ };
40
+ export const SUGGEST_COUNT_KEYS = ['shown', 'taken', 'typedThrough', 'wrong', 'saved', 'typedChars', 'midShown', 'midTaken', 'midThrough', 'midWrong', 'midSaved', 'fixShown', 'fixTaken', 'fixKept'];
41
+ /** The most words kept as typed (Esc on a fix): the oldest go. */
42
+ export const SUGGEST_KEPT_MAX = 500;
43
+ /** The most one report of counts may add to each count. */
44
+ export const SUGGEST_USAGE_CAP = 5000;
45
+ /** The bins of how sure a guess was (conf 0..1, each 1/40 wide) that judged guesses are counted in. */
46
+ export const SUGGEST_BINS = 40;
47
+ /** The judged answers a plan needs before its threshold is fitted to the person's writing. */
48
+ export const SUGGEST_FIT_MIN = 400;
49
+ /** How many local days of counts are kept (today and the 30 before). */
50
+ export const SUGGEST_USAGE_DAYS = 31;
@@ -0,0 +1,4 @@
1
+ /** The contents of the first file named `want` (anywhere in the archive) of a `.tar.gz` made by `tar` (ustar, pax or GNU). */
2
+ export declare function fromTarGz(archive: Buffer, want: string): Buffer;
3
+ /** The contents of the first file named `want` (anywhere in the archive) of a `.zip` (stored or deflated; no zip64). */
4
+ export declare function fromZip(zip: Buffer, want: string): Buffer;