shipmates 0.0.0 → 0.3.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.
Files changed (69) hide show
  1. package/LICENSE +661 -0
  2. package/dist/cli-run.d.ts +9 -0
  3. package/dist/cli-run.d.ts.map +1 -0
  4. package/dist/cli-run.js +237 -0
  5. package/dist/cli-run.js.map +1 -0
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +11 -0
  9. package/dist/cli.js.map +1 -0
  10. package/dist/delivery.d.ts +37 -0
  11. package/dist/delivery.d.ts.map +1 -0
  12. package/dist/delivery.js +13 -0
  13. package/dist/delivery.js.map +1 -0
  14. package/dist/host.d.ts +132 -0
  15. package/dist/host.d.ts.map +1 -0
  16. package/dist/host.js +66 -0
  17. package/dist/host.js.map +1 -0
  18. package/dist/ids.d.ts +3 -0
  19. package/dist/ids.d.ts.map +1 -0
  20. package/dist/ids.js +6 -0
  21. package/dist/ids.js.map +1 -0
  22. package/dist/index.d.ts +17 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +11 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/liveness.d.ts +25 -0
  27. package/dist/liveness.d.ts.map +1 -0
  28. package/dist/liveness.js +75 -0
  29. package/dist/liveness.js.map +1 -0
  30. package/dist/quiet.d.ts +7 -0
  31. package/dist/quiet.d.ts.map +1 -0
  32. package/dist/quiet.js +19 -0
  33. package/dist/quiet.js.map +1 -0
  34. package/dist/shipmates.d.ts +440 -0
  35. package/dist/shipmates.d.ts.map +1 -0
  36. package/dist/shipmates.js +1177 -0
  37. package/dist/shipmates.js.map +1 -0
  38. package/dist/store.d.ts +19 -0
  39. package/dist/store.d.ts.map +1 -0
  40. package/dist/store.js +236 -0
  41. package/dist/store.js.map +1 -0
  42. package/dist/tail.d.ts +27 -0
  43. package/dist/tail.d.ts.map +1 -0
  44. package/dist/tail.js +127 -0
  45. package/dist/tail.js.map +1 -0
  46. package/dist/types.d.ts +141 -0
  47. package/dist/types.d.ts.map +1 -0
  48. package/dist/types.js +16 -0
  49. package/dist/types.js.map +1 -0
  50. package/dist/watch.d.ts +13 -0
  51. package/dist/watch.d.ts.map +1 -0
  52. package/dist/watch.js +30 -0
  53. package/dist/watch.js.map +1 -0
  54. package/package.json +50 -13
  55. package/src/cli-run.ts +263 -0
  56. package/src/cli.ts +11 -0
  57. package/src/delivery.ts +49 -0
  58. package/src/host.ts +161 -0
  59. package/src/ids.ts +6 -0
  60. package/src/index.ts +44 -0
  61. package/src/liveness.ts +86 -0
  62. package/src/quiet.ts +22 -0
  63. package/src/shipmates.ts +1745 -0
  64. package/src/store.ts +252 -0
  65. package/src/tail.ts +143 -0
  66. package/src/types.ts +151 -0
  67. package/src/watch.ts +32 -0
  68. package/.npm-publish.log +0 -0
  69. package/README.md +0 -5
