kenning-pi 0.0.0 → 0.1.0

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/src/session.ts ADDED
@@ -0,0 +1,557 @@
1
+ import {
2
+ planDelivery,
3
+ type HumanInputMark,
4
+ type Kenning,
5
+ type Message,
6
+ type SessionState,
7
+ } from 'kenning';
8
+ import type {
9
+ ExtensionAPI,
10
+ ExtensionContext,
11
+ } from '@earendil-works/pi-coding-agent';
12
+ import {formatDelivery} from './format.js';
13
+ import {acquire, release} from './shared.js';
14
+ import {inWhereverServer, mayBeTerminalHuman, mayWakeItself} from './mode.js';
15
+ import {
16
+ SPAWN_ENV,
17
+ WAKE_GAP_MS,
18
+ WAKE_LEASE_MS,
19
+ planWake,
20
+ startDetached,
21
+ } from './spawn.js';
22
+
23
+ export const CUSTOM_TYPE = 'kenning';
24
+
25
+ /**
26
+ * How long a host's `kenning:human-input` mark stays valid (ADR 0003, D22). A
27
+ * host emits it immediately before the send, and pi runs `input` handlers first
28
+ * thing in `prompt()` and `sendUserMessage()`: measured mark-to-`input` latency
29
+ * on pi 1.4 is about 0.1 ms (0.51 ms worst of 20 sends). A send that never
30
+ * reaches the `input` handler (another extension returned `handled`, a terminal
31
+ * pi refused it while compacting) must not leave a mark behind that a later
32
+ * identical `extension` input, such as a scheduled `/standup`, would match. 5 s is
33
+ * 10,000 times the worst measured latency, room for a loaded event loop, yet far
34
+ * shorter than any schedule that could repeat the same text.
35
+ *
36
+ * The expiry is the backstop. A host that awaits its send closes the mark
37
+ * itself with `kenning:human-input-end` (D35), which leaves no window at all;
38
+ * a host that cannot (an extension's fire-and-forget `pi.sendUserMessage()`,
39
+ * like the @wherever-dev/pi bridge) relies on this. The real fix is pi
40
+ * carrying an origin on the send: earendil-works/pi#12291.
41
+ */
42
+ export const HUMAN_MARK_TTL_MS = 5_000;
43
+
44
+ type Boundary = {
45
+ entries: {
46
+ type: 'custom_message';
47
+ customType: string;
48
+ content: string;
49
+ display: boolean;
50
+ details: unknown;
51
+ }[];
52
+ continue: boolean;
53
+ };
54
+ export const ROLE_ENTRY = 'kenning-role';
55
+
56
+ type Entry = {
57
+ type: string;
58
+ customType?: string;
59
+ details?: unknown;
60
+ data?: unknown;
61
+ message?: {role?: string; customType?: string; details?: unknown};
62
+ };
63
+
64
+ /**
65
+ * One pi session as kenning sees it: its presence, and the delivery of its
66
+ * mailbox at the moments ADR 0002 allows. pi calls the factory again for every
67
+ * session (startup, /new, /resume, /fork, reload), so this lives per session.
68
+ */
69
+ export class SessionController {
70
+ kenning: Kenning | undefined;
71
+ file: string | undefined;
72
+ private ctx: ExtensionContext | undefined;
73
+ private phase: 'running' | 'settled' = 'settled';
74
+ private uiPrompt = false;
75
+ /** session_register({state: 'waiting-for-human'}) during this run (ADR 0006). */
76
+ declaredWaiting = false;
77
+ /** Inside session_wait or a blocking human_ask: the tool does its own reporting. */
78
+ toolState: SessionState | null = null;
79
+ private humanMarks: (HumanInputMark & {at: number})[] = [];
80
+ /** When the current run started (kenning's clock), for stop requests (D30). */
81
+ private runStartedAt = 0;
82
+ /**
83
+ * Set when a run ends aborted (Esc, or a stop): messages already pending then
84
+ * wait for the next run instead of waking the session at once, or a stop
85
+ * would undo itself (D30). Cleared when a run starts.
86
+ */
87
+ private abortedAt: number | null = null;
88
+ private readonly listener = {onChange: () => this.onChange()};
89
+
90
+ constructor(private readonly pi: ExtensionAPI) {}
91
+
92
+ get active(): boolean {
93
+ return !!this.kenning && !!this.file;
94
+ }
95
+
96
+ /** Ids already in this session's transcript: what "delivered" means (D5). */
97
+ private reconcile(): void {
98
+ if (!this.active || !this.ctx) return;
99
+ const branch = this.ctx.sessionManager.getBranch() as unknown as Entry[];
100
+ const ids: string[] = [];
101
+ for (
102
+ let i = branch.length - 1, seen = 0;
103
+ i >= 0 && seen < 400;
104
+ i--, seen++
105
+ ) {
106
+ const e = branch[i];
107
+ const details =
108
+ e.type === 'custom_message' && e.customType === CUSTOM_TYPE
109
+ ? e.details
110
+ : e.type === 'message' &&
111
+ e.message?.role === 'custom' &&
112
+ e.message.customType === CUSTOM_TYPE
113
+ ? e.message.details
114
+ : undefined;
115
+ const got = (details as {ids?: unknown} | undefined)?.ids;
116
+ if (Array.isArray(got))
117
+ ids.push(...got.filter((x): x is string => typeof x === 'string'));
118
+ }
119
+ if (ids.length) this.kenning!.markDelivered(this.file!, ids);
120
+ }
121
+
122
+ // ------------------------------------------------------------- lifecycle
123
+
124
+ start(ctx: ExtensionContext): void {
125
+ this.ctx = ctx;
126
+ if (process.env.PI_SUBAGENT_CHILD === '1') return; // D7: dormant in milestone 1
127
+ const file = ctx.sessionManager.getSessionFile();
128
+ if (!file) return; // --no-session: nothing to address
129
+ this.kenning = acquire(this.listener);
130
+ this.file = file;
131
+ this.kenning.register({
132
+ sessionFile: file,
133
+ sessionId: ctx.sessionManager.getSessionId(),
134
+ cwd: ctx.cwd,
135
+ });
136
+ this.bindSpawn(file);
137
+ this.reconcile();
138
+ this.reclaimRole(ctx);
139
+ void this.refreshBranch();
140
+ this.onChange();
141
+ }
142
+
143
+ shutdown(): void {
144
+ clearTimeout(this.recheck);
145
+ this.recheck = undefined;
146
+ if (this.kenning && this.file) {
147
+ try {
148
+ // Read everything: the next wake may come at once. Something still
149
+ // pending keeps the gap, so a child that cannot read is retried slowly.
150
+ if (!this.kenning.pendingFor(this.file).length)
151
+ this.kenning.wakeDone(this.file, 0);
152
+ this.kenning.unregister(this.file);
153
+ } catch {}
154
+ release(this.listener);
155
+ }
156
+ this.kenning = undefined;
157
+ this.file = undefined;
158
+ this.ctx = undefined;
159
+ }
160
+
161
+ /**
162
+ * A terminal child kenning spawned binds itself to its spawn, once (D28):
163
+ * this queues the owner's first prompt before `before_agent_start`. The
164
+ * variable is removed so nothing this process starts inherits it.
165
+ */
166
+ private bindSpawn(file: string): void {
167
+ const spawnId = process.env[SPAWN_ENV];
168
+ if (spawnId) {
169
+ delete process.env[SPAWN_ENV];
170
+ try {
171
+ this.kenning!.bindSpawn(spawnId, file);
172
+ } catch (e) {
173
+ this.notify(`kenning: ${(e as Error).message}`, 'warning');
174
+ }
175
+ }
176
+ // Up: a headless wake that started us is done (D29).
177
+ this.kenning!.wakeDone(file, WAKE_GAP_MS);
178
+ }
179
+
180
+ /** A resumed session re-claims the role it held; a fork (a copy in a new file) does not (D9). */
181
+ private reclaimRole(ctx: ExtensionContext): void {
182
+ const flagRole =
183
+ (this.pi.getFlag('kenning-role') as string | undefined) ||
184
+ process.env.KENNING_ROLE;
185
+ const roles = new Set<string>();
186
+ for (const e of ctx.sessionManager.getBranch() as unknown as Entry[]) {
187
+ if (e.type !== 'custom' || e.customType !== ROLE_ENTRY) continue;
188
+ const d = e.data as
189
+ {role?: string; sessionFile?: string; released?: boolean} | undefined;
190
+ if (!d?.role || d.sessionFile !== this.file) continue;
191
+ if (d.released) roles.delete(d.role);
192
+ else roles.add(d.role);
193
+ }
194
+ if (flagRole) roles.add(flagRole);
195
+ // A spawned session's role is part of its ownership record (D23).
196
+ const spawnedAs = this.kenning!.ownership(this.file!)?.role;
197
+ if (spawnedAs) roles.add(spawnedAs);
198
+ for (const role of roles) {
199
+ try {
200
+ const r = this.kenning!.claimRole(this.file!, role);
201
+ if (!r.ok)
202
+ this.notify(
203
+ `kenning: role ${role} is held by a live session (${r.holder}); not taken.`,
204
+ 'warning',
205
+ );
206
+ else if (role === flagRole) this.recordRole(role);
207
+ } catch (e) {
208
+ this.notify(`kenning: ${(e as Error).message}`, 'warning');
209
+ }
210
+ }
211
+ }
212
+
213
+ recordRole(role: string): void {
214
+ this.pi.appendEntry(ROLE_ENTRY, {role, sessionFile: this.file});
215
+ }
216
+
217
+ private async refreshBranch(): Promise<void> {
218
+ if (!this.active || !this.ctx) return;
219
+ try {
220
+ const r = await this.pi.exec(
221
+ 'git',
222
+ ['-C', this.ctx.cwd, 'rev-parse', '--abbrev-ref', 'HEAD'],
223
+ {timeout: 3000},
224
+ );
225
+ if (r.code === 0 && this.active)
226
+ this.kenning!.update(this.file!, {branch: r.stdout.trim() || null});
227
+ } catch {}
228
+ }
229
+
230
+ private setState(state: SessionState): void {
231
+ if (this.active) this.kenning!.update(this.file!, {state});
232
+ }
233
+
234
+ onAgentStart(ctx: ExtensionContext): void {
235
+ this.ctx = ctx;
236
+ this.phase = 'running';
237
+ this.abortedAt = null;
238
+ if (this.active) this.runStartedAt = this.kenning!.now();
239
+ this.setState('running');
240
+ }
241
+
242
+ onSettled(ctx: ExtensionContext): void {
243
+ this.ctx = ctx;
244
+ this.phase = 'settled';
245
+ if (!this.active) return;
246
+ this.reconcile();
247
+ this.setState(this.declaredWaiting ? 'waiting-for-human' : 'idle');
248
+ void this.refreshBranch();
249
+ this.onChange();
250
+ }
251
+
252
+ onUiPrompt(open: boolean): void {
253
+ this.uiPrompt = open;
254
+ if (this.toolState) return;
255
+ this.setState(
256
+ open
257
+ ? 'waiting-for-human'
258
+ : this.phase === 'running'
259
+ ? 'running'
260
+ : 'idle',
261
+ );
262
+ }
263
+
264
+ setToolState(
265
+ state: SessionState | null,
266
+ waitingOn: string | null = null,
267
+ ): void {
268
+ this.toolState = state;
269
+ if (!this.active) return;
270
+ this.kenning!.update(this.file!, {state: state ?? 'running', waitingOn});
271
+ }
272
+
273
+ // ------------------------------------------------------------ human input
274
+
275
+ /** Drop marks older than HUMAN_MARK_TTL_MS. A monotonic clock: a wall-clock jump must not revive one. */
276
+ private dropExpiredMarks(): void {
277
+ const oldest = performance.now() - HUMAN_MARK_TTL_MS;
278
+ this.humanMarks = this.humanMarks.filter((m) => m.at >= oldest);
279
+ }
280
+
281
+ onHumanMark(data: unknown): void {
282
+ this.dropExpiredMarks();
283
+ const m = data as Partial<HumanInputMark> | undefined;
284
+ if (typeof m?.text === 'string' && typeof m.channel === 'string')
285
+ this.humanMarks.push({
286
+ text: m.text,
287
+ channel: m.channel,
288
+ id: typeof m.id === 'string' ? m.id : undefined,
289
+ at: performance.now(),
290
+ });
291
+ if (this.humanMarks.length > 20) this.humanMarks.shift();
292
+ }
293
+
294
+ /**
295
+ * The host's marked send has settled (D35): drop its mark if no input took
296
+ * it. By id when the mark had one, else the oldest open mark with this text.
297
+ * A mark already consumed is not here, so a late end is a no-op.
298
+ */
299
+ onHumanMarkEnd(data: unknown): void {
300
+ this.dropExpiredMarks();
301
+ const e = data as {text?: unknown; id?: unknown} | undefined;
302
+ const i =
303
+ typeof e?.id === 'string'
304
+ ? this.humanMarks.findIndex((m) => m.id === e.id)
305
+ : typeof e?.text === 'string'
306
+ ? this.humanMarks.findIndex((m) => m.text === e.text && !m.id)
307
+ : -1;
308
+ if (i >= 0) this.humanMarks.splice(i, 1);
309
+ }
310
+
311
+ /** ADR 0003: TUI typing, or an input a host marked as human just before sending it. */
312
+ onInput(text: string, source: string): void {
313
+ if (!this.active) return;
314
+ if (source === 'interactive') {
315
+ if (this.typedAtTerminal())
316
+ this.kenning!.recordHumanTurn(this.file!, {text, channel: 'terminal'});
317
+ return;
318
+ }
319
+ if (source !== 'extension') return;
320
+ this.dropExpiredMarks();
321
+ const i = this.humanMarks.findIndex((m) => m.text === text);
322
+ if (i < 0) return;
323
+ const [mark] = this.humanMarks.splice(i, 1);
324
+ this.kenning!.recordHumanTurn(this.file!, {text, channel: mark.channel});
325
+ }
326
+
327
+ /**
328
+ * pi reports `pi -p TEXT` as source `interactive` too (print mode calls
329
+ * `prompt()` with the default source), so outside the TUI the source alone
330
+ * proves nothing: a headless child kenning spawned, a cron job or an agent's
331
+ * bash running `pi -p "I approve"` would all count as the human (D27). Outside
332
+ * the TUI it is the human only under the CLI's rule (D2): a terminal on stdin
333
+ * and no agent session around it. Inside wherever, never (D36).
334
+ */
335
+ private typedAtTerminal(): boolean {
336
+ return mayBeTerminalHuman({
337
+ mode: this.ctx?.mode ?? 'print',
338
+ inWhereverServer: inWhereverServer(),
339
+ stdinIsTTY: !!process.stdin.isTTY,
340
+ inAgentSession: !!process.env.PI_SESSION_FILE,
341
+ });
342
+ }
343
+
344
+ // ---------------------------------------------------------------- delivery
345
+
346
+ /** Anything changed in the database: maybe stop, wake a child, wake, update the notices. */
347
+ private onChange(): void {
348
+ if (!this.active || !this.ctx) return;
349
+ try {
350
+ this.handleStops();
351
+ this.wakeOwned();
352
+ this.refreshNotices();
353
+ // A real `pi -p` run never wakes itself (D29); a print-mode session in
354
+ // wherever's server does, or nothing would deliver to it (D36).
355
+ if (
356
+ !mayWakeItself({
357
+ mode: this.ctx.mode,
358
+ inWhereverServer: inWhereverServer(),
359
+ })
360
+ )
361
+ return;
362
+ if (this.phase !== 'settled' || !this.ctx.isIdle()) return;
363
+ const since = this.abortedAt ?? -Infinity;
364
+ const pending = this.kenning!.pendingFor(this.file!);
365
+ if (!pending.some((m) => m.createdAt > since)) return;
366
+ const presence = this.kenning!.presence(this.file!);
367
+ const plan = planDelivery(
368
+ {
369
+ phase: 'settled',
370
+ declared: presence?.state ?? 'idle',
371
+ uiPrompt: this.uiPrompt,
372
+ editorBusy: this.editorBusy(),
373
+ wake: presence?.wake ?? true,
374
+ },
375
+ {urgent: pending.some((m) => m.urgent)},
376
+ );
377
+ if (plan === 'wake') this.wake();
378
+ } catch (e) {
379
+ console.error('[kenning] delivery failed:', e);
380
+ }
381
+ }
382
+
383
+ /**
384
+ * D30: a stop request for this session aborts the run that was going when it
385
+ * was made, and only that; one made while settled, or before this run began,
386
+ * is answered `not-running`. A read per poll; the write only when there is one.
387
+ */
388
+ private handleStops(): void {
389
+ const k = this.kenning!;
390
+ for (const req of k.openStops(this.file!)) {
391
+ const running = this.phase === 'running' && this.runStartedAt <= req.at;
392
+ if (running) this.ctx!.abort();
393
+ k.settleStop(req.id, running ? 'stopped' : 'not-running');
394
+ }
395
+ }
396
+
397
+ /**
398
+ * D29: this session's headless children are `pi -p` runs that exit when
399
+ * done. When one is not running and has messages that arrived after its last
400
+ * stop, start `pi --session <path> -p` for it, under a lease so no two polls
401
+ * or processes start it twice. Only the owner wakes a child.
402
+ */
403
+ private wakeOwned(): void {
404
+ const k = this.kenning!;
405
+ for (const o of k.wakeCandidates(this.file!)) {
406
+ const child = o.session!;
407
+ if (k.isLive(child)) continue;
408
+ const lease = k.leaseWake(child, WAKE_LEASE_MS);
409
+ if (!lease.ok) {
410
+ // Nothing may change in the database when the lease lapses: look again then.
411
+ if (lease.until) this.recheckAt(lease.until);
412
+ continue;
413
+ }
414
+ startDetached(
415
+ planWake({env: process.env, sessionFile: child, folder: o.folder}),
416
+ o.id,
417
+ ).catch((e) =>
418
+ this.notify(
419
+ `kenning: could not wake ${child}: ${(e as Error).message}`,
420
+ 'warning',
421
+ ),
422
+ );
423
+ }
424
+ }
425
+
426
+ private recheck: ReturnType<typeof setTimeout> | undefined;
427
+ private recheckAt(at: number): void {
428
+ if (this.recheck) return;
429
+ const ms = Math.max(at - this.kenning!.now(), 0) + 50;
430
+ this.recheck = setTimeout(() => {
431
+ this.recheck = undefined;
432
+ this.onChange();
433
+ }, ms);
434
+ this.recheck.unref();
435
+ }
436
+
437
+ private editorBusy(): boolean {
438
+ if (!this.ctx || this.ctx.mode !== 'tui') return false;
439
+ try {
440
+ return this.ctx.ui.getEditorText().trim().length > 0;
441
+ } catch {
442
+ return false;
443
+ }
444
+ }
445
+
446
+ /** Claim what can be delivered now, after making sure nothing is claimed twice. */
447
+ private take(filter: (m: Message) => boolean = () => true): Message[] {
448
+ if (!this.active) return [];
449
+ this.reconcile();
450
+ const ids = this.kenning!.pendingFor(this.file!)
451
+ .filter(filter)
452
+ .map((m) => m.id);
453
+ return ids.length ? this.kenning!.claim(this.file!, {ids}) : [];
454
+ }
455
+
456
+ private payload(messages: Message[], woken: boolean) {
457
+ return {
458
+ customType: CUSTOM_TYPE as string,
459
+ content: formatDelivery(messages, {woken}),
460
+ display: true,
461
+ details: {
462
+ ids: messages.map((m) => m.id),
463
+ from: messages.map((m) => m.fromLabel),
464
+ origins: messages.map((m) => m.origin),
465
+ },
466
+ };
467
+ }
468
+
469
+ /** Deliver now into an idle session: it starts a turn. */
470
+ wake(opts: {woken?: boolean} = {}): boolean {
471
+ const messages = this.take();
472
+ if (!messages.length) return false;
473
+ this.phase = 'running';
474
+ this.pi.sendMessage(this.payload(messages, opts.woken ?? true), {
475
+ triggerTurn: true,
476
+ });
477
+ return true;
478
+ }
479
+
480
+ /** before_agent_start: attach everything held to the run the human (or anyone) just started. */
481
+ beforeAgentStart(): ReturnType<SessionController['payload']> | undefined {
482
+ this.declaredWaiting = false;
483
+ const messages = this.take();
484
+ return messages.length ? this.payload(messages, false) : undefined;
485
+ }
486
+
487
+ /** turn_end: urgent messages, and everything held while a dialog was open. */
488
+ atTurnEnd(aborted = false): Boundary | undefined {
489
+ if (aborted) return undefined; // a stopped turn must not be continued (D30)
490
+ const messages = this.take((m) => m.urgent || this.uiPrompt);
491
+ if (!messages.length) return undefined;
492
+ return {
493
+ entries: [
494
+ {type: 'custom_message' as const, ...this.payload(messages, false)},
495
+ ],
496
+ continue: true,
497
+ };
498
+ }
499
+
500
+ /** agent_before_settle: everything that arrived during the run, read before stopping. */
501
+ atSettle(outcome?: string): Boundary | undefined {
502
+ if (outcome === 'aborted') {
503
+ // Esc or a stop: continuing would undo it. What is pending waits (D30).
504
+ this.abortedAt = this.active ? this.kenning!.now() : Date.now();
505
+ return undefined;
506
+ }
507
+ if (this.declaredWaiting) return undefined; // it just said it waits for the human: hold
508
+ const messages = this.take();
509
+ if (!messages.length) return undefined;
510
+ return {
511
+ entries: [
512
+ {type: 'custom_message' as const, ...this.payload(messages, false)},
513
+ ],
514
+ continue: true,
515
+ };
516
+ }
517
+
518
+ onTurnStart(): void {
519
+ this.reconcile();
520
+ }
521
+
522
+ onCustomMessageEnd(): void {
523
+ this.reconcile();
524
+ this.refreshNotices();
525
+ }
526
+
527
+ // ----------------------------------------------------------------- notices
528
+
529
+ private lastWidget = '';
530
+ private lastBadge = '';
531
+
532
+ /** A widget for messages held for the human, and an inbox badge (D3, D13). */
533
+ refreshNotices(): void {
534
+ if (!this.active || !this.ctx || !this.ctx.hasUI || this.ctx.mode !== 'tui')
535
+ return;
536
+ const held =
537
+ this.phase === 'settled' ? this.kenning!.pendingFor(this.file!) : [];
538
+ const widget = held.length
539
+ ? `kenning: ${held.length} message${held.length === 1 ? '' : 's'} waiting (from ${[...new Set(held.map((m) => m.fromLabel))].join(', ')}). They join your next message; /kenning deliver reads them now.`
540
+ : '';
541
+ if (widget !== this.lastWidget) {
542
+ this.ctx.ui.setWidget('kenning', widget ? [widget] : undefined);
543
+ this.lastWidget = widget;
544
+ }
545
+ const items = this.kenning!.inbox().length;
546
+ const badge = items ? `kenning: ${items} for you (/kenning inbox)` : '';
547
+ if (badge !== this.lastBadge) {
548
+ this.ctx.ui.setStatus('kenning', badge || undefined);
549
+ this.lastBadge = badge;
550
+ }
551
+ }
552
+
553
+ notify(text: string, level: 'info' | 'warning' | 'error' = 'info'): void {
554
+ if (this.ctx?.hasUI) this.ctx.ui.notify(text, level);
555
+ else console.error(text);
556
+ }
557
+ }
package/src/shared.ts ADDED
@@ -0,0 +1,61 @@
1
+ import {
2
+ openKenning,
3
+ silenceSqliteWarning,
4
+ watchChanges,
5
+ type Kenning,
6
+ } from 'kenning';
7
+
8
+ /**
9
+ * One database connection and one change watcher per PROCESS, shared by every
10
+ * session in it (D6). A terminal pi has one session at a time; wherever runs many
11
+ * in one process, and one poller per session there would multiply for nothing.
12
+ * Started by the first session_start, stopped by the last session_shutdown, as
13
+ * the pi docs require (never in the factory: some invocations load extensions
14
+ * without starting a session).
15
+ */
16
+ export interface Listener {
17
+ onChange(): void;
18
+ }
19
+
20
+ interface Shared {
21
+ kenning: Kenning;
22
+ listeners: Set<Listener>;
23
+ stop(): void;
24
+ }
25
+
26
+ let shared: Shared | undefined;
27
+
28
+ export function acquire(listener: Listener): Kenning {
29
+ if (!shared) {
30
+ silenceSqliteWarning();
31
+ const kenning = openKenning();
32
+ kenning.pruneIfDue();
33
+ const listeners = new Set<Listener>();
34
+ const watcher = watchChanges(
35
+ kenning,
36
+ () => {
37
+ for (const l of listeners) l.onChange();
38
+ },
39
+ {intervalMs: Number(process.env.KENNING_POLL_MS) || 1000},
40
+ );
41
+ shared = {
42
+ kenning,
43
+ listeners,
44
+ stop() {
45
+ watcher.stop();
46
+ kenning.close();
47
+ },
48
+ };
49
+ }
50
+ shared.listeners.add(listener);
51
+ return shared.kenning;
52
+ }
53
+
54
+ export function release(listener: Listener): void {
55
+ if (!shared) return;
56
+ shared.listeners.delete(listener);
57
+ if (shared.listeners.size === 0) {
58
+ shared.stop();
59
+ shared = undefined;
60
+ }
61
+ }