@operad-io/mcp 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/channel.ts ADDED
@@ -0,0 +1,658 @@
1
+ /**
2
+ * The Claude Code channel: one-way change notifications beside the read tools.
3
+ *
4
+ * Two subscriptions are the source: the store's object changes, and the run
5
+ * log's changes. The waiting and running flags come from the runs, so a wait
6
+ * that opens or a step that starts touches no object. Each change re-reads the
7
+ * object's row. A watch is the fast path and each backend's own timer is the
8
+ * fallback, so a change another process writes is seen too. The server
9
+ * remembers the row it last saw for each object and sends only when its state
10
+ * differs or its waiting flag turns on, and never repeats the row it last sent.
11
+ */
12
+
13
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
14
+ import { dirname } from "node:path";
15
+ import {
16
+ CHANNEL_NOTIFY_KINDS,
17
+ DEFAULT_MCP_CHANNEL,
18
+ messageOf,
19
+ type ChannelNotifyKind,
20
+ ViewError,
21
+ type LogBackend,
22
+ type ObjectRef,
23
+ type PendingItem,
24
+ type PluginRegistry,
25
+ type ViewObject,
26
+ type ViewRow,
27
+ type Views,
28
+ } from "@operad-io/engine";
29
+
30
+ /** The experiment capability Claude Code reads a channel declaration from. */
31
+ export const CHANNEL_CAPABILITY = "claude/channel";
32
+
33
+ /** The capability this server never declares: it relays no permission prompts. */
34
+ export const CHANNEL_PERMISSION_CAPABILITY = "claude/channel/permission";
35
+
36
+ /** The notification method a channel event is sent with. */
37
+ export const CHANNEL_METHOD = "notifications/claude/channel";
38
+
39
+ /** The paragraph the channel adds to the server's instructions. */
40
+ export const CHANNEL_INSTRUCTIONS =
41
+ "Events arrive as `<channel>` blocks with the meta attributes `id`, `type`, `state`, `previous`, `waiting`, `running` and `reason`, and `step` while the object has an active run. `reason` says why the block was sent: `waiting` (something now waits for a person; the content carries the reason when the object has one), `ended` (the object reached a final state) or `loop` (the object reached the same state several times in a row with no wait or end between, so it is going round in circles). Other state changes send nothing unless `mcp.channel.notify` in the operad config.json lists `changes`, which sends every state change with reason `changes`. They are one-way: there is no reply tool. Read the details with `show`, `section`, `pending` and `history`.";
42
+
43
+ /** One notification's parameters: a one-line content and string meta. */
44
+ export interface ChannelNotification {
45
+ readonly content: string;
46
+ readonly meta: {
47
+ readonly id: string;
48
+ readonly type: string;
49
+ readonly state: string;
50
+ readonly previous: string;
51
+ readonly waiting: string;
52
+ readonly running: string;
53
+ /** Why the block was sent. */
54
+ readonly reason: ChannelReason;
55
+ /** The active run's last step; absent when the object has no active run. */
56
+ readonly step?: string;
57
+ };
58
+ }
59
+
60
+ /** Why a block was sent; `changes` is only used when `notify` lists it. */
61
+ export type ChannelReason = "waiting" | "ended" | "loop" | "changes";
62
+
63
+ /** A `notify` entry that is not a kind of block. */
64
+ export class ChannelNotifyError extends Error {
65
+ constructor(message: string) {
66
+ super(message);
67
+ this.name = "ChannelNotifyError";
68
+ }
69
+ }
70
+
71
+ /** A `--types` entry that is not an object type with views. */
72
+ export class ChannelTypeError extends Error {
73
+ constructor(message: string) {
74
+ super(message);
75
+ this.name = "ChannelTypeError";
76
+ }
77
+ }
78
+
79
+ /** What a channel needs: the views, both subscriptions and one writer. */
80
+ export interface ChannelOptions {
81
+ readonly views: Views;
82
+ readonly registry: PluginRegistry;
83
+ /** The run log; its changes carry the waiting and running flags. */
84
+ readonly log?: LogBackend | undefined;
85
+ /**
86
+ * Hold every notification until `release` is called. The channel still reads
87
+ * its starting rows and keeps diffing, so the release sends the changes seen
88
+ * since the start.
89
+ */
90
+ readonly hold?: boolean | undefined;
91
+ /** The object types to report; the default is every type with views. */
92
+ readonly types?: readonly string[] | undefined;
93
+ /** What to send a block for; the default is waits, ends and loops. */
94
+ readonly notify?: readonly ChannelNotifyKind[] | undefined;
95
+ /** How many arrivals at one state make a loop; the default is 3. */
96
+ readonly loopAfter?: number | undefined;
97
+ /** Reads the pending items, whose prompt is the reason of a wait. */
98
+ readonly pending?: (() => Promise<readonly PendingItem[]>) | undefined;
99
+ /**
100
+ * A JSON file that keeps the row each object's last delivered block reported,
101
+ * so a restarted server does not send a block again. Without it the memory
102
+ * lasts as long as the channel.
103
+ */
104
+ readonly sentFile?: string | undefined;
105
+ readonly send: (
106
+ notification: ChannelNotification,
107
+ ) => void | Promise<void>;
108
+ readonly onLog?: ((message: string) => void) | undefined;
109
+ }
110
+
111
+ /** A running channel. Closing it stops the subscription and waits for sends. */
112
+ export interface ChannelHandle {
113
+ /** Sends the notifications held since the start, then stops holding. */
114
+ release(): Promise<void>;
115
+ close(): Promise<void>;
116
+ }
117
+
118
+ interface SeenRow {
119
+ readonly state: string;
120
+ readonly waiting: boolean;
121
+ readonly running: boolean;
122
+ /** The plugin marked the state final; not part of what was sent. */
123
+ readonly final: boolean;
124
+ /** A loop block was delivered for the stretch this row belongs to. */
125
+ readonly looped?: boolean;
126
+ }
127
+
128
+ /** Reads a run's object key, such as `task:42`. */
129
+ function objectOf(key: string | undefined): ObjectRef | undefined {
130
+ if (key === undefined) return undefined;
131
+ const at = key.indexOf(":");
132
+ if (at <= 0 || at === key.length - 1) return undefined;
133
+ return { type: key.slice(0, at), id: key.slice(at + 1) };
134
+ }
135
+
136
+ function rowKey(type: string, id: string): string {
137
+ return `${type}\u0000${id}`;
138
+ }
139
+
140
+ function seenRow(row: ViewRow): SeenRow {
141
+ return {
142
+ state: row.state,
143
+ waiting: row.waiting,
144
+ running: row.running,
145
+ final: row.final === true,
146
+ };
147
+ }
148
+
149
+ function sameRow(left: SeenRow, right: SeenRow): boolean {
150
+ return (
151
+ left.state === right.state &&
152
+ left.waiting === right.waiting &&
153
+ left.running === right.running
154
+ );
155
+ }
156
+
157
+ function flattenNewlines(value: string): string {
158
+ return value.replace(/[\r\n]+/g, " ");
159
+ }
160
+
161
+ function contentOf(
162
+ row: ViewRow,
163
+ previous: string,
164
+ fallback: string | undefined,
165
+ ): string {
166
+ const text =
167
+ typeof row.note === "string" && row.note.trim().length > 0
168
+ ? row.note
169
+ : fallback;
170
+ const note =
171
+ text !== undefined && text.trim().length > 0 ? `: ${flattenNewlines(text)}` : "";
172
+ return `${flattenNewlines(row.id)} ${previous} -> ${flattenNewlines(row.state)}${note}`;
173
+ }
174
+
175
+ function notificationOf(
176
+ type: string,
177
+ row: ViewRow,
178
+ previous: string,
179
+ step: string | undefined,
180
+ reason: ChannelReason,
181
+ fallback?: string,
182
+ ): ChannelNotification {
183
+ return {
184
+ content: contentOf(row, previous, fallback),
185
+ meta: {
186
+ id: flattenNewlines(row.id),
187
+ type,
188
+ state: flattenNewlines(row.state),
189
+ previous: flattenNewlines(previous),
190
+ waiting: row.waiting ? "true" : "false",
191
+ running: row.running ? "true" : "false",
192
+ reason,
193
+ ...(step === undefined ? {} : { step: flattenNewlines(step) }),
194
+ },
195
+ };
196
+ }
197
+
198
+ /** A notification with the key and row its delivery records as sent. */
199
+ interface Held {
200
+ readonly notification: ChannelNotification;
201
+ readonly key: string;
202
+ readonly row: SeenRow;
203
+ }
204
+
205
+ function isSeenRow(value: unknown): value is SeenRow {
206
+ if (typeof value !== "object" || value === null) return false;
207
+ const row = value as Record<string, unknown>;
208
+ return (
209
+ typeof row.state === "string" &&
210
+ typeof row.waiting === "boolean" &&
211
+ typeof row.running === "boolean"
212
+ );
213
+ }
214
+
215
+ class ClaudeChannel implements ChannelHandle {
216
+ private readonly views: Views;
217
+ private readonly registry: PluginRegistry;
218
+ private readonly types: ReadonlySet<string>;
219
+ private readonly sendNotification: (
220
+ notification: ChannelNotification,
221
+ ) => void | Promise<void>;
222
+ private readonly onLog: (message: string) => void;
223
+ private readonly last = new Map<string, SeenRow>();
224
+ /** The row each object's last block reported. */
225
+ private readonly sent = new Map<string, SeenRow>();
226
+ /** Rows of blocks held for release, which count as sent for comparing. */
227
+ private readonly pendingSent = new Map<string, SeenRow>();
228
+ private readonly notify: ReadonlySet<ChannelNotifyKind>;
229
+ private readonly loopAfter: number;
230
+ private readonly pendingItems:
231
+ | (() => Promise<readonly PendingItem[]>)
232
+ | undefined;
233
+ /**
234
+ * Per object: how often each state was reached since the last wait or end,
235
+ * and whether a loop block was already sent for that stretch.
236
+ */
237
+ private readonly visits = new Map<
238
+ string,
239
+ { counts: Map<string, number>; looped: boolean }
240
+ >();
241
+ /** Objects whose current wait was skipped because its plugin answers it. */
242
+ private readonly quiet = new Map<string, ObjectRef>();
243
+ private readonly sentFile: string | undefined;
244
+ private readonly log: LogBackend | undefined;
245
+ /** Types whose starting rows could not be read: a first sighting is a baseline. */
246
+ private readonly unseeded = new Set<string>();
247
+ private held: Held[] | undefined;
248
+ private stops: (() => void)[] = [];
249
+ private queue: Promise<void> = Promise.resolve();
250
+ private closed = false;
251
+
252
+ constructor(options: ChannelOptions) {
253
+ this.views = options.views;
254
+ this.registry = options.registry;
255
+ if (options.types !== undefined) {
256
+ for (const type of options.types) {
257
+ if (this.registry.viewsFor(type) === undefined) {
258
+ throw new ChannelTypeError(
259
+ `mcp --types: "${type}" is not an object type with views`,
260
+ );
261
+ }
262
+ }
263
+ }
264
+ this.types =
265
+ options.types === undefined
266
+ ? new Set(
267
+ this.registry
268
+ .objectTypes()
269
+ .map((entry) => entry.type)
270
+ .filter((type) => this.registry.viewsFor(type) !== undefined),
271
+ )
272
+ : new Set(options.types);
273
+ for (const kind of options.notify ?? []) {
274
+ if (!CHANNEL_NOTIFY_KINDS.includes(kind)) {
275
+ throw new ChannelNotifyError(
276
+ `mcp channel notify: unknown entry "${String(kind)}"`,
277
+ );
278
+ }
279
+ }
280
+ this.notify = new Set(options.notify ?? DEFAULT_MCP_CHANNEL.notify);
281
+ this.loopAfter = options.loopAfter ?? DEFAULT_MCP_CHANNEL.loopAfter;
282
+ this.pendingItems = options.pending;
283
+ this.log = options.log;
284
+ this.sentFile = options.sentFile;
285
+ this.held = options.hold === true ? [] : undefined;
286
+ this.sendNotification = options.send;
287
+ this.onLog = options.onLog ?? ((message) => console.error(message));
288
+ }
289
+
290
+ async start(): Promise<void> {
291
+ await this.loadSent();
292
+ for (const type of this.types) {
293
+ try {
294
+ await this.seed(type);
295
+ } catch (error) {
296
+ this.unseeded.add(type);
297
+ this.onLog(
298
+ `channel: the starting rows of "${type}" could not be read: ${messageOf(error)}`,
299
+ );
300
+ }
301
+ }
302
+ if (this.closed) return;
303
+ this.stops.push(
304
+ this.registry.store.subscribe((object) => {
305
+ this.enqueue(object);
306
+ }),
307
+ );
308
+ if (this.log?.subscribe === undefined) {
309
+ this.onLog(
310
+ "channel: the run log cannot notify, so a wait or a running step is not reported until the object changes",
311
+ );
312
+ } else {
313
+ this.stops.push(
314
+ this.log.subscribe((change) => {
315
+ const object = objectOf(change.object);
316
+ if (object !== undefined) this.enqueue(object);
317
+ }),
318
+ );
319
+ }
320
+ }
321
+
322
+ async release(): Promise<void> {
323
+ this.queue = this.queue.then(async () => {
324
+ const held = this.held;
325
+ this.held = undefined;
326
+ for (const entry of held ?? []) {
327
+ if (this.closed) return;
328
+ await this.deliver(entry);
329
+ }
330
+ });
331
+ await this.queue;
332
+ }
333
+
334
+ async close(): Promise<void> {
335
+ this.closed = true;
336
+ for (const stop of this.stops) stop();
337
+ this.stops = [];
338
+ await this.queue;
339
+ }
340
+
341
+ /** Sends one block, then records its row as the last one delivered. */
342
+ private async deliver(entry: Held): Promise<void> {
343
+ await this.sendNotification(entry.notification);
344
+ const looped = this.visits.get(entry.key)?.looped === true;
345
+ this.sent.set(entry.key, looped ? { ...entry.row, looped } : entry.row);
346
+ if (this.pendingSent.get(entry.key) === entry.row) {
347
+ this.pendingSent.delete(entry.key);
348
+ }
349
+ await this.saveSent();
350
+ }
351
+
352
+ private async loadSent(): Promise<void> {
353
+ if (this.sentFile === undefined) return;
354
+ let text: string;
355
+ try {
356
+ text = await readFile(this.sentFile, "utf8");
357
+ } catch (error) {
358
+ if ((error as { code?: unknown }).code === "ENOENT") return;
359
+ this.onLog(`channel: the sent rows could not be read: ${messageOf(error)}`);
360
+ return;
361
+ }
362
+ try {
363
+ const parsed: unknown = JSON.parse(text);
364
+ if (typeof parsed !== "object" || parsed === null) return;
365
+ for (const [key, value] of Object.entries(parsed)) {
366
+ if (isSeenRow(value)) {
367
+ this.sent.set(key, {
368
+ state: value.state,
369
+ waiting: value.waiting,
370
+ running: value.running,
371
+ final: false,
372
+ });
373
+ if ((value as { looped?: unknown }).looped === true) {
374
+ this.visits.set(key, { counts: new Map(), looped: true });
375
+ }
376
+ }
377
+ }
378
+ } catch (error) {
379
+ this.onLog(`channel: the sent rows could not be read: ${messageOf(error)}`);
380
+ }
381
+ }
382
+
383
+ private async saveSent(): Promise<void> {
384
+ if (this.sentFile === undefined) return;
385
+ try {
386
+ await mkdir(dirname(this.sentFile), { recursive: true });
387
+ const temp = `${this.sentFile}.${process.pid}.tmp`;
388
+ await writeFile(temp, JSON.stringify(Object.fromEntries(this.sent)));
389
+ await rename(temp, this.sentFile);
390
+ } catch (error) {
391
+ this.onLog(`channel: the sent rows could not be saved: ${messageOf(error)}`);
392
+ }
393
+ }
394
+
395
+ /** Reads the rows that exist now; none of them is a change to report. */
396
+ private async seed(type: string): Promise<void> {
397
+ let cursor: string | undefined;
398
+ for (;;) {
399
+ const page = await this.views.list(
400
+ type,
401
+ cursor === undefined ? {} : { cursor },
402
+ );
403
+ for (const row of page.rows) {
404
+ this.last.set(rowKey(type, row.id), seenRow(row));
405
+ }
406
+ if (page.next === undefined) return;
407
+ cursor = page.next;
408
+ }
409
+ }
410
+
411
+ /**
412
+ * Counts the arrival at the row's state. A wait or an end starts a new
413
+ * stretch. Returns true once per stretch, when a state is reached
414
+ * `loopAfter` times.
415
+ */
416
+ private countVisit(
417
+ key: string,
418
+ row: SeenRow,
419
+ stateChanged: boolean,
420
+ reset: boolean,
421
+ ): boolean {
422
+ if (reset) {
423
+ const fresh = {
424
+ counts: new Map<string, number>(),
425
+ looped: false,
426
+ };
427
+ if (!row.final && stateChanged) fresh.counts.set(row.state, 1);
428
+ this.visits.set(key, fresh);
429
+ return false;
430
+ }
431
+ let entry = this.visits.get(key);
432
+ if (entry === undefined) {
433
+ entry = { counts: new Map(), looped: false };
434
+ this.visits.set(key, entry);
435
+ }
436
+ if (!stateChanged) return false;
437
+ const count = (entry.counts.get(row.state) ?? 0) + 1;
438
+ entry.counts.set(row.state, count);
439
+ if (count >= this.loopAfter && !entry.looped) {
440
+ entry.looped = true;
441
+ return true;
442
+ }
443
+ return false;
444
+ }
445
+
446
+ private enqueue(object: ObjectRef): void {
447
+ if (this.closed) return;
448
+ this.queue = this.queue
449
+ .then(() => this.handle(object))
450
+ .catch((error) => {
451
+ this.onLog(`channel: ${messageOf(error)}`);
452
+ });
453
+ }
454
+
455
+ /** The last step of the object's active run, if it has one. */
456
+ private async stepOf(object: ObjectRef): Promise<string | undefined> {
457
+ if (this.log === undefined) return undefined;
458
+ try {
459
+ const key = `${object.type}:${object.id}`;
460
+ const runs = await this.log.runs({ active: true });
461
+ // An object can have active runs of several flows: report the run with
462
+ // the latest fact, which is the one that changed the object just now.
463
+ let step: string | undefined;
464
+ let latest:
465
+ | { time: number; started: number; seq: number; runId: string }
466
+ | undefined;
467
+ for (const run of runs) {
468
+ if (run.object !== key) continue;
469
+ let runStep: string | undefined;
470
+ let time = run.startedAt;
471
+ let seq = 0;
472
+ for await (const fact of this.log.read(run.runId)) {
473
+ time = Math.max(time, fact.time);
474
+ seq = Math.max(seq, fact.seq);
475
+ const payload = fact.payload;
476
+ if (
477
+ fact.kind === "step_entered" &&
478
+ typeof payload === "object" &&
479
+ payload !== null &&
480
+ !Array.isArray(payload) &&
481
+ payload.kind !== "end" &&
482
+ typeof payload.step === "string"
483
+ ) {
484
+ runStep = payload.step;
485
+ }
486
+ }
487
+ if (
488
+ latest === undefined ||
489
+ laterRun(
490
+ { time, started: run.startedAt, seq, runId: run.runId },
491
+ latest,
492
+ )
493
+ ) {
494
+ latest = { time, started: run.startedAt, seq, runId: run.runId };
495
+ step = runStep;
496
+ }
497
+ }
498
+ return step;
499
+ } catch (error) {
500
+ this.onLog(`channel: the step of "${object.type}:${object.id}" could not be read: ${messageOf(error)}`);
501
+ return undefined;
502
+ }
503
+ }
504
+
505
+ private pendingSnapshot: readonly PendingItem[] | undefined;
506
+
507
+ /** The pending item of the object's wait, if it has one. */
508
+ private async waitItem(object: ObjectRef): Promise<PendingItem | undefined> {
509
+ if (this.pendingItems === undefined) return undefined;
510
+ try {
511
+ const key = `${object.type}:${object.id}`;
512
+ // One pass over the quiet objects reads the list once.
513
+ const items = this.pendingSnapshot ?? (await this.pendingItems());
514
+ return items.find(
515
+ (entry) => entry.object === key || entry.covers?.includes(key) === true,
516
+ );
517
+ } catch (error) {
518
+ this.onLog(`channel: the pending items could not be read: ${messageOf(error)}`);
519
+ return undefined;
520
+ }
521
+ }
522
+
523
+ private async handle(object: ObjectRef, recheck = true): Promise<void> {
524
+ if (this.closed) return;
525
+ if (recheck && this.quiet.size > 0) {
526
+ // A change elsewhere (a plan's auto level) can end an automatic answer.
527
+ // The pending list is read once for the whole pass.
528
+ try {
529
+ this.pendingSnapshot = await this.pendingItems?.();
530
+ } catch (error) {
531
+ this.onLog(`channel: the pending items could not be read: ${messageOf(error)}`);
532
+ }
533
+ try {
534
+ for (const [quietKey, ref] of [...this.quiet]) {
535
+ if (quietKey !== rowKey(object.type, object.id)) {
536
+ await this.handle(ref, false);
537
+ }
538
+ }
539
+ } finally {
540
+ this.pendingSnapshot = undefined;
541
+ }
542
+ }
543
+ if (!this.types.has(object.type)) return;
544
+ let current: ViewObject;
545
+ try {
546
+ current = await this.views.get(`${object.type}:${object.id}`);
547
+ } catch (error) {
548
+ if (error instanceof ViewError && error.kind === "not-found") {
549
+ // A deleted object: forget it, so a new one with the same id is new.
550
+ this.last.delete(rowKey(object.type, object.id));
551
+ this.pendingSent.delete(rowKey(object.type, object.id));
552
+ this.visits.delete(rowKey(object.type, object.id));
553
+ this.quiet.delete(rowKey(object.type, object.id));
554
+ if (this.sent.delete(rowKey(object.type, object.id))) {
555
+ await this.saveSent();
556
+ }
557
+ return;
558
+ }
559
+ this.onLog(
560
+ `channel: "${object.type}:${object.id}" could not be read: ${messageOf(error)}`,
561
+ );
562
+ return;
563
+ }
564
+ const row = current.row;
565
+ const key = rowKey(object.type, row.id);
566
+ const next = seenRow(row);
567
+ const previous = this.last.get(key);
568
+ this.last.set(key, next);
569
+ if (previous === undefined && this.unseeded.has(object.type)) return;
570
+ const stateChanged = previous === undefined || previous.state !== next.state;
571
+ const waitStart = next.waiting && previous?.waiting !== true;
572
+ // A wait the plugin answers itself is not announced; if the answer does
573
+ // not come, the next change finds the wait no longer marked and announces.
574
+ let item: PendingItem | undefined;
575
+ let waitingOn = waitStart;
576
+ if (next.waiting && (waitStart || this.quiet.has(key))) {
577
+ item = await this.waitItem(object);
578
+ if (item?.auto === true) {
579
+ this.quiet.set(key, object);
580
+ waitingOn = false;
581
+ } else if (item?.announce === false) {
582
+ // Pending, but its plugin says the lead needs no block for it.
583
+ this.quiet.delete(key);
584
+ waitingOn = false;
585
+ } else {
586
+ this.quiet.delete(key);
587
+ waitingOn = true;
588
+ }
589
+ } else if (!next.waiting) {
590
+ this.quiet.delete(key);
591
+ }
592
+ const ended = next.final && previous?.final !== true;
593
+ const looped = this.countVisit(key, next, stateChanged, waitStart || ended);
594
+ // What happened, in order of weight; a kind that is not listed sends only
595
+ // when `changes` is, which sends every state change and wait.
596
+ const kind: ChannelReason | undefined = ended
597
+ ? "ended"
598
+ : waitingOn
599
+ ? "waiting"
600
+ : looped
601
+ ? "loop"
602
+ : undefined;
603
+ const every =
604
+ this.notify.has("changes") && (stateChanged || waitingOn) && !this.quiet.has(key);
605
+ if (kind === undefined && !every) return;
606
+ const reason: ChannelReason = kind ?? "changes";
607
+ if (kind !== undefined && !this.notify.has(kind) && !every) return;
608
+ const lastSent = this.pendingSent.get(key) ?? this.sent.get(key);
609
+ // A loop is counted in memory, so it is never a repeat of a sent row.
610
+ if (reason !== "loop" && lastSent !== undefined && sameRow(lastSent, next)) {
611
+ return;
612
+ }
613
+ const notification = notificationOf(
614
+ object.type,
615
+ row,
616
+ previous?.state ?? "new",
617
+ await this.stepOf(object),
618
+ reason,
619
+ // A block sent for another reason still carries the wait's prompt.
620
+ next.waiting ? (item ?? (await this.waitItem(object)))?.prompt : undefined,
621
+ );
622
+ const entry: Held = { notification, key, row: next };
623
+ if (this.held !== undefined) {
624
+ this.held.push(entry);
625
+ // Held, not yet delivered: later changes still compare against it.
626
+ this.pendingSent.set(key, next);
627
+ } else {
628
+ await this.deliver(entry);
629
+ }
630
+ }
631
+ }
632
+
633
+ interface RunStamp {
634
+ readonly time: number;
635
+ readonly started: number;
636
+ readonly seq: number;
637
+ readonly runId: string;
638
+ }
639
+
640
+ /** Whether `a` is the later run: ties on time break on start, seq, then id. */
641
+ function laterRun(a: RunStamp, b: RunStamp): boolean {
642
+ if (a.time !== b.time) return a.time > b.time;
643
+ if (a.started !== b.started) return a.started > b.started;
644
+ if (a.seq !== b.seq) return a.seq > b.seq;
645
+ return a.runId > b.runId;
646
+ }
647
+
648
+ /**
649
+ * Starts the channel after reading the starting rows, and subscribes to the
650
+ * store. Call `close` when the server stops reading stdin.
651
+ */
652
+ export async function startClaudeChannel(
653
+ options: ChannelOptions,
654
+ ): Promise<ChannelHandle> {
655
+ const channel = new ClaudeChannel(options);
656
+ await channel.start();
657
+ return channel;
658
+ }