@@ -0,0 +1,1745 @@
1
+ import fs from 'node:fs';
2
+ import {defaultStateDir, openDb, write, type DB} from './store.js';
3
+ import {OsProbe, type ProcessIdentity, type ProcessProbe} from './liveness.js';
4
+ import {
5
+ ShipmatesError,
6
+ type ArchiveMark,
7
+ type AttentionItem,
8
+ type Message,
9
+ type Ownership,
10
+ type SpawnVia,
11
+ type StopRequest,
12
+ type Origin,
13
+ type Presence,
14
+ type Question,
15
+ type Relay,
16
+ type SessionState,
17
+ } from './types.js';
18
+ import {newId} from './ids.js';
19
+
20
+ export interface ShipmatesOptions {
21
+ stateDir?: string;
22
+ probe?: ProcessProbe;
23
+ now?: () => number;
24
+ }
25
+
26
+ export interface RegisterInput {
27
+ sessionFile: string;
28
+ sessionId?: string | null;
29
+ cwd?: string | null;
30
+ branch?: string | null;
31
+ }
32
+
33
+ export interface PresencePatch {
34
+ state?: SessionState;
35
+ status?: string | null;
36
+ refs?: string[];
37
+ waitingOn?: string | null;
38
+ branch?: string | null;
39
+ cwd?: string | null;
40
+ wake?: boolean;
41
+ }
42
+
43
+ export interface ListFilter {
44
+ cwd?: string;
45
+ role?: string;
46
+ state?: SessionState;
47
+ includeGone?: boolean;
48
+ }
49
+
50
+ type PresenceRow = {
51
+ session_file: string;
52
+ session_id: string | null;
53
+ cwd: string | null;
54
+ branch: string | null;
55
+ state: SessionState;
56
+ status: string | null;
57
+ refs: string | null;
58
+ waiting_on: string | null;
59
+ wake: number;
60
+ pid: number;
61
+ start_time: string | null;
62
+ boot_id: string | null;
63
+ host: string | null;
64
+ updated_at: number;
65
+ settled_at: number | null;
66
+ };
67
+
68
+ /** D14: message text is short; content stays in git and messages point at it. */
69
+ const DAY = 86_400_000;
70
+
71
+ export const MAX_TEXT_BYTES = 8 * 1024;
72
+
73
+ /**
74
+ * D24: an archive or delete cascade can be undone, as one batch, for 7 days. A
75
+ * cascade from an orchestrator takes every lane with it, and an accidental one
76
+ * is often noticed only after a weekend; until the window ends a host must not
77
+ * remove a deleted session's transcript. Rejected: a seconds-long "undo" toast
78
+ * (a cascade is noticed later than that) and 24 hours (shorter than a weekend).
79
+ */
80
+ export const ARCHIVE_UNDO_MS = 7 * DAY;
81
+
82
+ export interface SpawnInput {
83
+ owner: string;
84
+ folder: string;
85
+ /** The first prompt: delivered once, as a `spawn` message from the owner (D28). */
86
+ prompt?: string | null;
87
+ role?: string | null;
88
+ via: SpawnVia;
89
+ detail?: Record<string, unknown>;
90
+ }
91
+
92
+ type OwnershipRow = {
93
+ id: string;
94
+ session_file: string | null;
95
+ owner: string;
96
+ folder: string;
97
+ role: string | null;
98
+ via: SpawnVia;
99
+ detail: string | null;
100
+ prompt: string | null;
101
+ created_at: number;
102
+ bound_at: number | null;
103
+ wake_until: number | null;
104
+ };
105
+
106
+ type ArchiveRow = {
107
+ session_file: string;
108
+ kind: ArchiveMark['kind'];
109
+ batch: string;
110
+ by_label: string;
111
+ at: number;
112
+ };
113
+
114
+ type StopRow = {
115
+ id: string;
116
+ session_file: string;
117
+ by_session: string | null;
118
+ by_label: string;
119
+ at: number;
120
+ handled_at: number | null;
121
+ outcome: StopRequest['outcome'];
122
+ };
123
+
124
+ const toArchive = (r: ArchiveRow): ArchiveMark => ({
125
+ session: r.session_file,
126
+ kind: r.kind,
127
+ batch: r.batch,
128
+ by: r.by_label,
129
+ at: r.at,
130
+ undoUntil: r.at + ARCHIVE_UNDO_MS,
131
+ });
132
+
133
+ const toStop = (r: StopRow): StopRequest => ({
134
+ id: r.id,
135
+ session: r.session_file,
136
+ by: r.by_session,
137
+ byLabel: r.by_label,
138
+ at: r.at,
139
+ handledAt: r.handled_at,
140
+ outcome: r.outcome,
141
+ });
142
+
143
+ export interface SendInput {
144
+ /** The sending session, or null for a human at the CLI. */
145
+ from: string | null;
146
+ fromLabel?: string;
147
+ to: string;
148
+ text: string;
149
+ kind?: 'tell' | 'ask';
150
+ origin?: Origin;
151
+ relay?: Relay | null;
152
+ requestId?: string | null;
153
+ urgent?: boolean;
154
+ }
155
+
156
+ export interface SendResult {
157
+ message: Message;
158
+ question: Question | null;
159
+ duplicate: boolean;
160
+ /** The live session the message goes to, or null when nobody holds the role or the session is gone. */
161
+ target: Presence | null;
162
+ openQuestions: Question[];
163
+ }
164
+
165
+ type QuestionRow = {
166
+ id: string;
167
+ asker_session: string | null;
168
+ asker_label: string;
169
+ message_id: string;
170
+ to_kind: 'session' | 'role';
171
+ to_target: string;
172
+ text: string;
173
+ state: Question['state'];
174
+ answer: string | null;
175
+ answer_origin: Origin | null;
176
+ answer_relay: string | null;
177
+ answered_by: string | null;
178
+ created_at: number;
179
+ };
180
+
181
+ function toQuestion(r: QuestionRow): Question {
182
+ return {
183
+ id: r.id,
184
+ asker: r.asker_session,
185
+ askerLabel: r.asker_label,
186
+ messageId: r.message_id,
187
+ to: {kind: r.to_kind, target: r.to_target},
188
+ text: r.text,
189
+ state: r.state,
190
+ answer: r.answer,
191
+ answerOrigin: r.answer_origin,
192
+ answerRelay: r.answer_relay ? (JSON.parse(r.answer_relay) as Relay) : null,
193
+ answeredBy: r.answered_by,
194
+ createdAt: r.created_at,
195
+ };
196
+ }
197
+
198
+ type ItemRow = {
199
+ id: string;
200
+ session_file: string;
201
+ question: string;
202
+ options: string | null;
203
+ blocking: number;
204
+ on_behalf_of: string | null;
205
+ state: AttentionItem['state'];
206
+ answer: string | null;
207
+ answer_channel: string | null;
208
+ created_at: number;
209
+ finished_at: number | null;
210
+ };
211
+
212
+ function toItem(r: ItemRow): AttentionItem {
213
+ return {
214
+ id: r.id,
215
+ session: r.session_file,
216
+ question: r.question,
217
+ options: r.options ? (JSON.parse(r.options) as string[]) : null,
218
+ blocking: r.blocking === 1,
219
+ onBehalfOf: r.on_behalf_of ? (JSON.parse(r.on_behalf_of) as string[]) : [],
220
+ state: r.state,
221
+ answer: r.answer,
222
+ answerChannel: r.answer_channel,
223
+ createdAt: r.created_at,
224
+ finishedAt: r.finished_at,
225
+ };
226
+ }
227
+
228
+ export type WaitStatus =
229
+ | {status: 'answered'; question: Question}
230
+ | {status: 'withdrawn'; question: Question}
231
+ | {status: 'asked'; question: Question; questions: Question[]}
232
+ | {status: 'settled'; question: Question; target: Presence};
233
+
234
+ export type Resolved = {
235
+ kind: 'session' | 'role';
236
+ target: string;
237
+ session: string | null;
238
+ };
239
+
240
+ /** D8: lower-case words joined by `._:/-`, e.g. `template-tree/push` or `orchestrator:template-tree`. */
241
+ const ROLE_RE = /^[a-z0-9][a-z0-9._:/-]{0,79}$/;
242
+
243
+ type MessageRow = {
244
+ id: string;
245
+ from_session: string | null;
246
+ from_label: string;
247
+ to_kind: 'session' | 'role';
248
+ to_target: string;
249
+ kind: Message['kind'];
250
+ question_id: string | null;
251
+ item_id: string | null;
252
+ text: string;
253
+ origin: Origin;
254
+ relay: string | null;
255
+ urgent: number;
256
+ state: Message['state'];
257
+ superseded_by: string | null;
258
+ delivered_to: string | null;
259
+ claim_pid: number | null;
260
+ claim_start: string | null;
261
+ claim_until: number | null;
262
+ created_at: number;
263
+ };
264
+
265
+ export class Shipmates {
266
+ readonly db: DB;
267
+ readonly probe: ProcessProbe;
268
+ readonly now: () => number;
269
+ private localWrites = 0;
270
+
271
+ constructor(opts: ShipmatesOptions = {}) {
272
+ this.db = openDb(opts.stateDir ?? defaultStateDir());
273
+ this.probe = opts.probe ?? new OsProbe();
274
+ this.now = opts.now ?? Date.now;
275
+ }
276
+
277
+ close(): void {
278
+ this.db.close();
279
+ }
280
+
281
+ /** Changes whenever any connection (this one included) committed a write. */
282
+ changeToken(): string {
283
+ const row = this.db.prepare('PRAGMA data_version').get() as {
284
+ data_version: number;
285
+ };
286
+ return `${row.data_version}:${this.localWrites}`;
287
+ }
288
+
289
+ protected tx<T>(fn: () => T): T {
290
+ const out = write(this.db, fn);
291
+ this.localWrites++;
292
+ return out;
293
+ }
294
+
295
+ // ---------------------------------------------------------------- presence
296
+
297
+ register(input: RegisterInput): Presence {
298
+ const me = this.probe.self();
299
+ const t = this.now();
300
+ this.tx(() => {
301
+ this.db
302
+ .prepare(
303
+ `INSERT INTO presence(session_file, session_id, cwd, branch, state, pid, start_time, boot_id, host, registered_at, updated_at)
304
+ VALUES(?, ?, ?, ?, 'idle', ?, ?, ?, ?, ?, ?)
305
+ ON CONFLICT(session_file) DO UPDATE SET
306
+ session_id = excluded.session_id, cwd = excluded.cwd,
307
+ branch = COALESCE(excluded.branch, presence.branch),
308
+ pid = excluded.pid, start_time = excluded.start_time, boot_id = excluded.boot_id,
309
+ host = excluded.host, updated_at = excluded.updated_at,
310
+ state = CASE WHEN presence.pid = excluded.pid THEN presence.state ELSE 'idle' END`,
311
+ )
312
+ .run(
313
+ input.sessionFile,
314
+ input.sessionId ?? null,
315
+ input.cwd ?? null,
316
+ input.branch ?? null,
317
+ me.pid,
318
+ me.startTime,
319
+ me.bootId,
320
+ me.host,
321
+ t,
322
+ t,
323
+ );
324
+ });
325
+ return this.presence(input.sessionFile)!;
326
+ }
327
+
328
+ update(sessionFile: string, patch: PresencePatch): void {
329
+ const sets: string[] = [];
330
+ const vals: (string | number | null)[] = [];
331
+ const put = (col: string, v: string | number | null) => {
332
+ sets.push(`${col} = ?`);
333
+ vals.push(v);
334
+ };
335
+ if (patch.state !== undefined) {
336
+ put('state', patch.state);
337
+ if (patch.state === 'idle' || patch.state === 'waiting-for-human')
338
+ put('settled_at', this.now());
339
+ }
340
+ if (patch.status !== undefined) put('status', patch.status);
341
+ if (patch.refs !== undefined) put('refs', JSON.stringify(patch.refs));
342
+ if (patch.waitingOn !== undefined) put('waiting_on', patch.waitingOn);
343
+ if (patch.branch !== undefined) put('branch', patch.branch);
344
+ if (patch.cwd !== undefined) put('cwd', patch.cwd);
345
+ if (patch.wake !== undefined) put('wake', patch.wake ? 1 : 0);
346
+ put('updated_at', this.now());
347
+ this.tx(() => {
348
+ this.db
349
+ .prepare(
350
+ `UPDATE presence SET ${sets.join(', ')} WHERE session_file = ?`,
351
+ )
352
+ .run(...vals, sessionFile);
353
+ });
354
+ }
355
+
356
+ unregister(sessionFile: string): void {
357
+ const me = this.probe.self();
358
+ this.tx(() => {
359
+ // Only the process that registered it may remove it: the same file can be
360
+ // re-opened by another process (a resume elsewhere) before this one exits.
361
+ this.db
362
+ .prepare(`DELETE FROM presence WHERE session_file = ? AND pid = ?`)
363
+ .run(sessionFile, me.pid);
364
+ });
365
+ }
366
+
367
+ presence(sessionFile: string): Presence | null {
368
+ const row = this.db
369
+ .prepare(`SELECT * FROM presence WHERE session_file = ?`)
370
+ .get(sessionFile) as PresenceRow | undefined;
371
+ return row ? this.toPresence(row) : null;
372
+ }
373
+
374
+ isLive(sessionFile: string): boolean {
375
+ return this.presence(sessionFile)?.live ?? false;
376
+ }
377
+
378
+ list(filter: ListFilter = {}): Presence[] {
379
+ const rows = this.db
380
+ .prepare(`SELECT * FROM presence ORDER BY updated_at DESC`)
381
+ .all() as PresenceRow[];
382
+ return rows
383
+ .map((r) => this.toPresence(r))
384
+ .filter((p) => filter.includeGone || p.live)
385
+ .filter((p) => !filter.cwd || p.cwd === filter.cwd)
386
+ .filter((p) => !filter.state || p.state === filter.state)
387
+ .filter((p) => !filter.role || p.roles.includes(filter.role));
388
+ }
389
+
390
+ // ------------------------------------------------------------------- roles
391
+
392
+ claimRole(
393
+ sessionFile: string,
394
+ role: string,
395
+ opts: {takeover?: boolean} = {},
396
+ ): {ok: true; previous: string | null} | {ok: false; holder: string} {
397
+ if (!ROLE_RE.test(role))
398
+ throw new ShipmatesError(
399
+ `invalid role ${JSON.stringify(role)}: use lower-case words joined by . _ : / - (e.g. template-tree/push)`,
400
+ 'bad-role',
401
+ );
402
+ return this.tx(() => {
403
+ const row = this.db
404
+ .prepare(`SELECT session_file FROM role WHERE role = ?`)
405
+ .get(role) as {session_file: string} | undefined;
406
+ const holder = row?.session_file ?? null;
407
+ if (holder === sessionFile) return {ok: true as const, previous: null};
408
+ if (holder && this.isLive(holder) && !opts.takeover)
409
+ return {ok: false as const, holder};
410
+ this.db
411
+ .prepare(
412
+ `INSERT INTO role(role, session_file, claimed_at) VALUES(?, ?, ?)
413
+ ON CONFLICT(role) DO UPDATE SET session_file = excluded.session_file, claimed_at = excluded.claimed_at`,
414
+ )
415
+ .run(role, sessionFile, this.now());
416
+ if (holder && this.isLive(holder))
417
+ this.insertMessage({
418
+ from: sessionFile,
419
+ fromLabel: this.labelOf(sessionFile),
420
+ to: {kind: 'session', target: holder},
421
+ kind: 'notice',
422
+ text: `shipmates: the role ${role} was taken over by ${sessionFile}. You no longer hold it; messages to ${role} now go there.`,
423
+ origin: 'agent',
424
+ });
425
+ return {ok: true as const, previous: holder};
426
+ });
427
+ }
428
+
429
+ releaseRole(sessionFile: string, role: string): void {
430
+ this.tx(() => {
431
+ this.db
432
+ .prepare(`DELETE FROM role WHERE role = ? AND session_file = ?`)
433
+ .run(role, sessionFile);
434
+ });
435
+ }
436
+
437
+ roleHolder(role: string): string | null {
438
+ const row = this.db
439
+ .prepare(`SELECT session_file FROM role WHERE role = ?`)
440
+ .get(role) as {session_file: string} | undefined;
441
+ return row?.session_file ?? null;
442
+ }
443
+
444
+ /** D15: a `.jsonl` string is a session; else an exact role; else a unique session-id prefix. */
445
+ resolve(target: string): Resolved {
446
+ const t = target.trim();
447
+ if (t.endsWith('.jsonl')) return {kind: 'session', target: t, session: t};
448
+ const holder = this.roleHolder(t);
449
+ if (holder) return {kind: 'role', target: t, session: holder};
450
+ const matches = this.db
451
+ .prepare(
452
+ `SELECT session_file FROM presence WHERE session_id LIKE ? ESCAPE '\\'`,
453
+ )
454
+ .all(t.replace(/[\\%_]/g, (c) => '\\' + c) + '%') as {
455
+ session_file: string;
456
+ }[];
457
+ if (matches.length === 1)
458
+ return {
459
+ kind: 'session',
460
+ target: matches[0].session_file,
461
+ session: matches[0].session_file,
462
+ };
463
+ if (matches.length > 1)
464
+ throw new ShipmatesError(
465
+ `ambiguous target ${JSON.stringify(t)}: ${matches.map((m) => m.session_file).join(', ')}`,
466
+ 'ambiguous',
467
+ matches.map((m) => m.session_file),
468
+ );
469
+ // A role nobody holds yet still resolves (the message waits for its next
470
+ // holder), but only when it looks like one, so a typo is not silently queued.
471
+ if (ROLE_RE.test(t) && /[/:]/.test(t))
472
+ return {kind: 'role', target: t, session: null};
473
+ throw new ShipmatesError(
474
+ `no session or role matches ${JSON.stringify(t)}`,
475
+ 'not-found',
476
+ );
477
+ }
478
+
479
+ // ----------------------------------------------------------------- mailbox
480
+
481
+ /**
482
+ * Send a message. The result carries the target's presence and open
483
+ * questions, so the sender sees what it is talking to (read before send).
484
+ * `requestId` makes a retried send a no-op (exactly once per sender).
485
+ */
486
+ send(input: SendInput): SendResult {
487
+ const text = input.text;
488
+ if (!text.trim()) throw new ShipmatesError('a message needs text', 'empty');
489
+ if (Buffer.byteLength(text) > MAX_TEXT_BYTES)
490
+ throw new ShipmatesError(
491
+ `message is over 8 KB (${Buffer.byteLength(text)} bytes): put the content in git (a branch, a commit, a plan section) and send a pointer to it`,
492
+ 'too-large',
493
+ );
494
+ const origin = input.origin ?? (input.from ? 'agent' : 'human');
495
+ if (origin === 'human-relayed' && !input.relay)
496
+ throw new ShipmatesError(
497
+ 'a human-relayed message must carry the relay (the human words and where they were said)',
498
+ 'no-relay',
499
+ );
500
+ const resolved = this.resolve(input.to);
501
+ const fromLabel = input.fromLabel ?? this.labelOf(input.from);
502
+ const kind = input.kind ?? 'tell';
503
+ const out = this.tx(() => {
504
+ if (input.requestId) {
505
+ const dup = this.db
506
+ .prepare(
507
+ `SELECT * FROM message WHERE from_label = ? AND request_id = ?`,
508
+ )
509
+ .get(fromLabel, input.requestId) as MessageRow | undefined;
510
+ if (dup) return {id: dup.id, duplicate: true};
511
+ }
512
+ const questionId = kind === 'ask' ? newId('q') : null;
513
+ const id = this.insertMessage({
514
+ from: input.from,
515
+ fromLabel,
516
+ to: {kind: resolved.kind, target: resolved.target},
517
+ kind,
518
+ text,
519
+ origin,
520
+ relay: input.relay ?? null,
521
+ questionId,
522
+ requestId: input.requestId ?? null,
523
+ urgent: input.urgent,
524
+ });
525
+ if (questionId)
526
+ this.db
527
+ .prepare(
528
+ `INSERT INTO question(id, asker_session, asker_label, message_id, to_kind, to_target, text, created_at)
529
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?)`,
530
+ )
531
+ .run(
532
+ questionId,
533
+ input.from,
534
+ fromLabel,
535
+ id,
536
+ resolved.kind,
537
+ resolved.target,
538
+ text,
539
+ this.now(),
540
+ );
541
+ return {id, duplicate: false};
542
+ });
543
+ const message = this.message(out.id)!;
544
+ const session =
545
+ resolved.kind === 'role'
546
+ ? this.roleHolder(resolved.target)
547
+ : resolved.session;
548
+ const target = session ? this.presence(session) : null;
549
+ return {
550
+ message,
551
+ question: message.questionId ? this.question(message.questionId) : null,
552
+ duplicate: out.duplicate,
553
+ target: target && target.live ? target : null,
554
+ openQuestions: session ? this.openQuestionsTo(session) : [],
555
+ };
556
+ }
557
+
558
+ /**
559
+ * Claim this session's deliverable messages for this process. A message is
560
+ * claimed by one process at a time (the same session file can be open in two),
561
+ * and a claim lapses when its process dies or its lease expires.
562
+ */
563
+ claim(
564
+ sessionFile: string,
565
+ opts: {leaseMs?: number; ids?: string[]} = {},
566
+ ): Message[] {
567
+ const me = this.probe.self();
568
+ const until = this.now() + (opts.leaseMs ?? 60_000);
569
+ // The poller calls this every second in every process: take the write lock
570
+ // only when there is something to claim, or idle processes starve writers
571
+ // (measured: four processes claiming in a loop pushed a writer past
572
+ // busy_timeout).
573
+ const claimable = (m: MessageRow) =>
574
+ (!opts.ids || opts.ids.includes(m.id)) && !this.isClaimed(m);
575
+ if (!this.pendingRows(sessionFile).some(claimable)) return [];
576
+ return this.tx(() => {
577
+ const claimed: Message[] = [];
578
+ for (const m of this.pendingRows(sessionFile)) {
579
+ if (!claimable(m)) continue;
580
+ this.db
581
+ .prepare(
582
+ `UPDATE message SET claim_pid = ?, claim_start = ?, claim_until = ? WHERE id = ?`,
583
+ )
584
+ .run(me.pid, me.startTime, until, m.id);
585
+ claimed.push(this.toMessage(m));
586
+ }
587
+ return claimed;
588
+ });
589
+ }
590
+
591
+ /** Give claimed messages back (they were not injected after all). */
592
+ release(ids: string[]): void {
593
+ const me = this.probe.self();
594
+ this.tx(() => {
595
+ for (const id of ids)
596
+ this.db
597
+ .prepare(
598
+ `UPDATE message SET claim_pid = NULL, claim_start = NULL, claim_until = NULL WHERE id = ? AND claim_pid = ?`,
599
+ )
600
+ .run(id, me.pid);
601
+ });
602
+ }
603
+
604
+ /** The messages are in the receiver's transcript now. Idempotent. */
605
+ markDelivered(sessionFile: string, ids: string[]): void {
606
+ const t = this.now();
607
+ this.tx(() => {
608
+ for (const id of ids)
609
+ this.db
610
+ .prepare(
611
+ `UPDATE message SET state = 'delivered', delivered_to = ?, finished_at = ?, claim_pid = NULL, claim_until = NULL
612
+ WHERE id = ? AND state = 'pending'`,
613
+ )
614
+ .run(sessionFile, t, id);
615
+ });
616
+ }
617
+
618
+ supersede(from: string | null, id: string, text: string): Message {
619
+ const old = this.ownPending(from, id);
620
+ const sent = this.tx(() => {
621
+ const newIdValue = this.insertMessage({
622
+ from: old.from_session,
623
+ fromLabel: old.from_label,
624
+ to: {kind: old.to_kind, target: old.to_target},
625
+ kind: old.kind,
626
+ text,
627
+ origin: old.origin,
628
+ relay: old.relay ? (JSON.parse(old.relay) as Relay) : null,
629
+ questionId: old.question_id,
630
+ urgent: old.urgent === 1,
631
+ });
632
+ this.db
633
+ .prepare(
634
+ `UPDATE message SET state = 'superseded', superseded_by = ?, finished_at = ? WHERE id = ?`,
635
+ )
636
+ .run(newIdValue, this.now(), id);
637
+ if (old.question_id)
638
+ this.db
639
+ .prepare(`UPDATE question SET message_id = ?, text = ? WHERE id = ?`)
640
+ .run(newIdValue, text, old.question_id);
641
+ return newIdValue;
642
+ });
643
+ return this.message(sent)!;
644
+ }
645
+
646
+ withdraw(from: string | null, id: string): void {
647
+ const old = this.ownPending(from, id);
648
+ this.tx(() => {
649
+ this.db
650
+ .prepare(
651
+ `UPDATE message SET state = 'withdrawn', finished_at = ? WHERE id = ?`,
652
+ )
653
+ .run(this.now(), id);
654
+ if (old.question_id)
655
+ this.db
656
+ .prepare(
657
+ `UPDATE question SET state = 'withdrawn', finished_at = ? WHERE id = ? AND state = 'open'`,
658
+ )
659
+ .run(this.now(), old.question_id);
660
+ });
661
+ }
662
+
663
+ private ownPending(from: string | null, id: string): MessageRow {
664
+ const row = this.db
665
+ .prepare(`SELECT * FROM message WHERE id = ?`)
666
+ .get(id) as MessageRow | undefined;
667
+ if (!row) throw new ShipmatesError(`no message ${id}`, 'not-found');
668
+ if (row.from_session !== from)
669
+ throw new ShipmatesError(`message ${id} is not yours`, 'not-yours');
670
+ if (row.state !== 'pending')
671
+ throw new ShipmatesError(
672
+ `message ${id} is already ${row.state}`,
673
+ row.state,
674
+ );
675
+ if (this.isClaimed(row))
676
+ throw new ShipmatesError(
677
+ `message ${id} is being delivered right now`,
678
+ 'delivering',
679
+ );
680
+ return row;
681
+ }
682
+
683
+ /**
684
+ * Claimed by a live process whose lease has not expired, THIS process
685
+ * included: a message this process is already delivering must not be handed
686
+ * out again (measured: re-claiming returned in-flight messages twice).
687
+ */
688
+ private isClaimed(m: MessageRow): boolean {
689
+ if (m.claim_pid === null || m.claim_until === null) return false;
690
+ if (m.claim_until < this.now()) return false;
691
+ const me = this.probe.self();
692
+ return this.probe.isAlive({
693
+ pid: m.claim_pid,
694
+ startTime: m.claim_start,
695
+ bootId: me.bootId,
696
+ host: me.host,
697
+ });
698
+ }
699
+
700
+ private pendingRows(sessionFile: string): MessageRow[] {
701
+ return this.db
702
+ .prepare(
703
+ `SELECT * FROM message WHERE state = 'pending' AND (
704
+ (to_kind = 'session' AND to_target = ?) OR
705
+ (to_kind = 'role' AND to_target IN (SELECT role FROM role WHERE session_file = ?)))
706
+ ORDER BY created_at, rowid`,
707
+ )
708
+ .all(sessionFile, sessionFile) as MessageRow[];
709
+ }
710
+
711
+ // --------------------------------------------------------------- questions
712
+
713
+ question(id: string): Question | null {
714
+ const row = this.db
715
+ .prepare(`SELECT * FROM question WHERE id = ?`)
716
+ .get(id) as QuestionRow | undefined;
717
+ return row ? toQuestion(row) : null;
718
+ }
719
+
720
+ /** Open questions addressed to this session, directly or through a role it holds. */
721
+ openQuestionsTo(sessionFile: string): Question[] {
722
+ const rows = this.db
723
+ .prepare(
724
+ `SELECT * FROM question WHERE state = 'open' AND (
725
+ (to_kind = 'session' AND to_target = ?) OR
726
+ (to_kind = 'role' AND to_target IN (SELECT role FROM role WHERE session_file = ?)))
727
+ ORDER BY created_at`,
728
+ )
729
+ .all(sessionFile, sessionFile) as QuestionRow[];
730
+ return rows.map(toQuestion);
731
+ }
732
+
733
+ /**
734
+ * Answer a question: the only way to close one (D12). The answer is sent back
735
+ * to the asker as a message. Only the session it was asked of answers it
736
+ * (for a role, its current holder); `from: null` is a human at the CLI.
737
+ */
738
+ answer(input: {
739
+ from: string | null;
740
+ questionId: string;
741
+ text: string;
742
+ origin?: Origin;
743
+ relay?: Relay | null;
744
+ }): Message {
745
+ const q = this.question(input.questionId);
746
+ if (!q)
747
+ throw new ShipmatesError(`no question ${input.questionId}`, 'not-found');
748
+ if (q.state !== 'open')
749
+ throw new ShipmatesError(
750
+ `question ${q.id} is already ${q.state}`,
751
+ q.state,
752
+ );
753
+ if (input.from !== null) {
754
+ const addressee =
755
+ q.to.kind === 'session' ? q.to.target : this.roleHolder(q.to.target);
756
+ if (addressee !== input.from)
757
+ throw new ShipmatesError(
758
+ `question ${q.id} was not asked of ${input.from}`,
759
+ 'not-asked',
760
+ );
761
+ }
762
+ const origin = input.origin ?? (input.from ? 'agent' : 'human');
763
+ if (origin === 'human-relayed' && !input.relay)
764
+ throw new ShipmatesError(
765
+ 'a human-relayed answer must carry the relay',
766
+ 'no-relay',
767
+ );
768
+ const id = this.tx(() => {
769
+ const t = this.now();
770
+ this.db
771
+ .prepare(
772
+ `UPDATE question SET state = 'answered', answer = ?, answer_origin = ?, answer_relay = ?, answered_by = ?, finished_at = ? WHERE id = ?`,
773
+ )
774
+ .run(
775
+ input.text,
776
+ origin,
777
+ input.relay ? JSON.stringify(input.relay) : null,
778
+ input.from ?? 'human',
779
+ t,
780
+ q.id,
781
+ );
782
+ return this.insertMessage({
783
+ from: input.from,
784
+ fromLabel: this.labelOf(input.from),
785
+ to: q.asker
786
+ ? {kind: 'session', target: q.asker}
787
+ : {kind: 'role', target: q.askerLabel},
788
+ kind: 'answer',
789
+ text: input.text,
790
+ origin,
791
+ relay: input.relay ?? null,
792
+ questionId: q.id,
793
+ });
794
+ });
795
+ return this.message(id)!;
796
+ }
797
+
798
+ /**
799
+ * What `session_wait` returns on (D12), or null to keep waiting: the answer;
800
+ * the target settling (idle or waiting for the human) after the wait began
801
+ * without answering; a new question addressed to the waiter (two sessions
802
+ * waiting on each other would otherwise deadlock until the timeout); or the
803
+ * question being withdrawn.
804
+ */
805
+ waitStatus(input: {
806
+ waiter: string;
807
+ questionId: string;
808
+ since: number;
809
+ }): WaitStatus | null {
810
+ const q = this.question(input.questionId);
811
+ if (!q)
812
+ throw new ShipmatesError(`no question ${input.questionId}`, 'not-found');
813
+ if (q.state === 'answered') return {status: 'answered', question: q};
814
+ if (q.state === 'withdrawn') return {status: 'withdrawn', question: q};
815
+ const asked = this.openQuestionsTo(input.waiter).filter(
816
+ (x) => x.createdAt >= input.since,
817
+ );
818
+ if (asked.length) return {status: 'asked', question: q, questions: asked};
819
+ const session =
820
+ q.to.kind === 'session' ? q.to.target : this.roleHolder(q.to.target);
821
+ const target = session ? this.presence(session) : null;
822
+ if (
823
+ target?.live &&
824
+ target.state !== 'running' &&
825
+ target.state !== 'waiting-for-session' &&
826
+ (target.settledAt ?? 0) > input.since
827
+ )
828
+ return {status: 'settled', question: q, target};
829
+ return null;
830
+ }
831
+
832
+ // -------------------------------------------------------------- the human
833
+
834
+ /** Raise an attention item: a question for the human, in the one inbox (D13). */
835
+ humanAsk(input: {
836
+ from: string;
837
+ question: string;
838
+ options?: string[];
839
+ blocking?: boolean;
840
+ onBehalfOf?: string[];
841
+ }): AttentionItem {
842
+ const onBehalfOf = input.onBehalfOf ?? [];
843
+ for (const qid of onBehalfOf)
844
+ if (!this.question(qid))
845
+ throw new ShipmatesError(
846
+ `onBehalfOf names no question: ${qid}`,
847
+ 'not-found',
848
+ );
849
+ const id = newId('h');
850
+ this.tx(() => {
851
+ this.db
852
+ .prepare(
853
+ `INSERT INTO item(id, session_file, question, options, blocking, on_behalf_of, created_at) VALUES(?, ?, ?, ?, ?, ?, ?)`,
854
+ )
855
+ .run(
856
+ id,
857
+ input.from,
858
+ input.question,
859
+ input.options?.length ? JSON.stringify(input.options) : null,
860
+ input.blocking ? 1 : 0,
861
+ onBehalfOf.length ? JSON.stringify(onBehalfOf) : null,
862
+ this.now(),
863
+ );
864
+ });
865
+ return this.item(id)!;
866
+ }
867
+
868
+ item(id: string): AttentionItem | null {
869
+ const row = this.db.prepare(`SELECT * FROM item WHERE id = ?`).get(id) as
870
+ ItemRow | undefined;
871
+ return row ? toItem(row) : null;
872
+ }
873
+
874
+ /** Open items, oldest first; blocking ones first of all. */
875
+ inbox(): AttentionItem[] {
876
+ const rows = this.db
877
+ .prepare(
878
+ `SELECT * FROM item WHERE state = 'open' ORDER BY blocking DESC, created_at`,
879
+ )
880
+ .all() as ItemRow[];
881
+ return rows.map(toItem);
882
+ }
883
+
884
+ /**
885
+ * The human answered an item. Callers must only call this for a real human act
886
+ * (a slash command, the CLI at a terminal, a host's authenticated UI, a human
887
+ * turn in the asking session): ADR 0003.
888
+ *
889
+ * The answer goes to the asking session as a message of origin `human`, unless
890
+ * `deliver` is false: the human said it in that session's own turn, so their
891
+ * words are already in its transcript and a second copy would repeat them (D39).
892
+ */
893
+ answerItem(
894
+ itemId: string,
895
+ text: string,
896
+ opts: {channel: string; deliver?: true},
897
+ ): Message;
898
+ answerItem(
899
+ itemId: string,
900
+ text: string,
901
+ opts: {channel: string; deliver: boolean},
902
+ ): Message | null;
903
+ answerItem(
904
+ itemId: string,
905
+ text: string,
906
+ opts: {channel: string; deliver?: boolean},
907
+ ): Message | null {
908
+ // Checked inside the write: the session's input handler and another
909
+ // channel (the CLI, a host) may answer the same item at the same moment,
910
+ // and only one of them may win (D39).
911
+ const id = this.tx(() => {
912
+ const item = this.item(itemId);
913
+ if (!item) throw new ShipmatesError(`no item ${itemId}`, 'not-found');
914
+ if (item.state !== 'open')
915
+ throw new ShipmatesError(
916
+ `item ${itemId} is already ${item.state}`,
917
+ item.state,
918
+ );
919
+ return this.closeItem(item, text, opts);
920
+ });
921
+ return id ? this.message(id)! : null;
922
+ }
923
+
924
+ /**
925
+ * The human replied in the session that raised these items (D39): every item
926
+ * of `sessionFile` still open, except `except`, is answered with their words
927
+ * on `opts.channel` (by convention `session`). Returns the items it closed.
928
+ *
929
+ * With `notice`, the session also gets one `notice` message (origin agent,
930
+ * from shipmates) naming the items the reply closed: the human's words are in
931
+ * its turn, but nothing else would tell the agent which questions they
932
+ * closed, and it may still be waiting on one of them.
933
+ */
934
+ answerOpenItemsOf(
935
+ sessionFile: string,
936
+ text: string,
937
+ opts: {
938
+ channel: string;
939
+ deliver?: boolean;
940
+ except?: string[];
941
+ notice?: boolean;
942
+ },
943
+ ): AttentionItem[] {
944
+ const skip = new Set(opts.except ?? []);
945
+ const open = () =>
946
+ (
947
+ this.db
948
+ .prepare(
949
+ `SELECT * FROM item WHERE session_file = ? AND state = 'open' ORDER BY created_at`,
950
+ )
951
+ .all(sessionFile) as ItemRow[]
952
+ ).filter((r) => !skip.has(r.id));
953
+ // Read first: the write lock only when there is something to close
954
+ // (every human input calls this; most sessions have no open item).
955
+ if (!open().length) return [];
956
+ return this.tx(() => {
957
+ const rows = open();
958
+ for (const r of rows) this.closeItem(toItem(r), text, opts);
959
+ if (opts.notice && rows.length)
960
+ this.insertMessage({
961
+ from: null,
962
+ fromLabel: 'shipmates',
963
+ to: {kind: 'session', target: sessionFile},
964
+ kind: 'notice',
965
+ text: `The human's reply in this session closed ${rows.length === 1 ? 'your inbox item' : `${rows.length} of your inbox items`} (answered with their words, channel ${opts.channel}): ${rows.map((r) => `${r.id} "${r.question.slice(0, 120)}"`).join('; ')}. If it did not answer one of them, ask again.`,
966
+ origin: 'agent',
967
+ });
968
+ return rows.map((r) => r.id);
969
+ }).map((id) => this.item(id)!);
970
+ }
971
+
972
+ /** Inside a write: mark an open item answered, and send the answer unless told not to. */
973
+ private closeItem(
974
+ item: AttentionItem,
975
+ text: string,
976
+ opts: {channel: string; deliver?: boolean},
977
+ ): string | null {
978
+ const t = this.now();
979
+ const r = this.db
980
+ .prepare(
981
+ `UPDATE item SET state = 'answered', answer = ?, answer_channel = ?, finished_at = ? WHERE id = ? AND state = 'open'`,
982
+ )
983
+ .run(text, opts.channel, t, item.id);
984
+ if (Number(r.changes) !== 1)
985
+ throw new ShipmatesError(`item ${item.id} is no longer open`, 'answered');
986
+ if (opts.deliver === false) return null;
987
+ const relay: Relay = {
988
+ text,
989
+ channel: opts.channel,
990
+ session: null,
991
+ itemId: item.id,
992
+ at: t,
993
+ };
994
+ return this.insertMessage({
995
+ from: null,
996
+ fromLabel: 'human',
997
+ to: {kind: 'session', target: item.session},
998
+ kind: 'answer',
999
+ text,
1000
+ origin: 'human',
1001
+ relay,
1002
+ itemId: item.id,
1003
+ });
1004
+ }
1005
+
1006
+ /**
1007
+ * Withdraw an item this session raised and that is still open. Refused for
1008
+ * another session's item: only the asker knows the question no longer stands.
1009
+ * Returns the item as it now is (unchanged when it was already answered).
1010
+ */
1011
+ withdrawItem(from: string, itemId: string): AttentionItem {
1012
+ const item = this.item(itemId);
1013
+ if (!item) throw new ShipmatesError(`no item ${itemId}`, 'not-found');
1014
+ if (item.session !== from)
1015
+ throw new ShipmatesError(
1016
+ `item ${itemId} was raised by ${this.labelOf(item.session)}, not by you`,
1017
+ 'not-yours',
1018
+ );
1019
+ this.tx(() => {
1020
+ this.db
1021
+ .prepare(
1022
+ `UPDATE item SET state = 'withdrawn', finished_at = ? WHERE id = ? AND session_file = ? AND state = 'open'`,
1023
+ )
1024
+ .run(this.now(), itemId, from);
1025
+ });
1026
+ return this.item(itemId)!;
1027
+ }
1028
+
1029
+ /**
1030
+ * Items that closed (answered or withdrawn) at or after `since`, oldest
1031
+ * first: what a host reads to update its own copy of an item it pushed to
1032
+ * the human (a Telegram message that must stop looking open, D39).
1033
+ */
1034
+ itemsFinishedSince(since: number): AttentionItem[] {
1035
+ const rows = this.db
1036
+ .prepare(
1037
+ `SELECT * FROM item WHERE state != 'open' AND finished_at >= ? ORDER BY finished_at, rowid`,
1038
+ )
1039
+ .all(since) as ItemRow[];
1040
+ return rows.map(toItem);
1041
+ }
1042
+
1043
+ /** The human's answers to this session's items, newest first. */
1044
+ humanAnswers(sessionFile: string): AttentionItem[] {
1045
+ const rows = this.db
1046
+ .prepare(
1047
+ `SELECT * FROM item WHERE session_file = ? AND state = 'answered' ORDER BY finished_at DESC`,
1048
+ )
1049
+ .all(sessionFile) as ItemRow[];
1050
+ return rows.map(toItem);
1051
+ }
1052
+
1053
+ /**
1054
+ * Record a turn a human really typed into this session (ADR 0003): TUI input,
1055
+ * or a host's `shipmates:human-input` mark. Never call this for agent text.
1056
+ */
1057
+ recordHumanTurn(
1058
+ sessionFile: string,
1059
+ input: {text: string; channel: string},
1060
+ ): string {
1061
+ const id = newId('t');
1062
+ this.tx(() => {
1063
+ this.db
1064
+ .prepare(
1065
+ `INSERT INTO human_turn(id, session_file, text, channel, at) VALUES(?, ?, ?, ?, ?)`,
1066
+ )
1067
+ .run(id, sessionFile, input.text, input.channel, this.now());
1068
+ });
1069
+ return id;
1070
+ }
1071
+
1072
+ /**
1073
+ * Build the relay for a human-relayed message: the human's own words, found
1074
+ * among this session's recent human turns (by a quote the agent gives, or the
1075
+ * latest turn), or an answered inbox item of this session. An agent can carry
1076
+ * a human's words; it cannot make them up.
1077
+ */
1078
+ relayFromHuman(
1079
+ sessionFile: string,
1080
+ ref: {quote?: string; itemId?: string},
1081
+ ): Relay {
1082
+ if (ref.itemId) {
1083
+ const item = this.item(ref.itemId);
1084
+ if (
1085
+ !item ||
1086
+ item.session !== sessionFile ||
1087
+ item.state !== 'answered' ||
1088
+ item.answer === null
1089
+ )
1090
+ throw new ShipmatesError(
1091
+ `no answered inbox item ${ref.itemId} for this session`,
1092
+ 'no-human-turn',
1093
+ );
1094
+ return {
1095
+ text: item.answer,
1096
+ channel: item.answerChannel ?? 'unknown',
1097
+ session: null,
1098
+ itemId: item.id,
1099
+ at: this.now(),
1100
+ };
1101
+ }
1102
+ const turns = this.db
1103
+ .prepare(
1104
+ `SELECT * FROM human_turn WHERE session_file = ? ORDER BY at DESC, rowid DESC LIMIT 20`,
1105
+ )
1106
+ .all(sessionFile) as {
1107
+ id: string;
1108
+ text: string;
1109
+ channel: string;
1110
+ at: number;
1111
+ }[];
1112
+ const norm = (x: string) => x.replace(/\s+/g, ' ').trim().toLowerCase();
1113
+ const turn = ref.quote
1114
+ ? turns.find((t) => norm(t.text).includes(norm(ref.quote!)))
1115
+ : turns[0];
1116
+ if (!turn)
1117
+ throw new ShipmatesError(
1118
+ ref.quote
1119
+ ? `no human turn in this session contains ${JSON.stringify(ref.quote)}: only words the human typed can be relayed`
1120
+ : 'no human turn in this session to relay',
1121
+ 'no-human-turn',
1122
+ );
1123
+ return {
1124
+ text: turn.text,
1125
+ channel: turn.channel,
1126
+ session: sessionFile,
1127
+ turnId: turn.id,
1128
+ at: turn.at,
1129
+ };
1130
+ }
1131
+
1132
+ /** Open questions this session asked. */
1133
+ openQuestionsFrom(sessionFile: string): Question[] {
1134
+ const rows = this.db
1135
+ .prepare(
1136
+ `SELECT * FROM question WHERE state = 'open' AND asker_session = ? ORDER BY created_at`,
1137
+ )
1138
+ .all(sessionFile) as QuestionRow[];
1139
+ return rows.map(toQuestion);
1140
+ }
1141
+
1142
+ /** Messages this session may receive now: to it, or to a role it holds. */
1143
+ pendingFor(sessionFile: string): Message[] {
1144
+ return this.pendingRows(sessionFile).map((r) => this.toMessage(r));
1145
+ }
1146
+
1147
+ message(id: string): Message | null {
1148
+ const row = this.db
1149
+ .prepare(`SELECT * FROM message WHERE id = ?`)
1150
+ .get(id) as MessageRow | undefined;
1151
+ return row ? this.toMessage(row) : null;
1152
+ }
1153
+
1154
+ protected insertMessage(m: {
1155
+ from: string | null;
1156
+ fromLabel: string;
1157
+ to: {kind: 'session' | 'role'; target: string};
1158
+ kind: Message['kind'];
1159
+ text: string;
1160
+ origin: Origin;
1161
+ relay?: Relay | null;
1162
+ questionId?: string | null;
1163
+ itemId?: string | null;
1164
+ requestId?: string | null;
1165
+ urgent?: boolean;
1166
+ }): string {
1167
+ const id = newId('m');
1168
+ this.db
1169
+ .prepare(
1170
+ `INSERT INTO message(id, from_session, from_label, to_kind, to_target, kind, question_id, item_id, text, origin, relay, request_id, urgent, created_at)
1171
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1172
+ )
1173
+ .run(
1174
+ id,
1175
+ m.from,
1176
+ m.fromLabel,
1177
+ m.to.kind,
1178
+ m.to.target,
1179
+ m.kind,
1180
+ m.questionId ?? null,
1181
+ m.itemId ?? null,
1182
+ m.text,
1183
+ m.origin,
1184
+ m.relay ? JSON.stringify(m.relay) : null,
1185
+ m.requestId ?? null,
1186
+ m.urgent ? 1 : 0,
1187
+ this.now(),
1188
+ );
1189
+ return id;
1190
+ }
1191
+
1192
+ /** How a sender is named to receivers: its roles if it has any, else its file. */
1193
+ labelOf(sessionFile: string | null): string {
1194
+ if (!sessionFile) return 'human';
1195
+ const roles = this.rolesOf(sessionFile);
1196
+ return roles.length ? roles.join(',') : sessionFile;
1197
+ }
1198
+
1199
+ protected toMessage(r: MessageRow): Message {
1200
+ return {
1201
+ id: r.id,
1202
+ from: r.from_session,
1203
+ fromLabel: r.from_label,
1204
+ to: {kind: r.to_kind, target: r.to_target},
1205
+ kind: r.kind,
1206
+ questionId: r.question_id,
1207
+ itemId: r.item_id,
1208
+ text: r.text,
1209
+ origin: r.origin,
1210
+ relay: r.relay ? (JSON.parse(r.relay) as Relay) : null,
1211
+ urgent: r.urgent === 1,
1212
+ state: r.state,
1213
+ supersededBy: r.superseded_by,
1214
+ deliveredTo: r.delivered_to,
1215
+ createdAt: r.created_at,
1216
+ };
1217
+ }
1218
+
1219
+ // --------------------------------------------------------------- ownership
1220
+
1221
+ /**
1222
+ * Start a spawn: the ownership record exists before the new session does, so
1223
+ * a terminal child can bind itself at its own `session_start` (D28). The owner
1224
+ * is fixed here and never changes.
1225
+ */
1226
+ beginSpawn(input: SpawnInput): Ownership {
1227
+ if (input.prompt && Buffer.byteLength(input.prompt) > MAX_TEXT_BYTES)
1228
+ throw new ShipmatesError(
1229
+ `the first prompt is over 8 KB (${Buffer.byteLength(input.prompt)} bytes): put the plan in git and point at it`,
1230
+ 'too-large',
1231
+ );
1232
+ if (input.role && !ROLE_RE.test(input.role))
1233
+ throw new ShipmatesError(
1234
+ `invalid role ${JSON.stringify(input.role)}`,
1235
+ 'bad-role',
1236
+ );
1237
+ const id = newId('sp');
1238
+ this.tx(() => {
1239
+ this.db
1240
+ .prepare(
1241
+ `INSERT INTO ownership(id, owner, folder, role, via, detail, prompt, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`,
1242
+ )
1243
+ .run(
1244
+ id,
1245
+ input.owner,
1246
+ input.folder,
1247
+ input.role ?? null,
1248
+ input.via,
1249
+ input.detail ? JSON.stringify(input.detail) : null,
1250
+ input.prompt ?? null,
1251
+ this.now(),
1252
+ );
1253
+ });
1254
+ return this.spawnRecord(id)!;
1255
+ }
1256
+
1257
+ /**
1258
+ * The spawned session exists: bind it to its spawn, once, and queue its first
1259
+ * prompt as a `spawn` message from the owner, origin agent (never a human
1260
+ * turn, D28). Binding the same session again is a no-op; a session that is
1261
+ * already owned, or a spawn bound to another session, is refused: ownership
1262
+ * never changes.
1263
+ */
1264
+ bindSpawn(spawnId: string, sessionFile: string): Ownership {
1265
+ this.tx(() => {
1266
+ const row = this.db
1267
+ .prepare(`SELECT * FROM ownership WHERE id = ?`)
1268
+ .get(spawnId) as OwnershipRow | undefined;
1269
+ if (!row) throw new ShipmatesError(`no spawn ${spawnId}`, 'not-found');
1270
+ if (row.session_file === sessionFile) return;
1271
+ if (row.session_file)
1272
+ throw new ShipmatesError(
1273
+ `spawn ${spawnId} is already ${row.session_file}`,
1274
+ 'owned',
1275
+ );
1276
+ const other = this.db
1277
+ .prepare(`SELECT owner FROM ownership WHERE session_file = ?`)
1278
+ .get(sessionFile) as {owner: string} | undefined;
1279
+ if (other)
1280
+ throw new ShipmatesError(
1281
+ `${sessionFile} is already owned by ${other.owner}; ownership never changes`,
1282
+ 'owned',
1283
+ );
1284
+ if (
1285
+ sessionFile === row.owner ||
1286
+ this.ancestors(row.owner).includes(sessionFile)
1287
+ )
1288
+ throw new ShipmatesError(
1289
+ `${sessionFile} cannot be owned by ${row.owner}: that would be a cycle`,
1290
+ 'cycle',
1291
+ );
1292
+ this.db
1293
+ .prepare(
1294
+ `UPDATE ownership SET session_file = ?, bound_at = ? WHERE id = ?`,
1295
+ )
1296
+ .run(sessionFile, this.now(), spawnId);
1297
+ if (row.prompt)
1298
+ this.insertMessage({
1299
+ from: row.owner,
1300
+ fromLabel: this.labelOf(row.owner),
1301
+ to: {kind: 'session', target: sessionFile},
1302
+ kind: 'spawn',
1303
+ text: row.prompt,
1304
+ origin: 'agent',
1305
+ requestId: `spawn:${spawnId}`,
1306
+ });
1307
+ });
1308
+ return this.spawnRecord(spawnId)!;
1309
+ }
1310
+
1311
+ /** Record that `owner` owns an existing session (a host that spawned it by its own means). */
1312
+ recordOwnership(input: SpawnInput & {session: string}): Ownership {
1313
+ const sp = this.beginSpawn(input);
1314
+ try {
1315
+ return this.bindSpawn(sp.id, input.session);
1316
+ } catch (e) {
1317
+ this.tx(() => {
1318
+ this.db.prepare(`DELETE FROM ownership WHERE id = ?`).run(sp.id);
1319
+ });
1320
+ throw e;
1321
+ }
1322
+ }
1323
+
1324
+ spawnRecord(spawnId: string): Ownership | null {
1325
+ const row = this.db
1326
+ .prepare(`SELECT * FROM ownership WHERE id = ?`)
1327
+ .get(spawnId) as OwnershipRow | undefined;
1328
+ return row ? this.toOwnership(row) : null;
1329
+ }
1330
+
1331
+ /** The ownership record of a session, or null when nobody spawned it. */
1332
+ ownership(sessionFile: string): Ownership | null {
1333
+ const row = this.db
1334
+ .prepare(`SELECT * FROM ownership WHERE session_file = ?`)
1335
+ .get(sessionFile) as OwnershipRow | undefined;
1336
+ return row ? this.toOwnership(row) : null;
1337
+ }
1338
+
1339
+ ownerOf(sessionFile: string): string | null {
1340
+ return this.ownership(sessionFile)?.owner ?? null;
1341
+ }
1342
+
1343
+ /**
1344
+ * The sessions `owner` spawned, live or not, oldest first; with `transitive`,
1345
+ * their own children too (depth first). Spawns that never came up are left out.
1346
+ */
1347
+ ownedBy(owner: string, opts: {transitive?: boolean} = {}): Ownership[] {
1348
+ const out: Ownership[] = [];
1349
+ const seen = new Set([owner]);
1350
+ const walk = (o: string) => {
1351
+ const rows = this.db
1352
+ .prepare(
1353
+ `SELECT * FROM ownership WHERE owner = ? AND session_file IS NOT NULL ORDER BY created_at, rowid`,
1354
+ )
1355
+ .all(o) as OwnershipRow[];
1356
+ for (const r of rows) {
1357
+ if (seen.has(r.session_file!)) continue;
1358
+ seen.add(r.session_file!);
1359
+ out.push(this.toOwnership(r));
1360
+ if (opts.transitive) walk(r.session_file!);
1361
+ }
1362
+ };
1363
+ walk(owner);
1364
+ return out;
1365
+ }
1366
+
1367
+ /**
1368
+ * Whether `caller` owns `target`, directly or through the sessions it owns
1369
+ * (D23): an orchestrator answers for its children's children too.
1370
+ */
1371
+ owns(caller: string, target: string): boolean {
1372
+ return this.ancestors(target).includes(caller);
1373
+ }
1374
+
1375
+ /** The owner, the owner's owner, and so on up. */
1376
+ private ancestors(sessionFile: string): string[] {
1377
+ const out: string[] = [];
1378
+ for (let s = this.ownerOf(sessionFile); s && out.length < 64;) {
1379
+ if (out.includes(s)) break;
1380
+ out.push(s);
1381
+ s = this.ownerOf(s);
1382
+ }
1383
+ return out;
1384
+ }
1385
+
1386
+ /**
1387
+ * A host archives or deletes a session: mark it and every session it owns,
1388
+ * transitively, as one batch (D24). shipmates cannot touch transcripts; the host
1389
+ * hides or deletes them, and must keep a deleted one until `undoUntil`.
1390
+ * Sessions already archived keep their own batch.
1391
+ */
1392
+ archive(
1393
+ sessionFile: string,
1394
+ opts: {kind: ArchiveMark['kind']; by: string},
1395
+ ): {batch: string; at: number; undoUntil: number; sessions: string[]} {
1396
+ const batch = newId('ar');
1397
+ const at = this.now();
1398
+ const sessions = this.tx(() => {
1399
+ // Inside the transaction, so a child bound meanwhile is not missed.
1400
+ const all = [
1401
+ sessionFile,
1402
+ ...this.ownedBy(sessionFile, {transitive: true}).map((o) => o.session!),
1403
+ ];
1404
+ const marked: string[] = [];
1405
+ for (const s of all) {
1406
+ const r = this.db
1407
+ .prepare(
1408
+ `INSERT INTO archive(session_file, kind, batch, by_label, at) VALUES(?, ?, ?, ?, ?) ON CONFLICT(session_file) DO NOTHING`,
1409
+ )
1410
+ .run(s, opts.kind, batch, opts.by, at);
1411
+ if (r.changes) marked.push(s);
1412
+ }
1413
+ return marked;
1414
+ });
1415
+ return {batch, at, undoUntil: at + ARCHIVE_UNDO_MS, sessions};
1416
+ }
1417
+
1418
+ /** Undo a whole archive batch within its window; returns the sessions restored. */
1419
+ undoArchive(batch: string): string[] {
1420
+ return this.tx(() => {
1421
+ const rows = this.db
1422
+ .prepare(`SELECT * FROM archive WHERE batch = ?`)
1423
+ .all(batch) as ArchiveRow[];
1424
+ if (!rows.length)
1425
+ throw new ShipmatesError(`no archive batch ${batch}`, 'not-found');
1426
+ if (rows[0].at + ARCHIVE_UNDO_MS < this.now())
1427
+ throw new ShipmatesError(
1428
+ `archive ${batch} is past its undo window (7 days)`,
1429
+ 'expired',
1430
+ );
1431
+ this.db.prepare(`DELETE FROM archive WHERE batch = ?`).run(batch);
1432
+ return rows.map((r) => r.session_file);
1433
+ });
1434
+ }
1435
+
1436
+ archiveMark(sessionFile: string): ArchiveMark | null {
1437
+ const row = this.db
1438
+ .prepare(`SELECT * FROM archive WHERE session_file = ?`)
1439
+ .get(sessionFile) as ArchiveRow | undefined;
1440
+ return row ? toArchive(row) : null;
1441
+ }
1442
+
1443
+ /** Marks whose undo window has passed: a host may now make them permanent. */
1444
+ expiredArchives(): ArchiveMark[] {
1445
+ return (
1446
+ this.db
1447
+ .prepare(`SELECT * FROM archive WHERE at < ? ORDER BY at`)
1448
+ .all(this.now() - ARCHIVE_UNDO_MS) as ArchiveRow[]
1449
+ ).map(toArchive);
1450
+ }
1451
+
1452
+ /**
1453
+ * D29: the headless children of `owner` that have messages to read which
1454
+ * arrived after their last stop, and are not archived. One cached query,
1455
+ * since every session's poller asks on every change. Measured: 3 µs for a
1456
+ * session that owns nothing, 42 µs with 5 children and one to wake, against
1457
+ * about 500 µs as separate reads per child. Liveness is left to the caller:
1458
+ * it is a process probe, not SQL.
1459
+ */
1460
+ wakeCandidates(owner: string): Ownership[] {
1461
+ const rows = this.cached(
1462
+ `SELECT o.* FROM ownership o
1463
+ LEFT JOIN (SELECT session_file, max(at) AS at FROM stop_request GROUP BY session_file) s
1464
+ ON s.session_file = o.session_file
1465
+ WHERE o.owner = ? AND o.via = 'headless' AND o.session_file IS NOT NULL
1466
+ AND NOT EXISTS (SELECT 1 FROM archive a WHERE a.session_file = o.session_file)
1467
+ AND (EXISTS (SELECT 1 FROM message m WHERE m.state = 'pending' AND m.to_kind = 'session'
1468
+ AND m.to_target = o.session_file AND m.created_at > COALESCE(s.at, -1))
1469
+ OR EXISTS (SELECT 1 FROM role r JOIN message m ON m.state = 'pending' AND m.to_kind = 'role'
1470
+ AND m.to_target = r.role
1471
+ WHERE r.session_file = o.session_file AND m.created_at > COALESCE(s.at, -1)))
1472
+ ORDER BY o.created_at`,
1473
+ ).all(owner) as OwnershipRow[];
1474
+ return rows.map((r) => this.toOwnership(r));
1475
+ }
1476
+
1477
+ /**
1478
+ * Prepared once per connection, for the queries the poller runs on every
1479
+ * change: compiling a statement is most of the cost of a small query.
1480
+ */
1481
+ private statements = new Map<string, ReturnType<DB['prepare']>>();
1482
+ private cached(sql: string): ReturnType<DB['prepare']> {
1483
+ let st = this.statements.get(sql);
1484
+ if (!st) this.statements.set(sql, (st = this.db.prepare(sql)));
1485
+ return st;
1486
+ }
1487
+
1488
+ /**
1489
+ * A headless child is being woken (D29): granted to exactly one caller until
1490
+ * the lease lapses, so two polls or two processes never start it twice. A
1491
+ * refusal says when the current lease ends, so the caller can look again then.
1492
+ */
1493
+ leaseWake(
1494
+ sessionFile: string,
1495
+ ms: number,
1496
+ ): {ok: true} | {ok: false; until: number | null} {
1497
+ // Read first: a refused lease must not write. A write bumps changeToken(),
1498
+ // which wakes every poller, which asks again: a write-lock loop every
1499
+ // poll while the lease is held (invariant 4's reason; found in review).
1500
+ const held = this.db
1501
+ .prepare(`SELECT wake_until FROM ownership WHERE session_file = ?`)
1502
+ .get(sessionFile) as {wake_until: number | null} | undefined;
1503
+ if (!held) return {ok: false, until: null};
1504
+ if (held.wake_until != null && held.wake_until >= this.now())
1505
+ return {ok: false, until: held.wake_until};
1506
+ return this.tx(() => {
1507
+ const t = this.now();
1508
+ const r = this.db
1509
+ .prepare(
1510
+ `UPDATE ownership SET wake_until = ? WHERE session_file = ? AND (wake_until IS NULL OR wake_until < ?)`,
1511
+ )
1512
+ .run(t + ms, sessionFile, t);
1513
+ if (r.changes === 1) return {ok: true as const};
1514
+ const row = this.db
1515
+ .prepare(`SELECT wake_until FROM ownership WHERE session_file = ?`)
1516
+ .get(sessionFile) as {wake_until: number | null} | undefined;
1517
+ return {ok: false as const, until: row?.wake_until ?? null};
1518
+ });
1519
+ }
1520
+
1521
+ /**
1522
+ * The woken child is up: shorten its lease to `gapMs` from now. Once it has
1523
+ * exited, the next wake may come after that gap, not before: a child that
1524
+ * dies before reading its messages is retried at that pace, never in a loop.
1525
+ */
1526
+ wakeDone(sessionFile: string, gapMs: number): void {
1527
+ const until = this.now() + gapMs;
1528
+ const row = this.db
1529
+ .prepare(`SELECT wake_until FROM ownership WHERE session_file = ?`)
1530
+ .get(sessionFile) as {wake_until: number | null} | undefined;
1531
+ // No write lock for nothing (the reason behind invariant 4).
1532
+ if (row?.wake_until == null || row.wake_until <= until) return;
1533
+ this.tx(() => {
1534
+ this.db
1535
+ .prepare(
1536
+ `UPDATE ownership SET wake_until = ? WHERE session_file = ? AND wake_until > ?`,
1537
+ )
1538
+ .run(until, sessionFile, until);
1539
+ });
1540
+ }
1541
+
1542
+ protected toOwnership(r: OwnershipRow): Ownership {
1543
+ return {
1544
+ id: r.id,
1545
+ session: r.session_file,
1546
+ owner: r.owner,
1547
+ folder: r.folder,
1548
+ role: r.role,
1549
+ via: r.via,
1550
+ detail: r.detail ? (JSON.parse(r.detail) as Record<string, unknown>) : {},
1551
+ createdAt: r.created_at,
1552
+ boundAt: r.bound_at,
1553
+ archived: r.session_file ? this.archiveMark(r.session_file) : null,
1554
+ };
1555
+ }
1556
+
1557
+ // -------------------------------------------------------------------- stop
1558
+
1559
+ /**
1560
+ * Ask a session to stop its current turn (D30). Its own extension acts on it
1561
+ * at the next poll and records the outcome; it never cascades. Authorisation
1562
+ * is the caller's job: the tool checks `owns`, the CLI that a human runs it.
1563
+ */
1564
+ requestStop(sessionFile: string, opts: {by: string | null}): StopRequest {
1565
+ const id = newId('s');
1566
+ this.tx(() => {
1567
+ this.db
1568
+ .prepare(
1569
+ `INSERT INTO stop_request(id, session_file, by_session, by_label, at) VALUES(?, ?, ?, ?, ?)`,
1570
+ )
1571
+ .run(id, sessionFile, opts.by, this.labelOf(opts.by), this.now());
1572
+ });
1573
+ return this.stopRequest(id)!;
1574
+ }
1575
+
1576
+ stopRequest(id: string): StopRequest | null {
1577
+ const row = this.db
1578
+ .prepare(`SELECT * FROM stop_request WHERE id = ?`)
1579
+ .get(id) as StopRow | undefined;
1580
+ return row ? toStop(row) : null;
1581
+ }
1582
+
1583
+ /** Stop requests this session has not acted on yet, oldest first. A read: no lock. */
1584
+ openStops(sessionFile: string): StopRequest[] {
1585
+ return (
1586
+ this.cached(
1587
+ `SELECT * FROM stop_request WHERE session_file = ? AND handled_at IS NULL ORDER BY at, rowid`,
1588
+ ).all(sessionFile) as StopRow[]
1589
+ ).map(toStop);
1590
+ }
1591
+
1592
+ settleStop(id: string, outcome: 'stopped' | 'not-running'): void {
1593
+ this.tx(() => {
1594
+ this.db
1595
+ .prepare(
1596
+ `UPDATE stop_request SET handled_at = ?, outcome = ? WHERE id = ? AND handled_at IS NULL`,
1597
+ )
1598
+ .run(this.now(), outcome, id);
1599
+ });
1600
+ }
1601
+
1602
+ /** When this session was last asked to stop, or null. */
1603
+ lastStopAt(sessionFile: string): number | null {
1604
+ const row = this.db
1605
+ .prepare(`SELECT max(at) AS at FROM stop_request WHERE session_file = ?`)
1606
+ .get(sessionFile) as {at: number | null};
1607
+ return row.at;
1608
+ }
1609
+
1610
+ // --------------------------------------------------------------- retention
1611
+
1612
+ /**
1613
+ * D11: finished messages, questions and items go after 30 days (the receiver's
1614
+ * transcript keeps every delivered message for good); presence of a dead process
1615
+ * after a day. Pending messages and open questions are never pruned by age.
1616
+ */
1617
+ prune(): void {
1618
+ const t = this.now();
1619
+ const finished = t - 30 * DAY;
1620
+ const dead = this.db
1621
+ .prepare(`SELECT * FROM presence WHERE updated_at < ?`)
1622
+ .all(t - DAY) as PresenceRow[];
1623
+ this.tx(() => {
1624
+ this.db
1625
+ .prepare(
1626
+ `DELETE FROM message WHERE state != 'pending' AND finished_at < ?`,
1627
+ )
1628
+ .run(finished);
1629
+ this.db
1630
+ .prepare(
1631
+ `DELETE FROM question WHERE state != 'open' AND finished_at < ?`,
1632
+ )
1633
+ .run(finished);
1634
+ this.db
1635
+ .prepare(`DELETE FROM item WHERE state != 'open' AND finished_at < ?`)
1636
+ .run(finished);
1637
+ this.db.prepare(`DELETE FROM human_turn WHERE at < ?`).run(finished);
1638
+ this.db
1639
+ .prepare(
1640
+ `DELETE FROM stop_request WHERE handled_at IS NOT NULL AND handled_at < ?`,
1641
+ )
1642
+ .run(finished);
1643
+ this.pruneOwnership(t);
1644
+ for (const row of dead)
1645
+ if (!this.probe.isAlive(this.identityOf(row)))
1646
+ this.db
1647
+ .prepare(`DELETE FROM presence WHERE session_file = ? AND pid = ?`)
1648
+ .run(row.session_file, row.pid);
1649
+ this.db
1650
+ .prepare(
1651
+ `INSERT OR REPLACE INTO meta(key, value) VALUES('last_prune', ?)`,
1652
+ )
1653
+ .run(String(t));
1654
+ });
1655
+ }
1656
+
1657
+ /**
1658
+ * D25: ownership is never pruned while its session exists. A spawn that never
1659
+ * came up goes after a day. A bound record goes only when its transcript file
1660
+ * is gone, nobody runs it, and it is over 30 days old (pi writes a transcript
1661
+ * only after the first assistant message, so a missing file alone proves
1662
+ * nothing about a fresh session). An archive mark goes with its transcript,
1663
+ * once the undo window has passed. Called inside prune's transaction.
1664
+ */
1665
+ private pruneOwnership(t: number): void {
1666
+ this.db
1667
+ .prepare(
1668
+ `DELETE FROM ownership WHERE session_file IS NULL AND created_at < ?`,
1669
+ )
1670
+ .run(t - DAY);
1671
+ const old = this.db
1672
+ .prepare(
1673
+ `SELECT session_file FROM ownership WHERE session_file IS NOT NULL AND bound_at < ?`,
1674
+ )
1675
+ .all(t - 30 * DAY) as {session_file: string}[];
1676
+ for (const {session_file} of old)
1677
+ if (!fs.existsSync(session_file) && !this.isLive(session_file))
1678
+ this.db
1679
+ .prepare(`DELETE FROM ownership WHERE session_file = ?`)
1680
+ .run(session_file);
1681
+ const marks = this.db
1682
+ .prepare(`SELECT session_file FROM archive WHERE at < ?`)
1683
+ .all(t - Math.max(ARCHIVE_UNDO_MS, 30 * DAY)) as {session_file: string}[];
1684
+ for (const {session_file} of marks)
1685
+ if (!fs.existsSync(session_file))
1686
+ this.db
1687
+ .prepare(`DELETE FROM archive WHERE session_file = ?`)
1688
+ .run(session_file);
1689
+ }
1690
+
1691
+ /** Prune when the last prune is a day old. Cheap enough to call on every open. */
1692
+ pruneIfDue(): boolean {
1693
+ const row = this.db
1694
+ .prepare(`SELECT value FROM meta WHERE key = 'last_prune'`)
1695
+ .get() as {value: string} | undefined;
1696
+ if (row && Number(row.value) > this.now() - DAY) return false;
1697
+ this.prune();
1698
+ return true;
1699
+ }
1700
+
1701
+ protected identityOf(row: {
1702
+ pid: number;
1703
+ start_time: string | null;
1704
+ boot_id: string | null;
1705
+ host: string | null;
1706
+ }): ProcessIdentity {
1707
+ return {
1708
+ pid: row.pid,
1709
+ startTime: row.start_time,
1710
+ bootId: row.boot_id,
1711
+ host: row.host ?? '',
1712
+ };
1713
+ }
1714
+
1715
+ protected rolesOf(sessionFile: string): string[] {
1716
+ return (
1717
+ this.db
1718
+ .prepare(`SELECT role FROM role WHERE session_file = ? ORDER BY role`)
1719
+ .all(sessionFile) as {role: string}[]
1720
+ ).map((r) => r.role);
1721
+ }
1722
+
1723
+ private toPresence(r: PresenceRow): Presence {
1724
+ return {
1725
+ sessionFile: r.session_file,
1726
+ sessionId: r.session_id,
1727
+ cwd: r.cwd,
1728
+ branch: r.branch,
1729
+ roles: this.rolesOf(r.session_file),
1730
+ state: r.state,
1731
+ status: r.status,
1732
+ refs: r.refs ? (JSON.parse(r.refs) as string[]) : [],
1733
+ waitingOn: r.waiting_on,
1734
+ wake: r.wake === 1,
1735
+ live: this.probe.isAlive(this.identityOf(r)),
1736
+ pid: r.pid,
1737
+ updatedAt: r.updated_at,
1738
+ settledAt: r.settled_at,
1739
+ };
1740
+ }
1741
+ }
1742
+
1743
+ export function openShipmates(opts: ShipmatesOptions = {}): Shipmates {
1744
+ return new Shipmates(opts);
1745
+ }