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
@@ -0,0 +1,669 @@
1
+ /** The client of the engine host: `connect()` gives a `Grayling` that finds or starts the host and stays connected to it. */
2
+ import { open } from 'node:fs/promises';
3
+ import { openSocket, spawnHost } from './connection.js';
4
+ import { GraylingError, messageOf } from './errors.js';
5
+ import { paths } from './paths.js';
6
+ import { findProgram, installProgram, programVersion, startableProgram } from './program.js';
7
+ import { outcomeFromWire, suggestToWire } from './suggest.js';
8
+ import { GRAYLING_SETTING_DEFAULTS, GRAYLING_SETTING_KEYS, } from './types.js';
9
+ import { packageVersion, versionCmp } from './version.js';
10
+ import { appsFromWire, appsToWire, fromWire, helloFromWire, infoFromWire, OPAQUE, settingsToWire, stateFromWire, toWire } from './wire.js';
11
+ /** The protocol this client speaks (docs/protocol.md). */
12
+ export const PROTOCOL = 1;
13
+ export const DEFAULT_TIMEOUTS = {
14
+ start: 15_000,
15
+ hello: 10_000,
16
+ request: 30_000,
17
+ wait: 3_000,
18
+ replace: 10_000,
19
+ poll: 50,
20
+ backoffMin: 200,
21
+ backoffMax: 5_000,
22
+ provider: 600_000,
23
+ provideEvery: 60_000,
24
+ };
25
+ const sleepFor = (ms) => new Promise((r) => setTimeout(r, ms));
26
+ const isLines = (v) => !!v && typeof v === 'object' && (Symbol.iterator in v || Symbol.asyncIterator in v);
27
+ const emptyCounts = () => ({
28
+ shown: 0, taken: 0, typedThrough: 0, wrong: 0, saved: 0, typedChars: 0, midShown: 0, midTaken: 0, midThrough: 0, midWrong: 0,
29
+ midSaved: 0, fixShown: 0, fixTaken: 0, fixKept: 0,
30
+ });
31
+ /** A state for when the host cannot be asked: what was last known, saying that the host is not there. */
32
+ function unavailableState(last, detail) {
33
+ const zero = { since: Date.now(), total: emptyCounts(), today: emptyCounts(), week: emptyCounts() };
34
+ return {
35
+ settings: last?.settings ?? { ...GRAYLING_SETTING_DEFAULTS },
36
+ status: {
37
+ ...(last?.status ?? { llm: { state: 'off' }, model: { kind: 'base' }, training: { state: 'idle' }, usage: zero, thresholds: { judged: 0, needed: 0, fitted: false }, kept: 0, engine: '' }),
38
+ state: 'failed',
39
+ detail,
40
+ },
41
+ };
42
+ }
43
+ /** A connection to the engine host that keeps itself up. Make one with `connect()`. */
44
+ export class Grayling {
45
+ paths;
46
+ t;
47
+ env;
48
+ program;
49
+ canStart;
50
+ engine;
51
+ hello;
52
+ conn = null;
53
+ helloAnswer = null;
54
+ closing = false;
55
+ reconnecting = false;
56
+ lastError;
57
+ lastState;
58
+ waiters = new Set();
59
+ nap;
60
+ listeners = new Map();
61
+ watched = '';
62
+ claimed = null;
63
+ provider = null;
64
+ typedAt = 0;
65
+ providedAt = 0;
66
+ providedKey = '';
67
+ provideTimer;
68
+ /** Lines the host sent that were not JSON (a count, for people who look). */
69
+ garbage = 0;
70
+ /** Why the program could not be had in the background (`connect`'s `install`), when it could not. */
71
+ programError;
72
+ /** @internal Use `connect()`. */
73
+ constructor(o = {}) {
74
+ const client = o.client ?? 'node';
75
+ if (!client || client.length > 40 || !/^[A-Za-z0-9._-]+$/.test(client)) {
76
+ throw new GraylingError('bad', 'client: letters, digits, ".", "_" and "-", at most 40');
77
+ }
78
+ this.t = { ...DEFAULT_TIMEOUTS, ...o.timeouts };
79
+ this.env = o.home ? { ...(o.env ?? process.env), GRAYLING_HOME: o.home } : (o.env ?? process.env);
80
+ this.paths = paths({ env: this.env });
81
+ this.canStart = o.start !== false;
82
+ this.program = this.canStart ? (o.program === undefined ? findProgram({ env: this.env, appDir: o.appDir }) : o.program) : null;
83
+ const forced = o.engine ?? (this.env.GRAYLING_TEST_VERSION || undefined);
84
+ this.engine = forced ?? (this.program ? programVersion(this.program, this.env) : null) ?? packageVersion();
85
+ this.hello = {
86
+ protocol: PROTOCOL,
87
+ client,
88
+ instance: o.instance ?? '',
89
+ version: o.clientVersion ?? packageVersion(),
90
+ engine: this.engine,
91
+ };
92
+ }
93
+ // ---- connecting ----------------------------------------------------------------------------------------------------
94
+ /** @internal */
95
+ async open() {
96
+ this.up(await this.openConn());
97
+ }
98
+ /** Whether this client has a program to start the engine with. */
99
+ get hasProgram() {
100
+ return !!this.program;
101
+ }
102
+ /**
103
+ * Gives the client the program to start the engine with, when it had none (what `installProgram` made): from now on it starts an
104
+ * engine when none answers, and hands an older one over to its own, as a client that had a program from the start does. (Not for a
105
+ * client made with `start: false`.)
106
+ */
107
+ setProgram(program) {
108
+ if (!this.canStart)
109
+ return;
110
+ this.program = program;
111
+ const forced = this.env.GRAYLING_TEST_VERSION || undefined;
112
+ this.engine = forced ?? programVersion(program, this.env) ?? packageVersion();
113
+ this.hello.engine = this.engine;
114
+ }
115
+ /** The host's pid, version and protocol, from hello; null while there is no connection. */
116
+ get host() {
117
+ return this.conn ? this.helloAnswer : null;
118
+ }
119
+ get connected() {
120
+ return !!this.conn && !this.conn.replaced;
121
+ }
122
+ async openConn() {
123
+ let replaced = false;
124
+ for (let round = 0; round < 3; round++) {
125
+ const conn = await this.connectStarting();
126
+ let hello;
127
+ try {
128
+ hello = await this.shake(conn);
129
+ }
130
+ catch (e) {
131
+ conn.close();
132
+ throw e;
133
+ }
134
+ // A client that brought a newer program than the host's asks it to hand over, and starts its own.
135
+ const older = !!this.program && this.canStart && versionCmp(this.engine, hello.engine) > 0;
136
+ if (!older || replaced) {
137
+ this.helloAnswer = hello;
138
+ return conn;
139
+ }
140
+ try {
141
+ await conn.request('replace', { engine: this.engine }, this.t.hello).promise;
142
+ replaced = true;
143
+ // The host lets go of the lock and then closes the connections: when this one closes, ours may start.
144
+ await Promise.race([conn.closed, sleepFor(this.t.replace)]);
145
+ conn.close();
146
+ }
147
+ catch {
148
+ // Too young to hand over, or it will not: it serves this client, as an older host serves a newer client.
149
+ this.helloAnswer = hello;
150
+ return conn;
151
+ }
152
+ }
153
+ throw new GraylingError('start-failed', 'the engine host did not hand over');
154
+ }
155
+ async shake(conn) {
156
+ let refused;
157
+ conn.onNullError = (e) => {
158
+ refused = e;
159
+ conn.close();
160
+ };
161
+ try {
162
+ const a = await conn.request('hello', this.hello, this.t.hello).promise;
163
+ return helloFromWire(a);
164
+ }
165
+ catch (e) {
166
+ if (refused)
167
+ throw refused;
168
+ if (e instanceof GraylingError && e.code === 'protocol') {
169
+ const err = new GraylingError('protocol', `The engine host does not speak this client's protocol (${PROTOCOL}): ${e.message}. Update the grayling package or the grayling program.`, { cause: e });
170
+ err.protocols = e.protocols;
171
+ throw err;
172
+ }
173
+ throw e;
174
+ }
175
+ }
176
+ newSocket() {
177
+ return openSocket(this.paths, {
178
+ event: (e) => this.onEvent(e),
179
+ garbage: () => this.garbage++,
180
+ });
181
+ }
182
+ /** Connects, starting the program when no host answers, and trying again every 50 ms until `timeouts.start`. */
183
+ async connectStarting() {
184
+ try {
185
+ return await this.newSocket();
186
+ }
187
+ catch (e) {
188
+ this.lastError = e;
189
+ }
190
+ if (!this.canStart)
191
+ throw new GraylingError('not-running', 'the engine host is not running');
192
+ const program = this.program;
193
+ if (!program) {
194
+ throw new GraylingError('no-program', 'The engine host is not running and no grayling program was found to start it. Install the package for this system (@algoprog/grayling-<platform>-<arch>), call installProgram(), or set GRAYLING_BIN.');
195
+ }
196
+ // Windows: not out of node_modules (a running program locks its folder); a copy in the data folder.
197
+ const toStart = await startableProgram(program, { env: this.env });
198
+ const deadline = Date.now() + this.t.start;
199
+ let spawned = spawnHost(toStart, this.env);
200
+ let lastSpawn = Date.now();
201
+ let lastErr = messageOf(this.lastError);
202
+ for (;;) {
203
+ await sleepFor(this.t.poll);
204
+ try {
205
+ return await this.newSocket();
206
+ }
207
+ catch (e) {
208
+ lastErr = messageOf(e);
209
+ }
210
+ if (spawned.error)
211
+ throw new GraylingError('start-failed', `cannot start ${program}: ${spawned.error.message}`, { cause: spawned.error });
212
+ if (spawned.exit) {
213
+ const code = spawned.exit.code;
214
+ // 0 or 3: another host holds the lock and is starting (or ending): wait for it, and start ours if it does not come.
215
+ if (code === 0 || code === 3) {
216
+ if (Date.now() - lastSpawn >= 500) {
217
+ spawned = spawnHost(toStart, this.env);
218
+ lastSpawn = Date.now();
219
+ }
220
+ }
221
+ else {
222
+ try {
223
+ return await this.newSocket();
224
+ }
225
+ catch {
226
+ throw new GraylingError('start-failed', `the engine host could not start (exit ${code ?? 'by a signal'})`);
227
+ }
228
+ }
229
+ }
230
+ if (Date.now() >= deadline)
231
+ throw new GraylingError('start-failed', `the engine host did not answer in ${Math.round(this.t.start / 1000)} s (${lastErr})`);
232
+ }
233
+ }
234
+ /** A connection is up: wake the asks that wait, put back what was watched, claimed and provided. */
235
+ up(conn) {
236
+ this.conn = conn;
237
+ this.lastError = undefined;
238
+ this.watched = '';
239
+ // (Written before any waiting ask, on one socket: the host handles them in order.)
240
+ this.syncWatch();
241
+ if (this.claimed)
242
+ void conn.request('claim', { apps: appsToWire(this.claimed) }, this.t.request).promise.catch(() => { });
243
+ if (this.provider)
244
+ void this.sendProvide(true).catch(() => { });
245
+ for (const w of this.waiters) {
246
+ clearTimeout(w.timer);
247
+ w.resolve(conn);
248
+ }
249
+ this.waiters.clear();
250
+ this.emit('connect', this.helloAnswer);
251
+ if (this.has('state'))
252
+ void this.state().then((s) => this.emit('state', s), () => { });
253
+ void conn.closed.then(() => this.down(conn));
254
+ }
255
+ down(conn) {
256
+ if (this.conn !== conn)
257
+ return;
258
+ this.conn = null;
259
+ this.watched = '';
260
+ this.providedKey = '';
261
+ this.emit('disconnect', { reason: conn.reason });
262
+ // Whoever watches the state is told at once that there is none to ask (and the real one comes with the reconnect).
263
+ if (!this.closing && this.has('state'))
264
+ this.emit('state', unavailableState(this.lastState, `The engine host is not reachable (${conn.reason})`));
265
+ if (!this.closing)
266
+ void this.reconnect();
267
+ }
268
+ /** Connects again, with a wait that grows from 0.2 s to 5 s while the host is not there. */
269
+ async reconnect() {
270
+ if (this.reconnecting)
271
+ return;
272
+ this.reconnecting = true;
273
+ let delay = this.t.backoffMin;
274
+ try {
275
+ while (!this.closing) {
276
+ await new Promise((resolve) => {
277
+ this.nap = { resolve, timer: setTimeout(resolve, delay) };
278
+ });
279
+ this.nap = undefined;
280
+ if (this.closing)
281
+ return;
282
+ try {
283
+ const conn = await this.openConn();
284
+ if (this.closing)
285
+ return void conn.close();
286
+ this.up(conn);
287
+ return;
288
+ }
289
+ catch (e) {
290
+ this.lastError = e;
291
+ delay = Math.min(delay * 2, this.t.backoffMax);
292
+ }
293
+ }
294
+ }
295
+ finally {
296
+ this.reconnecting = false;
297
+ }
298
+ }
299
+ /** The connection, waiting up to `ms` for it to come back; null when it did not (or the client was closed, or `signal` aborted). */
300
+ waitUp(ms, signal) {
301
+ if (this.conn && !this.conn.replaced)
302
+ return Promise.resolve(this.conn);
303
+ if (this.closing || signal?.aborted)
304
+ return Promise.resolve(null);
305
+ return new Promise((resolve) => {
306
+ const w = {
307
+ resolve: (c) => (signal?.removeEventListener('abort', onAbort), resolve(c)),
308
+ timer: setTimeout(() => (this.waiters.delete(w), w.resolve(null)), ms),
309
+ };
310
+ const onAbort = () => (clearTimeout(w.timer), this.waiters.delete(w), w.resolve(null));
311
+ signal?.addEventListener('abort', onAbort, { once: true });
312
+ this.waiters.add(w);
313
+ });
314
+ }
315
+ unavailable() {
316
+ const why = this.lastError ? `: ${messageOf(this.lastError)}` : '';
317
+ return new GraylingError('unavailable', `The engine host is not reachable${why}`);
318
+ }
319
+ /** A request and its answer; made while the connection is down it waits for it (up to `timeouts.wait`), and once more after `replaced`. */
320
+ async call(op, fields = {}) {
321
+ for (let attempt = 0;; attempt++) {
322
+ const conn = await this.waitUp(this.t.wait);
323
+ if (!conn)
324
+ throw this.unavailable();
325
+ try {
326
+ return await conn.request(op, fields, this.t.request).promise;
327
+ }
328
+ catch (e) {
329
+ if (attempt === 0 && e instanceof GraylingError && e.code === 'replaced')
330
+ continue;
331
+ throw e;
332
+ }
333
+ }
334
+ }
335
+ // ---- events --------------------------------------------------------------------------------------------------------
336
+ has(event) {
337
+ return (this.listeners.get(event)?.size ?? 0) > 0;
338
+ }
339
+ emit(event, value) {
340
+ for (const f of [...(this.listeners.get(event) ?? [])]) {
341
+ try {
342
+ f(value);
343
+ }
344
+ catch {
345
+ // a listener's failure is not the client's
346
+ }
347
+ }
348
+ }
349
+ /** Listens to an event; returns what stops listening. `state` and `claims` are watched on the host while someone listens. */
350
+ on(event, fn) {
351
+ let set = this.listeners.get(event);
352
+ if (!set)
353
+ this.listeners.set(event, (set = new Set()));
354
+ set.add(fn);
355
+ this.syncWatch();
356
+ return () => this.off(event, fn);
357
+ }
358
+ off(event, fn) {
359
+ this.listeners.get(event)?.delete(fn);
360
+ this.syncWatch();
361
+ }
362
+ /** The host's state whenever it changes (at most every 150 ms): `on('state', fn)`. */
363
+ watch(fn) {
364
+ return this.on('state', fn);
365
+ }
366
+ /** What the host is told to send: the events someone listens to. */
367
+ syncWatch() {
368
+ const events = ['state', 'claims'].filter((e) => this.has(e));
369
+ const key = events.join(',');
370
+ const conn = this.conn;
371
+ if (!conn || key === this.watched || (key === '' && this.watched === ''))
372
+ return;
373
+ this.watched = key;
374
+ void conn.request('watch', { events }, this.t.request).promise.catch(() => { });
375
+ }
376
+ onEvent(e) {
377
+ switch (e.event) {
378
+ case 'state':
379
+ this.emit('state', (this.lastState = stateFromWire(e)));
380
+ break;
381
+ case 'claims':
382
+ this.emit('claims', appsFromWire(e.apps));
383
+ break;
384
+ case 'texts':
385
+ void this.runProvider(e);
386
+ break;
387
+ }
388
+ }
389
+ // ---- suggestions ---------------------------------------------------------------------------------------------------
390
+ /** A suggestion, or null (and `suggestRaw` says why): off, still starting, cancelled by a newer one of the tab, or the host is not there. */
391
+ async suggest(req, o = {}) {
392
+ return (await this.suggestRaw(req, o)).response;
393
+ }
394
+ /** `suggest`, with the reason there was none: `starting`, `dropped`, `memory`, `failed`, `off`, `elsewhere`, `unavailable`, `aborted`, `timeout`. */
395
+ async suggestRaw(req, o = {}) {
396
+ if (o.signal?.aborted)
397
+ return { response: null, why: 'aborted' };
398
+ const conn = await this.waitUp(this.t.wait, o.signal);
399
+ if (!conn)
400
+ return { response: null, why: o.signal?.aborted ? 'aborted' : 'unavailable' };
401
+ const { id, promise } = conn.request('suggest', suggestToWire(req, o.tab), this.t.request);
402
+ const onAbort = () => conn.cancel(id);
403
+ o.signal?.addEventListener('abort', onAbort, { once: true });
404
+ try {
405
+ return outcomeFromWire(await promise, req);
406
+ }
407
+ catch (e) {
408
+ const code = e instanceof GraylingError ? e.code : '';
409
+ if (code === 'aborted')
410
+ return { response: null, why: 'aborted' };
411
+ if (code === 'timeout') {
412
+ if (!conn.isClosed)
413
+ void conn.request('cancel', { target: id }, 5_000).promise.catch(() => { });
414
+ return { response: null, why: 'timeout' };
415
+ }
416
+ if (code === 'closed' || code === 'replaced')
417
+ return { response: null, why: 'unavailable' };
418
+ throw e;
419
+ }
420
+ finally {
421
+ o.signal?.removeEventListener('abort', onAbort);
422
+ }
423
+ }
424
+ /** A text box got the focus: what is set up is loaded (the first one ever starts the set-up). Null when the host is not there. */
425
+ async warm() {
426
+ try {
427
+ return this.remember(stateFromWire(await this.call('warm')));
428
+ }
429
+ catch (e) {
430
+ if (isDown(e))
431
+ return null;
432
+ throw e;
433
+ }
434
+ }
435
+ /** Chat text for the session cache (the person's own words are `own: true`). Best effort: nothing happens when the host is not there. */
436
+ async session(id, texts, own) {
437
+ try {
438
+ await this.call('session', { session: id, texts, ...(own ? { own } : {}) });
439
+ }
440
+ catch (e) {
441
+ if (!isDown(e))
442
+ throw e;
443
+ }
444
+ }
445
+ // ---- state and settings --------------------------------------------------------------------------------------------
446
+ remember(s) {
447
+ return (this.lastState = s);
448
+ }
449
+ /**
450
+ * The settings and the status. When the host cannot be reached it is still an answer: the last state known, with `status.state`
451
+ * `failed` and the reason in `status.detail`.
452
+ */
453
+ async state() {
454
+ try {
455
+ return this.remember(stateFromWire(await this.call('state')));
456
+ }
457
+ catch (e) {
458
+ if (isDown(e)) {
459
+ const why = e instanceof GraylingError ? e.message : messageOf(e);
460
+ return unavailableState(this.lastState, /not reachable/.test(why) ? why : `The engine host is not reachable (${why})`);
461
+ }
462
+ throw e;
463
+ }
464
+ }
465
+ /** Changes some of the host's settings (shared by every client); every field is checked, and a bad one is the error `bad`. */
466
+ async set(patch) {
467
+ return this.remember(stateFromWire(await this.call('set', { settings: settingsToWire(patch) })));
468
+ }
469
+ // ---- counts, kept words, learning ----------------------------------------------------------------------------------
470
+ /** Adds counts (and judged guesses) of what suggestions did: never any text. Gives this client's usage and thresholds. */
471
+ async usage(counts, judged) {
472
+ const body = toWire({ counts, ...(judged ? { judged } : {}) }, OPAQUE.usage);
473
+ const a = await this.call('usage', body);
474
+ return fromWire({ usage: a.usage, thresholds: a.thresholds });
475
+ }
476
+ /** Starts this client's counts again from nothing (and what was judged with them). */
477
+ async resetUsage() {
478
+ return this.remember(stateFromWire(await this.call('usage.reset')));
479
+ }
480
+ /** A word the person kept as typed: never offered as a typo again, to any client. How many are kept now. */
481
+ async keep(word) {
482
+ return Number((await this.call('keep', { word })).kept ?? 0);
483
+ }
484
+ /** Forgets every kept word. */
485
+ async forgetKept() {
486
+ return this.remember(stateFromWire(await this.call('kept.forget')));
487
+ }
488
+ /** Controls learning: `now` (also goes on with a paused run), `pause`, `stop`, `forget` (the personal model). */
489
+ async learn(action) {
490
+ return this.remember(stateFromWire(await this.call('learn', { action })));
491
+ }
492
+ // ---- providing texts, claiming ---------------------------------------------------------------------------------------
493
+ /**
494
+ * Says this client has texts to learn from (`fn`), or no longer (`null`). When a learning run begins the host asks for them and
495
+ * `fn` writes them (see `TextsProvider`). Call it again with `typedAt` (milliseconds; 0: unknown) when the person has typed: it
496
+ * is sent at most once a minute. It is put back after a reconnect.
497
+ */
498
+ async provide(fn, typedAt = 0) {
499
+ const was = !!this.provider;
500
+ this.provider = fn;
501
+ this.typedAt = typedAt;
502
+ if (!fn || !was) {
503
+ clearTimeout(this.provideTimer);
504
+ this.provideTimer = undefined;
505
+ await this.sendProvide(true);
506
+ return;
507
+ }
508
+ const wait = this.providedAt + this.t.provideEvery - Date.now();
509
+ if (wait <= 0)
510
+ await this.sendProvide(false);
511
+ else if (!this.provideTimer) {
512
+ this.provideTimer = setTimeout(() => {
513
+ this.provideTimer = undefined;
514
+ void this.sendProvide(false).catch(() => { });
515
+ }, wait);
516
+ this.provideTimer.unref?.();
517
+ }
518
+ }
519
+ async sendProvide(force) {
520
+ const conn = this.conn;
521
+ if (!conn || conn.replaced)
522
+ return;
523
+ const body = { on: !!this.provider, typed_at: this.typedAt };
524
+ const key = JSON.stringify(body);
525
+ if (!force && key === this.providedKey)
526
+ return;
527
+ this.providedKey = key;
528
+ this.providedAt = Date.now();
529
+ await conn.request('provide', body, this.t.request).promise;
530
+ }
531
+ async runProvider(e) {
532
+ const conn = this.conn;
533
+ if (!conn)
534
+ return;
535
+ const ref = String(e.ref ?? '');
536
+ const reply = (fields) => conn.request('texts', { ref, ...fields }, this.t.request).promise.catch(() => { });
537
+ const fn = this.provider;
538
+ if (!fn)
539
+ return void (await reply({ error: 'this client has no texts to give' }));
540
+ const ac = new AbortController();
541
+ const timer = setTimeout(() => ac.abort(), this.t.provider);
542
+ try {
543
+ const n = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
544
+ const job = { file: String(e.file ?? ''), since: n(e.since), until: n(e.until), freshSince: n(e.fresh_since), signal: ac.signal };
545
+ const out = await fn(job);
546
+ const counts = isLines(out) ? await writeTexts(job.file, out, job.freshSince, ac.signal) : out;
547
+ if (!counts || typeof counts !== 'object')
548
+ throw new Error('the texts provider returned neither the lines nor their counts');
549
+ const c = counts;
550
+ await reply({ user: n(c.user), agent: n(c.agent), doc: n(c.doc), fresh: n(c.fresh) });
551
+ }
552
+ catch (err) {
553
+ await reply({ error: messageOf(err).slice(0, 500) });
554
+ }
555
+ finally {
556
+ clearTimeout(timer);
557
+ }
558
+ }
559
+ /** The programs of this client that show suggestions of their own: the desktop app leaves them alone. They are this connection's. */
560
+ async claim(apps) {
561
+ this.claimed = apps;
562
+ const conn = this.conn;
563
+ if (conn && !conn.replaced)
564
+ await conn.request('claim', { apps: appsToWire(apps) }, this.t.request).promise;
565
+ }
566
+ // ---- the rest --------------------------------------------------------------------------------------------------------
567
+ /** Brings in what an earlier Hydor kept for itself, once, each only where the host has none. What was adopted. */
568
+ async adopt(what) {
569
+ const { venvGpu, ...rest } = what;
570
+ const body = { ...rest, ...(venvGpu !== undefined ? { venv_gpu: venvGpu } : {}) };
571
+ const a = await this.call('adopt', body);
572
+ return Array.isArray(a.adopted) ? a.adopted.map(String) : [];
573
+ }
574
+ /** The host's process, folders and clients. */
575
+ async info() {
576
+ return infoFromWire(await this.call('info'));
577
+ }
578
+ /**
579
+ * Asks the host to end, and ends this client (it would otherwise start the host again). With `ifAlone` the host ends only when this
580
+ * is the only connection it has; the answer says whether it is ending (this client ends either way).
581
+ */
582
+ async stopHost(options = {}) {
583
+ let stopping = true;
584
+ try {
585
+ const a = await this.call('stop', options.ifAlone ? { if_alone: true } : undefined);
586
+ if (options.ifAlone && a.stopping === false)
587
+ stopping = false;
588
+ }
589
+ finally {
590
+ await this.close();
591
+ }
592
+ return stopping;
593
+ }
594
+ /** Ends the connection, and does not connect again. The host goes on (it ends itself ten minutes after the last client left). */
595
+ async close() {
596
+ this.closing = true;
597
+ clearTimeout(this.provideTimer);
598
+ if (this.nap) {
599
+ clearTimeout(this.nap.timer);
600
+ this.nap.resolve();
601
+ }
602
+ for (const w of this.waiters) {
603
+ clearTimeout(w.timer);
604
+ w.resolve(null);
605
+ }
606
+ this.waiters.clear();
607
+ const conn = this.conn;
608
+ if (conn) {
609
+ conn.close();
610
+ await conn.closed;
611
+ }
612
+ }
613
+ }
614
+ const isDown = (e) => e instanceof GraylingError && ['unavailable', 'closed', 'timeout', 'replaced'].includes(e.code);
615
+ /** Writes the lines to `file` (JSON lines) and counts them. */
616
+ async function writeTexts(file, lines, freshSince, signal) {
617
+ const counts = { user: 0, agent: 0, doc: 0, fresh: 0 };
618
+ // Opened for writing without being made: the host made it, private, and it stays so.
619
+ const fh = await open(file, 'w');
620
+ try {
621
+ let batch = '';
622
+ for await (const l of lines) {
623
+ if (signal.aborted)
624
+ throw new Error('the texts took too long');
625
+ if (!l || (l.kind !== 'user' && l.kind !== 'agent' && l.kind !== 'doc') || typeof l.text !== 'string' || typeof l.ts !== 'number' || !Number.isFinite(l.ts)) {
626
+ throw new Error('a text line needs kind (user, agent or doc), text and ts');
627
+ }
628
+ counts[l.kind]++;
629
+ if (l.kind === 'user' && l.ts > freshSince)
630
+ counts.fresh++;
631
+ batch += JSON.stringify(l) + '\n';
632
+ if (batch.length > 1 << 16) {
633
+ await fh.write(batch);
634
+ batch = '';
635
+ }
636
+ }
637
+ if (batch)
638
+ await fh.write(batch);
639
+ }
640
+ finally {
641
+ await fh.close();
642
+ }
643
+ return counts;
644
+ }
645
+ /** Connects to the engine host, starting the `grayling` program when none answers. Rejects when it cannot (`GraylingError`). */
646
+ export async function connect(o = {}) {
647
+ const g = new Grayling(o);
648
+ if (!o.install || g.hasProgram || o.start === false || o.program === null) {
649
+ await g.open();
650
+ return g;
651
+ }
652
+ const opts = o.install === true ? {} : o.install;
653
+ const install = () => installProgram({ ...opts, env: o.env, home: o.home });
654
+ try {
655
+ await g.open();
656
+ }
657
+ catch (e) {
658
+ if (!(e instanceof GraylingError) || e.code !== 'no-program')
659
+ throw e;
660
+ // No engine runs: the program first, then an engine of this client's own.
661
+ g.setProgram(await install());
662
+ await g.open();
663
+ return g;
664
+ }
665
+ // An engine runs already and answered: the program comes meanwhile, for the day that engine ends.
666
+ void install().then((program) => g.setProgram(program), (e) => void (g.programError = e instanceof Error ? e : new Error(String(e))));
667
+ return g;
668
+ }
669
+ export { GRAYLING_SETTING_KEYS };