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