-
Notifications
You must be signed in to change notification settings - Fork 60
Expand file tree
/
Copy pathattach-drive.ts
More file actions
1422 lines (1351 loc) · 56.7 KB
/
Copy pathattach-drive.ts
File metadata and controls
1422 lines (1351 loc) · 56.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* `agent-relay drive <name>` — interactive read-write take-over client.
*
* Attaches to a running agent, puts it in `auto_inject` inbound delivery mode so
* relay messages keep reaching it live, and forwards your keystrokes to the
* worker's PTY. Watching an agent never pauses it: a driven agent goes on
* receiving its peers' messages exactly as it would unattended, which is what
* makes it possible to observe a team coordinating instead of freezing it by
* looking at it.
*
* `Ctrl+]` toggles the worker into `manual_flush` when you want the screen to
* hold still while you type — messages park in a per-worker queue, the status
* line counts them (`pending=N`), and the next press drains the queue and
* returns to live delivery. The out-of-band commands `local agent message
* flush`, `local agent message hold`, and `local agent message auto` still work
* from another terminal: a bare `flush` during a drive session injects the
* queued backlog immediately (the broker follows the handoff with a one-shot
* `flush_injections` frame that exempts it from the interactive hold) while
* leaving the mode — and the parking of later messages — unchanged. `Ctrl+C`
* detaches, restores the worker's previous inbound delivery mode, and leaves
* the agent running under the broker — `drive` never kills the worker.
*
* Sequence of operations on attach (subscribe-first, so no output around
* attach time is lost and none is double-painted):
*
* 1. Discover broker connection (CLI flag → env → connection.json).
* 2. `GET /api/spawned/{name}/delivery-mode` → remember the previous mode.
* 3. `PUT /api/spawned/{name}/delivery-mode` → assert `auto_inject`.
* 4. `GET /api/events/replay` → capture the durable-event `sinceSeq` cutoff,
* then `GET /api/spawned/{name}/pending` → seed the status-line counter
* and the set of already-queued `event_id`s. Cutoff-first + id-dedupe
* keeps the counter exact across the attach race (no under/over-count).
* 5. Open `/ws?sinceSeq=<cutoff>`, subscribe, and buffer live output. The
* cutoff stops the broker replaying historical durable events that would
* inflate the pending counter; any replayed `delivery_queued` already in
* the seed is deduped by `event_id`.
* 6. On subscribe: `captureAndRenderSnapshot` repaints the agent's current
* screen; buffered chunks are reconciled against the snapshot's stream
* offset (drop what the snapshot already shows, apply the rest).
* 7. Forward the initial terminal size (resize now lands in the live stream,
* not a dead zone), then open the SDK PTY input stream and switch local
* stdin to raw mode.
*
* On detach (clean or abnormal), best-effort `PUT .../delivery-mode` restores the
* previous mode so the queue doesn't fill up indefinitely.
*/
import { Buffer } from 'node:buffer';
import { randomUUID } from 'node:crypto';
import { StringDecoder } from 'node:string_decoder';
import type { InboundDeliveryMode } from '@agent-relay/harness-driver';
import WebSocket from 'ws';
import {
captureAndRenderSnapshot,
canReserveStatusLine,
clampStatusLineText,
createBackpressureAwareWriter,
DETACH_CLEANUP_DEADLINE_MS,
pickInitialTerminalCols,
pickInitialTerminalRows,
prepareAttachTarget,
reserveStatusLineRow,
renderChildScrollRegion,
resetLocalTerminalOnDetach,
restoreInboundDeliveryModeOnDetach,
StatusLineController,
StreamSyncBuffer,
switchInboundDeliveryModeOrAbort,
syncInitialPtySize,
TerminalScrollRegionTracker,
type AttachSnapshotConnection,
type AttachSnapshotDeps,
} from '../lib/attach.js';
import {
defaultStateDir,
readConnectionFileFromDisk,
toWsUrl,
type BrokerConnection,
} from '../lib/broker-connection.js';
import { defaultExit, runSignalHandler } from '../lib/exit.js';
import {
createBrokerClient,
mapBrokerSdkFailure,
type PtyInputStreamOptions,
type PtyInputWriteResult,
} from '../lib/attach-broker.js';
import { describeError } from './describe-error.js';
import { createPredictiveEcho, type CreatePredictiveEchoOptions } from './predictive-echo-screen.js';
import type { PredictiveEcho } from '@agent-relay/harness-driver';
type ExitFn = (code: number) => never;
/** Wire string for the broker's `InboundDeliveryMode` enum. */
export type { InboundDeliveryMode };
/** Minimal WebSocket surface we depend on — same shape as `view`'s. */
export interface DriveWebSocket {
on(event: 'open', listener: () => void): unknown;
on(event: 'message', listener: (data: WebSocket.RawData) => void): unknown;
on(event: 'close', listener: (code: number, reason: Buffer) => void): unknown;
on(event: 'error', listener: (err: Error) => void): unknown;
close(code?: number, reason?: string): void;
}
export type DriveWebSocketFactory = (url: string, headers: Record<string, string>) => DriveWebSocket;
export interface DriveSignalRegistrar {
(signal: NodeJS.Signals, handler: () => void | Promise<void>): void | (() => void);
}
/** Stdin surface — tests provide a fake that never touches the real TTY. */
export interface DriveStdin {
setRawMode?: (mode: boolean) => unknown;
isTTY?: boolean;
isRaw?: boolean;
resume(): unknown;
pause(): unknown;
on(event: 'data', listener: (chunk: Buffer) => void): unknown;
off?(event: 'data', listener: (chunk: Buffer) => void): unknown;
removeListener?(event: 'data', listener: (chunk: Buffer) => void): unknown;
}
/**
* Local terminal-size source. Wraps `process.stdout` in production so
* the resize wiring reads the user's actual terminal dimensions and
* gets a SIGWINCH-equivalent `'resize'` event for free. Tests inject a
* controllable fake.
*/
export interface DriveTerminal {
/** Current `(rows, cols)`. Returns `null` when stdout is not a TTY,
* in which case resize forwarding is skipped entirely. */
getSize(): { rows: number; cols: number } | null;
/** Subscribe to local-terminal resize events. Returns an unsubscribe
* function the client calls during teardown. */
onResize(handler: () => void): () => void;
}
export interface CliPtyInputStream {
waitUntilOpen(): Promise<void>;
send(data: string): Promise<PtyInputWriteResult>;
close(code?: number, reason?: string): void;
/** Smoothed input→ack RTT (ms), or null before the first ack. */
readonly srttMs?: number | null;
}
export interface DriveDependencies {
/** Reads `<state-dir>/connection.json` and returns parsed JSON, or null. */
readConnectionFile: (stateDir: string) => unknown;
/** Project paths helper — used to pick the default state dir. */
getDefaultStateDir: () => string;
/** Environment variables (so tests can inject). */
env: NodeJS.ProcessEnv;
/** Factory for the WebSocket — overridden in tests with a mock. */
createWebSocket: DriveWebSocketFactory;
/** Where the PTY chunks get written. Defaults to `process.stdout.write`. */
writeChunk: (chunk: string) => void;
/**
* Tear down the backpressure-aware writer on detach: drop its pending queue
* and unhook its `'drain'` listener so nothing flushes to stdout after the
* session settles. Defaults to the writer created in {@link withDefaults};
* tests that inject their own `writeChunk` can omit it (no-op).
*/
disposeWriter?: () => void;
/** Signal registration (so tests can drive SIGINT without killing the test). */
onSignal: DriveSignalRegistrar;
log: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
exit: ExitFn;
/** HTTP client used for mode/pending/flush/resize calls. Defaults to global `fetch`. */
fetch: typeof globalThis.fetch;
/** Override for the snapshot-on-attach helper (tests substitute a stub). */
captureAndRenderSnapshot: (
connection: AttachSnapshotConnection,
name: string,
deps: AttachSnapshotDeps
) => ReturnType<typeof captureAndRenderSnapshot>;
/** Stdin handle — defaults to `process.stdin`. */
stdin: DriveStdin;
/** Local terminal size source — defaults to `process.stdout`. */
terminal: DriveTerminal;
/** Opens the SDK PTY input stream used for raw human keystrokes. */
openInputStream: (
connection: BrokerConnection,
name: string,
options?: PtyInputStreamOptions
) => CliPtyInputStream;
/**
* Builds the adaptive predictive-echo engine, or returns null to disable
* it (degenerate terminal). Omitted by tests that want plain pass-through.
*/
createPredictiveEcho?: (opts: CreatePredictiveEchoOptions) => PredictiveEcho | null;
/**
* Minimum ms between status-line repaints (coalescing window). Defaults to a
* small positive value in production to shrink the per-chunk splice window;
* tests set `0` for immediate, deterministic paints.
*/
statusRepaintCoalesceMs?: number;
/**
* Interval (ms) at which the session re-asserts PTY resize ownership by
* re-sending its current size (single-resizer policy, #1247). Keeps an
* idle-but-live session from being superseded after the broker's
* stale-owner window; the broker treats a same-size re-assert as a no-op
* refresh (no SIGWINCH). Defaults to 60000. Set `0` to disable (tests).
*/
ownershipReassertMs?: number;
}
function withDefaults(overrides: Partial<DriveDependencies> = {}): DriveDependencies {
const fetchFn: typeof globalThis.fetch = overrides.fetch ?? ((input, init) => fetch(input, init));
const writer = createBackpressureAwareWriter(process.stdout);
return {
readConnectionFile: readConnectionFileFromDisk,
getDefaultStateDir: defaultStateDir,
env: process.env,
createWebSocket: (url, headers) => new WebSocket(url, { headers }) as DriveWebSocket,
writeChunk: writer.write,
disposeWriter: writer.dispose,
statusRepaintCoalesceMs: 40,
onSignal: (signal, handler) => {
const listener = () => runSignalHandler(handler);
process.on(signal, listener);
return () => process.off(signal, listener);
},
log: (...args: unknown[]) => console.error(...args),
error: (...args: unknown[]) => console.error(...args),
exit: defaultExit,
fetch: fetchFn,
captureAndRenderSnapshot,
stdin: process.stdin as DriveStdin,
terminal: {
getSize: () => {
// process.stdout.isTTY is `true | undefined`; reading
// rows/columns on a non-TTY returns `undefined`.
const stdout = process.stdout;
if (!stdout.isTTY) return null;
const rows = stdout.rows;
const cols = stdout.columns;
if (typeof rows !== 'number' || typeof cols !== 'number') return null;
return { rows, cols };
},
onResize: (handler) => {
// Node automatically translates SIGWINCH into a `'resize'`
// event on `process.stdout` when stdout is a TTY.
process.stdout.on('resize', handler);
return () => process.stdout.off('resize', handler);
},
},
openInputStream: (connection, name, options) => openPtyInputStream(connection, name, fetchFn, options),
createPredictiveEcho,
...overrides,
};
}
/** ----- HTTP helpers ----- */
/** `GET /api/spawned/{name}/delivery-mode` → `'manual_flush' | 'auto_inject'` or `null` on failure. */
export async function getInboundDeliveryMode(
connection: BrokerConnection,
name: string,
fetchFn: typeof globalThis.fetch
): Promise<InboundDeliveryMode | null> {
try {
return await createBrokerClient(connection, fetchFn).getInboundDeliveryMode(name);
} catch {
return null;
}
}
/** Outcome of a `PUT /api/spawned/{name}/delivery-mode` call. */
export interface SetInboundDeliveryModeResult {
ok: boolean;
status: number;
/** Server-reported number of pending messages drained on a `manual_flush→auto_inject` flip. */
flushed?: number;
/** Human-readable error message when `ok` is false. */
message?: string;
}
export async function setInboundDeliveryMode(
connection: BrokerConnection,
name: string,
mode: InboundDeliveryMode,
fetchFn: typeof globalThis.fetch
): Promise<SetInboundDeliveryModeResult> {
try {
const body = await createBrokerClient(connection, fetchFn).setInboundDeliveryMode(name, mode);
const flushed = body.flushed;
return { ok: true, status: 200, flushed };
} catch (err: unknown) {
const failure = mapBrokerSdkFailure(err);
return { ok: false, status: failure.status, message: failure.message };
}
}
/** Seed for the `drive` pending counter: the current queue depth plus the
* set of `event_id`s already in the queue. The id set lets the WS handler
* dedupe replayed `delivery_queued` frames against deliveries already
* counted in `count` (see {@link runDriveSession}). */
export interface PendingSeed {
count: number;
eventIds: Set<string>;
}
/**
* `GET /api/spawned/{name}/pending` → `{ count, eventIds }`, or an empty seed
* on failure (best-effort). The `eventIds` set carries every pending
* delivery's `event_id` (deliveries without one are still counted but can't
* be deduped) so a replayed `delivery_queued` frame for an already-seeded
* delivery doesn't inflate the counter.
*/
export async function getPendingSeed(
connection: BrokerConnection,
name: string,
fetchFn: typeof globalThis.fetch
): Promise<PendingSeed> {
try {
const pending = await createBrokerClient(connection, fetchFn).getPending(name);
const eventIds = new Set<string>();
for (const message of pending) {
if (typeof message.event_id === 'string') eventIds.add(message.event_id);
}
return { count: pending.length, eventIds };
} catch {
return { count: 0, eventIds: new Set<string>() };
}
}
/**
* Current durable-event sequence cutoff, used as the event WS `sinceSeq` so
* the broker does not replay historical durable events (old `delivery_queued`
* frames) that would otherwise inflate the freshly-seeded pending counter.
* Returns `0` on failure (best-effort) — the caller then omits `sinceSeq`
* and behaves as before.
*/
export async function getCurrentEventSeq(
connection: BrokerConnection,
fetchFn: typeof globalThis.fetch
): Promise<number> {
try {
return await createBrokerClient(connection, fetchFn).currentEventSeq();
} catch {
return 0;
}
}
/** `POST /api/spawned/{name}/flush` → server returns `{ flushed: N }`. */
export async function flushPending(
connection: BrokerConnection,
name: string,
fetchFn: typeof globalThis.fetch
): Promise<{ ok: boolean; flushed?: number; message?: string }> {
try {
const body = await createBrokerClient(connection, fetchFn).flushPending(name);
return { ok: true, flushed: body.flushed };
} catch (err: unknown) {
const failure = mapBrokerSdkFailure(err);
return { ok: false, message: failure.message };
}
}
/** `POST /api/input/{name}` body `{ data: "<bytes>" }`. */
export async function sendInput(
connection: BrokerConnection,
name: string,
data: string,
fetchFn: typeof globalThis.fetch
): Promise<{ ok: boolean; message?: string }> {
try {
await createBrokerClient(connection, fetchFn).sendInput(name, data);
return { ok: true };
} catch (err: unknown) {
const failure = mapBrokerSdkFailure(err);
return { ok: false, message: failure.message };
}
}
/** Open the SDK-backed raw PTY input stream for interactive CLI sessions. */
export function openPtyInputStream(
connection: BrokerConnection,
name: string,
fetchFn: typeof globalThis.fetch,
options?: PtyInputStreamOptions
): CliPtyInputStream {
return createBrokerClient(connection, fetchFn).openInputStream(name, options);
}
/**
* `POST /api/resize/{name}` body `{ rows, cols }`. Forwards the
* driver's local terminal dimensions so the agent's PTY (and any TUI
* running in it) sees the size the human is actually looking at.
* Called once on attach and again on every local-terminal resize.
*/
export async function resizeWorker(
connection: BrokerConnection,
name: string,
rows: number,
cols: number,
fetchFn: typeof globalThis.fetch,
options?: { sessionId?: string }
): Promise<{ ok: boolean; message?: string; applied?: boolean }> {
try {
const result = await createBrokerClient(connection, fetchFn).resizePty(name, rows, cols, options);
return { ok: true, applied: result.applied !== false };
} catch (err: unknown) {
const failure = mapBrokerSdkFailure(err);
return { ok: false, message: failure.message };
}
}
/**
* Release this session's PTY resize ownership on detach (single-resizer
* policy, #1247), so the next client that attaches can resize the shared PTY.
* Best-effort: the broker also supersedes a crashed owner after an idle window.
*
* `restoreSize` gives back the row and column a writable attach reserved for
* Relay's status line (see `reserveStatusLineRow`). Without it the worker stays
* at `rows - 1`/`cols - 1` after the status line disappears, and since a
* read-only `view` session never resizes the PTY, the agent's TUI would remain
* one row and column short until the next writable attach. The broker applies
* the size before dropping ownership, so this stays one round-trip and cannot
* lose the ordering race a separate resize call would introduce.
*/
export async function releaseResizeOwnership(
connection: BrokerConnection,
name: string,
sessionId: string,
fetchFn: typeof globalThis.fetch,
restoreSize?: { rows: number; cols: number } | null
): Promise<void> {
try {
// Omitting the dimensions is a pure release — the broker skips the resize,
// so a session with no local TTY invents no placeholder size.
await createBrokerClient(connection, fetchFn).resizePty(name, restoreSize?.rows, restoreSize?.cols, {
sessionId,
release: true,
});
} catch {
// Best-effort — ownership falls back to the broker's idle-takeover net.
}
}
/** ----- WS message classification ----- */
function isStringObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
/** Discriminated union of the broker events `drive` cares about. */
export type DriveWsEvent =
| { kind: 'worker_stream'; chunk: string; offset?: number }
| { kind: 'delivery_queued'; eventId?: string }
| { kind: 'agent_pending_drained'; count?: number }
| { kind: 'other' };
/**
* Inspect a single WebSocket frame and classify it relative to the agent
* we're driving. Non-matching / malformed frames return `{ kind: 'other' }`
* so the caller can ignore them cheaply.
*
* Exported for unit testing the filter in isolation.
*/
export function classifyWsEvent(rawMessage: string, name: string): DriveWsEvent {
let parsed: unknown;
try {
parsed = JSON.parse(rawMessage);
} catch {
return { kind: 'other' };
}
if (!isStringObject(parsed)) return { kind: 'other' };
// All three events we care about are scoped by the worker `name` field.
if (parsed.name !== name) return { kind: 'other' };
if (parsed.kind === 'worker_stream') {
const chunk = parsed.chunk;
if (typeof chunk !== 'string') return { kind: 'other' };
const offset = typeof parsed.offset === 'number' ? parsed.offset : undefined;
return { kind: 'worker_stream', chunk, offset };
}
if (parsed.kind === 'delivery_queued') {
// Two different layers emit `delivery_queued`. Only the inbound hold means
// "parked in the per-worker pending queue" — the count this status line
// shows and the one `/api/spawned/{name}/pending` seeds. The harness
// runtimes emit the same kind for every delivery they enqueue for
// injection, which is ordinary traffic on its way to the agent; counting
// those would make `pending` climb on every message the agent receives and
// never come back down (nothing drains a queue the message was never in).
if (parsed.reason !== 'inbound_delivery_manual_flush') return { kind: 'other' };
// `event_id` correlates a replayed frame with the pending seed so the
// counter isn't double-incremented for a delivery already reflected in
// the seed (see the seed-dedup note in `runDriveSession`). Absent on
// legacy/mixed frames — treated as "not in the seed" (counted).
const eventId = typeof parsed.event_id === 'string' ? parsed.event_id : undefined;
return { kind: 'delivery_queued', eventId };
}
if (parsed.kind === 'agent_pending_drained') {
const count = typeof parsed.count === 'number' ? parsed.count : undefined;
return { kind: 'agent_pending_drained', count };
}
return { kind: 'other' };
}
/** ----- Keybind state machine ----- */
/** Outcome of feeding one chunk to the keybind parser. */
export interface KeybindOutcome {
/** Bytes that should be forwarded to the agent (may be empty). */
forward: Buffer;
/** Local actions the client should perform, in order. */
actions: KeybindAction[];
}
export type KeybindAction = 'detach' | 'toggle-delivery';
/**
* Parser for the two local control bytes drive keeps: `Ctrl+C` detaches and
* `Ctrl+]` toggles inbound delivery between hold and live injection.
*
* Semantics:
* - `Ctrl+C` (0x03) → emit `detach`, never forwarded.
* - `Ctrl+]` (0x1D) → emit `toggle-delivery`, never forwarded.
* - Every other byte, including Ctrl+B and Ctrl+G, is forwarded to the agent.
*
* Neither byte can appear inside a multi-byte UTF-8 sequence (continuation
* bytes are ≥ 0x80) or a keyboard escape sequence, so scanning raw bytes is
* safe.
*/
export class KeybindParser {
/** Process one chunk; returns bytes to forward + actions to take. */
feed(chunk: Buffer): KeybindOutcome {
const forward: number[] = [];
const actions: KeybindAction[] = [];
for (const byte of chunk) {
if (byte === 0x03 /* Ctrl+C */) {
actions.push('detach');
break;
}
if (byte === 0x1d /* Ctrl+] */) {
actions.push('toggle-delivery');
continue;
}
forward.push(byte);
}
return {
forward: Buffer.from(forward),
actions,
};
}
/** Reset the parser (e.g. before tearing down). */
reset(): void {}
}
/** ----- Status line rendering ----- */
/**
* Render the bottom-of-terminal status line for `drive`. Uses ANSI
* save-cursor / restore-cursor so the agent's output isn't disturbed.
*
* Exported for unit testing — `runDriveSession` calls it on every
* pending-count change.
*/
export function renderStatusLine(opts: {
name: string;
mode: InboundDeliveryMode;
pending: number;
/** Terminal rows — defaults to 24 if unknown. The status line lands on row N. */
rows?: number;
/** Terminal columns — the label is truncated to fit. Defaults to 80. */
cols?: number;
scrollTop?: number;
scrollBottom?: number;
originMode?: boolean;
}): string {
const row = Math.max(opts.rows ?? 24, 1);
const scrollTop = Math.max(1, opts.scrollTop ?? 1);
const scrollBottom = Math.max(scrollTop + 1, opts.scrollBottom ?? row - 1);
// The Ctrl+] hint names the action the NEXT press performs: in auto_inject
// (the session default) it holds; in manual_flush it delivers, draining the
// parked queue and going live again. Without the hint, a parked message is
// invisible beyond the pending counter and a held agent looks like it never
// receives replies.
const toggleHint = opts.mode === 'manual_flush' ? 'Ctrl+] deliver' : 'Ctrl+] hold';
const text = clampStatusLineText(
`[drive ${opts.name} | delivery=${opts.mode} | pending=${opts.pending} | ${toggleHint} | Ctrl+C detach]`,
opts.cols,
true
);
// ESC 7 = save cursor; ESC[<row>;1H = move to bottom row; ESC[2K = clear line;
// ESC[7m = reverse video; ESC[0m = reset; ESC 8 = restore cursor.
// Temporarily restore the full physical scroll region so CUP can reach the
// reserved row even if autowrap left the cursor below the child margin.
// Reinstall the child margin before restoring its cursor.
const restoreOrigin = opts.originMode ? '\x1b[?6h' : '';
return `\x1b7\x1b[?6l\x1b[r\x1b[${row};1H\x1b[2K\x1b[7m${text}\x1b[0m\x1b[${scrollTop};${scrollBottom}r${restoreOrigin}\x1b8`;
}
/** ----- Main session runner ----- */
/** Initial state handed off to the interactive session loop. */
interface DriveSessionState {
connection: BrokerConnection;
name: string;
previousMode: InboundDeliveryMode | null;
sessionRevision: string | null;
initialPending: number;
/**
* `event_id`s already reflected in `initialPending`. The event WS replays
* durable `delivery_queued` frames with `seq > cutoffSeq`; a frame whose id
* is in this set was already counted in the seed and must not re-increment
* the counter (see {@link runDriveSession} for why the cutoff is captured
* first and the seed second).
*/
seededEventIds: Set<string>;
/** Local terminal size at attach, for sizing the predictive-echo model. */
initialLocalSize: { rows: number; cols: number } | null;
/**
* Durable-event sequence cutoff at attach. Passed to the event WS as
* `sinceSeq` so the broker doesn't replay historical durable events
* (old `delivery_queued`) that would inflate the pending counter.
*/
cutoffSeq: number;
/**
* Tears down the early SIGINT/SIGTERM handlers registered by
* {@link runDriveSession} right after the delivery-mode flip. Called by the
* loop before it installs its own fuller handlers so Ctrl+C is never
* double-handled. Also disables the early restore path.
*/
disposeEarlySignals: () => void;
}
/**
* Run the interactive session. Subscribe-first: opens the event WS, buffers
* live `worker_stream` chunks, then (on subscribe) paints the snapshot,
* reconciles the buffer against the snapshot offset, forwards the initial
* resize, and takes over stdin. Restores the worker's previous mode on any
* exit path. Resolves with the exit code the CLI should propagate.
*/
function runDriveSessionLoop(state: DriveSessionState, deps: DriveDependencies): Promise<number> {
const { connection, name, previousMode, seededEventIds } = state;
// Connect with a `sinceSeq` cutoff so the broker replays only events after
// attach — historical durable events must not inflate the pending counter.
// Omit it when the cutoff is 0 (no durable events yet / lookup failed) so
// the URL and behaviour match the pre-cutoff default.
const wsUrl =
state.cutoffSeq > 0 ? `${toWsUrl(connection.url)}?sinceSeq=${state.cutoffSeq}` : toWsUrl(connection.url);
const headers: Record<string, string> = {};
if (connection.apiKey) {
headers['X-API-Key'] = connection.apiKey;
}
return new Promise<number>((resolve) => {
let settled = false;
let rawModeWasSet = false;
let unsubscribeResize: (() => void) | null = null;
// Stable per-attach id for the broker's single-resizer policy (#1247): all
// of this session's resizes carry it so we own the shared PTY size while
// driving, and we release it on detach.
const resizeSessionId = randomUUID();
// In-flight resize requests. Detach awaits these before releasing ownership
// so a late-resolving SIGWINCH resize can't re-claim the PTY *after* the
// release lands (single-resizer detach race, #1247).
const outstandingResizes = new Set<Promise<unknown>>();
const trackResize = (p: Promise<unknown>): void => {
outstandingResizes.add(p);
void p.finally(() => outstandingResizes.delete(p));
};
// Periodic ownership re-assert timer (see `ownershipReassertMs`).
let reassertTimer: ReturnType<typeof setInterval> | null = null;
let pending = state.initialPending;
// This session's last-known inbound delivery mode and its broker revision.
// The attach asserted `auto_inject`; `Ctrl+]` toggles it mid-session, and
// the detach restore compare-and-sets against whatever this session last
// wrote so an out-of-band change is never clobbered.
let currentMode: InboundDeliveryMode = 'auto_inject';
let currentRevision = state.sessionRevision;
let terminalRows = pickInitialTerminalRows(state.initialLocalSize, undefined);
let terminalCols = pickInitialTerminalCols(state.initialLocalSize, undefined);
const parser = new KeybindParser();
// Stateful UTF-8 decoder for forwarded stdin. Decoding each raw stdin chunk
// independently would turn a multi-byte character split across `data`
// events (routine in large pastes / IME) into U+FFFD; the StringDecoder
// buffers a trailing incomplete sequence until the next chunk completes it.
// Detach scanning still runs on raw bytes upstream (0x03 can't appear inside
// a multi-byte sequence), so this only touches the forwarded payload.
const inputDecoder = new StringDecoder('utf8');
let inputStream: CliPtyInputStream | null = null;
const cleanupSignals: Array<() => void> = [];
const isTtyOutput = state.initialLocalSize !== null;
// Skip the status line entirely when stdout is not a TTY (e.g. piped to
// `tee`) — a fabricated row-24 repaint would corrupt the captured log.
let statusLineEnabled = canReserveStatusLine(state.initialLocalSize);
// Subscribe-first: buffer live `worker_stream` chunks until the snapshot
// is painted and reconciled against its per-worker offset.
const sync = new StreamSyncBuffer();
// Adaptive predictive echo masks round-trip latency on remote brokers.
// Seeded with the snapshot (once painted) so its confirmed model matches
// the screen.
let initialAgentSize = reserveStatusLineRow(state.initialLocalSize);
const scrollRegion = new TerminalScrollRegionTracker(initialAgentSize?.rows ?? 1);
let observeRenderedOutput = (_chunk: string): void => {};
const predictiveEcho =
deps.createPredictiveEcho?.({
cols: initialAgentSize?.cols ?? 0,
rows: initialAgentSize?.rows ?? 0,
write: (chunk) => {
deps.writeChunk(chunk);
observeRenderedOutput(chunk);
},
getInputSrtt: () => inputStream?.srttMs ?? null,
}) ?? null;
// Tee the snapshot's painted bytes so we can seed the predictive-echo
// model with them — its cursor must match the real screen before we
// optimistically echo, or predicted glyphs land at the wrong position.
let snapshotBytes = '';
// Guard the snapshot paint on `settled`: a Ctrl+C during the snapshot HTTP
// fetch would otherwise paint the snapshot after teardown began (the render
// runs inside the awaited `captureAndRenderSnapshot`, past the WS guard).
const captureWrite = (chunk: string): void => {
if (settled) return;
deps.writeChunk(chunk);
snapshotBytes += chunk;
};
const correctSetupResize = async (baseline: { rows: number; cols: number } | null): Promise<void> => {
const latest = reserveStatusLineRow(deps.terminal.getSize());
if (!latest || (latest.rows === baseline?.rows && latest.cols === baseline?.cols)) return;
const correction = resizeWorker(connection, name, latest.rows, latest.cols, deps.fetch, {
sessionId: resizeSessionId,
});
trackResize(correction);
const result = await correction;
if (!result.ok) {
deps.log(`[drive] setup resize correction failed: ${result.message ?? 'unknown error'}`);
}
};
const beginSubscribedLayout = (): void => {
// Install this before the first resize/snapshot await so a local resize
// during setup cannot be lost.
unsubscribeResize ??= deps.terminal.onResize(resizeHandler);
const currentSize = deps.terminal.getSize();
terminalRows = pickInitialTerminalRows(currentSize, undefined);
terminalCols = currentSize?.cols;
statusLineEnabled = canReserveStatusLine(currentSize);
initialAgentSize = reserveStatusLineRow(currentSize);
if (initialAgentSize) {
scrollRegion.setRows(initialAgentSize.rows);
predictiveEcho?.onResize(initialAgentSize.cols, initialAgentSize.rows);
}
if (statusLineEnabled && initialAgentSize) {
deps.writeChunk(renderChildScrollRegion(initialAgentSize.rows));
}
};
// Boundary-held + coalesced status painter. Holds repaints while the agent
// is mid escape-sequence (no splicing into a half-sent CSI), rate-limits
// per-chunk repaints, and skips painting entirely on a non-TTY stdout.
const statusController = new StatusLineController({
render: () => {
const region = scrollRegion.region;
return renderStatusLine({
name,
mode: currentMode,
pending,
rows: terminalRows,
cols: terminalCols,
scrollTop: region.top,
scrollBottom: region.bottom,
originMode: scrollRegion.isOriginMode,
});
},
write: deps.writeChunk,
enabled: () => statusLineEnabled,
coalesceMs: deps.statusRepaintCoalesceMs ?? 40,
});
const paintStatus = (): void => {
statusController.request();
};
observeRenderedOutput = (chunk): void => {
scrollRegion.push(chunk);
statusController.observeOutput(chunk);
};
// Route server output through the predictive-echo engine (which owns
// cursor save/restore) or straight to stdout. Feed every chunk to the
// status controller for boundary tracking. Repaint after each completed
// chunk because terminal autowrap can briefly cross a DECSTBM bottom
// margin. The clipped label cannot autowrap itself, and the child PTY's
// reserved row prevents cursor-addressed TUI frames from fighting it.
const applyServerOutput = (chunk: string): void => {
if (predictiveEcho) {
void predictiveEcho.onServerOutput(chunk).then(
() => {
paintStatus();
},
() => {
paintStatus();
}
);
} else {
deps.writeChunk(chunk);
observeRenderedOutput(chunk);
paintStatus();
}
};
// Local-terminal resize handler. Forwards to the broker and
// repaints the status line at the new bottom-row index. Registered
// on `socket.on('open')` (same point we take over stdin) so a
// failed connection doesn't leave a dangling listener; unregistered
// in `teardownStdin` so detach is clean.
const resizeHandler = (): void => {
const size = deps.terminal.getSize();
if (!size) return;
terminalRows = size.rows;
terminalCols = size.cols;
statusLineEnabled = canReserveStatusLine(size);
const agentSize = reserveStatusLineRow(size);
if (!agentSize) return;
scrollRegion.setRows(agentSize.rows);
predictiveEcho?.onResize(agentSize.cols, agentSize.rows);
trackResize(
resizeWorker(connection, name, agentSize.rows, agentSize.cols, deps.fetch, {
sessionId: resizeSessionId,
}).then((res) => {
if (!res.ok) {
deps.log(`[drive] resize forward failed: ${res.message ?? 'unknown error'}`);
} else if (res.applied === false) {
deps.log('[drive] broker did not apply the reserved PTY size; using status repaint fallback');
}
})
);
// Repaint regardless of fetch outcome — the local terminal has
// already moved, so the status line position needs to move with
// it whether or not the broker accepted the resize.
paintStatus();
};
// In-band delivery toggle (`Ctrl+]`). Flips the worker between
// `auto_inject` (the session default — messages inject live while you
// watch) and `manual_flush` (messages park so nothing splices into what
// you are typing); flipping back drains the parked queue into the PTY.
//
// Guarded compare-and-set against this session's last-known revision: if
// another session or CLI changed the mode out-of-band, the broker no-ops
// and reports the current mode/revision, which we adopt (the next press
// toggles from the adopted state). Pending-counter updates come from the
// broker's `agent_pending_drained` event, not from this response, so the
// count is never double-subtracted.
// In-flight toggle request, if any. `finish()` awaits it before the
// detach restore so a quick Ctrl+] → Ctrl+C can't restore against a
// stale mode/revision while the toggle PUT is still changing broker
// state — the session's `currentMode`/`currentRevision` are updated even
// when teardown began mid-request, precisely so the restore CASes
// against what this session actually last wrote.
let deliveryToggleInFlight: Promise<void> | null = null;
const toggleDeliveryMode = (): Promise<void> => {
if (deliveryToggleInFlight) return deliveryToggleInFlight;
if (settled) return Promise.resolve();
const run = async (): Promise<void> => {
try {
const target: InboundDeliveryMode = currentMode === 'manual_flush' ? 'auto_inject' : 'manual_flush';
// Always guard on the session's last-known mode; add the revision
// when the broker reports one. A legacy broker without revisions
// still gets mode-level CAS instead of an unconditional write.
const result = await createBrokerClient(connection, deps.fetch).setInboundDeliveryMode(
name,
target,
{
expectedMode: currentMode,
...(currentRevision !== null ? { expectedRevision: currentRevision } : {}),
}
);
currentMode = result.mode;
if (result.revision !== null) {
currentRevision = result.revision;
}
if (settled) return;
if (!result.matched) {
deps.log(`[drive] delivery mode was changed by another session; now ${result.mode}`);
}
paintStatus();
} catch (err: unknown) {
if (settled) return;
const failure = mapBrokerSdkFailure(err);
deps.log(`[drive] could not toggle delivery mode: ${failure.message ?? 'unknown error'}`);
}
};
deliveryToggleInFlight = run().finally(() => {
deliveryToggleInFlight = null;
});
return deliveryToggleInFlight;
};
// ---- stdin handling ----
let stdinReady = false;
const stdinDataHandler = (chunk: Buffer): void => {
// Raw mode starts before snapshot replay so terminal input reports cannot
// echo. Until the predictive echo model is seeded, discard all input
// except Ctrl+C: forwarding stale mouse/focus reports (or echoing user
// input against an unseeded screen) would be worse than dropping it.
if (!stdinReady) {
if (chunk.includes(0x03)) finish(0);
return;
}
const outcome = parser.feed(chunk);
if (outcome.forward.length > 0) {
const stream = inputStream;
if (!stream) {
deps.log('[drive] input stream is not ready');
return;
}
// Decode through the stateful UTF-8 decoder so a multi-byte character
// split across stdin chunks is forwarded intact rather than as U+FFFD.
// An incomplete trailing sequence decodes to '' and is held until the
// next chunk completes it.
const decoded = inputDecoder.write(outcome.forward);
if (decoded.length > 0) {
// Fire-and-forget; surface errors via log but don't block the
// event loop on every keystroke.
void stream.send(decoded).catch((err: unknown) => {
if (settled) return;
const message = describeError(err);
deps.log(`[drive] input stream send failed: ${message}`);
// The keystroke never reached the PTY — drop any optimistic echo
// for it so the screen doesn't show input the agent didn't get.
predictiveEcho?.rollback();
});
}
predictiveEcho?.onUserInput(outcome.forward);
}
for (const action of outcome.actions) {
switch (action) {
case 'detach':
finish(0);
return;
case 'toggle-delivery':
void toggleDeliveryMode();
break;
}
}
};
const teardownStdin = (): void => {
try {
if (deps.stdin.off) {
deps.stdin.off('data', stdinDataHandler);
} else if (deps.stdin.removeListener) {
deps.stdin.removeListener('data', stdinDataHandler);
}
} catch {
// best effort
}
try {
if (rawModeWasSet && typeof deps.stdin.setRawMode === 'function') {
deps.stdin.setRawMode(false);
}
} catch {
// best effort
}
try {
// Heal the local terminal: the snapshot + live stream may have left it
// in app-cursor / mouse / bracketed-paste / alt-screen mode. Gate on a
// TTY stdout (same signal that gates the status line).
resetLocalTerminalOnDetach(deps.writeChunk, isTtyOutput);
} catch {
// best effort
}
try {
deps.stdin.pause();
} catch {
// best effort
}
try {
if (unsubscribeResize) {
unsubscribeResize();
unsubscribeResize = null;
}
} catch {
// best effort
}
try {
if (reassertTimer) {
clearInterval(reassertTimer);
reassertTimer = null;
}
} catch {
// best effort
}
rawModeWasSet = false;
};
const closeInputStream = (): void => {