agent-relay 17.2.1 → 18.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +74 -266
- package/dist/cli/agent-relay-mcp.d.ts.map +1 -1
- package/dist/cli/agent-relay-mcp.js +6 -5
- package/dist/cli/agent-relay-mcp.js.map +1 -1
- package/dist/cli/bootstrap.d.ts +1 -1
- package/dist/cli/bootstrap.d.ts.map +1 -1
- package/dist/cli/bootstrap.js +11 -29
- package/dist/cli/bootstrap.js.map +1 -1
- package/dist/cli/commands/agent.d.ts.map +1 -1
- package/dist/cli/commands/agent.js +3 -2
- package/dist/cli/commands/agent.js.map +1 -1
- package/dist/cli/commands/cloud-integration.d.ts.map +1 -1
- package/dist/cli/commands/cloud-integration.js +2 -1
- package/dist/cli/commands/cloud-integration.js.map +1 -1
- package/dist/cli/commands/cloud-room.d.ts.map +1 -1
- package/dist/cli/commands/cloud-room.js +2 -1
- package/dist/cli/commands/cloud-room.js.map +1 -1
- package/dist/cli/commands/cloud-v1-deprecations.d.ts +4 -6
- package/dist/cli/commands/cloud-v1-deprecations.d.ts.map +1 -1
- package/dist/cli/commands/cloud-v1-deprecations.js +4 -6
- package/dist/cli/commands/cloud-v1-deprecations.js.map +1 -1
- package/dist/cli/commands/cloud-worker.d.ts +6 -2
- package/dist/cli/commands/cloud-worker.d.ts.map +1 -1
- package/dist/cli/commands/cloud-worker.js +74 -37
- package/dist/cli/commands/cloud-worker.js.map +1 -1
- package/dist/cli/commands/cloud.d.ts.map +1 -1
- package/dist/cli/commands/cloud.js +20 -18
- package/dist/cli/commands/cloud.js.map +1 -1
- package/dist/cli/commands/core.d.ts +3 -91
- package/dist/cli/commands/core.d.ts.map +1 -1
- package/dist/cli/commands/core.js +5 -254
- package/dist/cli/commands/core.js.map +1 -1
- package/dist/cli/commands/fleet-agent.d.ts +9 -54
- package/dist/cli/commands/fleet-agent.d.ts.map +1 -1
- package/dist/cli/commands/fleet-agent.js +105 -314
- package/dist/cli/commands/fleet-agent.js.map +1 -1
- package/dist/cli/commands/fleet.d.ts +0 -3
- package/dist/cli/commands/fleet.d.ts.map +1 -1
- package/dist/cli/commands/fleet.js +48 -267
- package/dist/cli/commands/fleet.js.map +1 -1
- package/dist/cli/commands/init.js +1 -1
- package/dist/cli/commands/init.js.map +1 -1
- package/dist/cli/commands/integration-cleanup-journal.d.ts +6 -2
- package/dist/cli/commands/integration-cleanup-journal.d.ts.map +1 -1
- package/dist/cli/commands/integration-cleanup-journal.js +611 -134
- package/dist/cli/commands/integration-cleanup-journal.js.map +1 -1
- package/dist/cli/commands/integration-recipient.d.ts +0 -17
- package/dist/cli/commands/integration-recipient.d.ts.map +1 -1
- package/dist/cli/commands/integration-recipient.js +1 -104
- package/dist/cli/commands/integration-recipient.js.map +1 -1
- package/dist/cli/commands/integration.d.ts +7 -3
- package/dist/cli/commands/integration.d.ts.map +1 -1
- package/dist/cli/commands/integration.js +37 -82
- package/dist/cli/commands/integration.js.map +1 -1
- package/dist/cli/commands/local-workflow.d.ts +1 -1
- package/dist/cli/commands/local-workflow.d.ts.map +1 -1
- package/dist/cli/commands/local-workflow.js +20 -6
- package/dist/cli/commands/local-workflow.js.map +1 -1
- package/dist/cli/commands/node.d.ts +18 -20
- package/dist/cli/commands/node.d.ts.map +1 -1
- package/dist/cli/commands/node.js +42 -272
- package/dist/cli/commands/node.js.map +1 -1
- package/dist/cli/commands/product-surfaces.js +2 -2
- package/dist/cli/commands/session.d.ts.map +1 -1
- package/dist/cli/commands/session.js +2 -1
- package/dist/cli/commands/session.js.map +1 -1
- package/dist/cli/commands/skills.d.ts.map +1 -1
- package/dist/cli/commands/skills.js +2 -1
- package/dist/cli/commands/skills.js.map +1 -1
- package/dist/cli/commands/status.d.ts +1 -7
- package/dist/cli/commands/status.d.ts.map +1 -1
- package/dist/cli/commands/status.js +2 -28
- package/dist/cli/commands/status.js.map +1 -1
- package/dist/cli/commands/workspace.d.ts.map +1 -1
- package/dist/cli/commands/workspace.js +2 -2
- package/dist/cli/commands/workspace.js.map +1 -1
- package/dist/cli/index.d.ts.map +1 -1
- package/dist/cli/index.js +1 -3
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/lib/agent-relay-cli-reentry.d.ts +40 -0
- package/dist/cli/lib/agent-relay-cli-reentry.d.ts.map +1 -0
- package/dist/cli/lib/agent-relay-cli-reentry.js +47 -0
- package/dist/cli/lib/agent-relay-cli-reentry.js.map +1 -0
- package/dist/cli/lib/agent-tools-mcp.d.ts.map +1 -1
- package/dist/cli/lib/agent-tools-mcp.js +3 -2
- package/dist/cli/lib/agent-tools-mcp.js.map +1 -1
- package/dist/cli/lib/cloud-worker-authored-runtime.d.ts +3 -0
- package/dist/cli/lib/cloud-worker-authored-runtime.d.ts.map +1 -0
- package/dist/cli/lib/cloud-worker-authored-runtime.js +67 -0
- package/dist/cli/lib/cloud-worker-authored-runtime.js.map +1 -0
- package/dist/cli/lib/cloud-worker-enrollment-token.d.ts +13 -0
- package/dist/cli/lib/cloud-worker-enrollment-token.d.ts.map +1 -0
- package/dist/cli/lib/cloud-worker-enrollment-token.js +88 -0
- package/dist/cli/lib/cloud-worker-enrollment-token.js.map +1 -0
- package/dist/cli/lib/core-maintenance.d.ts +2 -3
- package/dist/cli/lib/core-maintenance.d.ts.map +1 -1
- package/dist/cli/lib/core-maintenance.js +3 -37
- package/dist/cli/lib/core-maintenance.js.map +1 -1
- package/dist/cli/lib/desktop-presence.js +1 -1
- package/dist/cli/lib/desktop-presence.js.map +1 -1
- package/dist/cli/lib/install-paths.d.ts +100 -0
- package/dist/cli/lib/install-paths.d.ts.map +1 -0
- package/dist/cli/lib/install-paths.js +157 -0
- package/dist/cli/lib/install-paths.js.map +1 -0
- package/dist/cli/lib/product-surface-store.d.ts.map +1 -1
- package/dist/cli/lib/product-surface-store.js +4 -1
- package/dist/cli/lib/product-surface-store.js.map +1 -1
- package/dist/cli/lib/relay-node.d.ts +7 -34
- package/dist/cli/lib/relay-node.d.ts.map +1 -1
- package/dist/cli/lib/relay-node.js +7 -182
- package/dist/cli/lib/relay-node.js.map +1 -1
- package/dist/cli/lib/removed-broker-command.d.ts +7 -0
- package/dist/cli/lib/removed-broker-command.d.ts.map +1 -0
- package/dist/cli/lib/removed-broker-command.js +13 -0
- package/dist/cli/lib/removed-broker-command.js.map +1 -0
- package/dist/cli/lib/sdk-client.d.ts +4 -4
- package/dist/cli/lib/sdk-client.js +4 -4
- package/dist/cli/lib/self-update.d.ts +8 -19
- package/dist/cli/lib/self-update.d.ts.map +1 -1
- package/dist/cli/lib/self-update.js +14 -28
- package/dist/cli/lib/self-update.js.map +1 -1
- package/dist/cli/lib/skills-install.d.ts.map +1 -1
- package/dist/cli/lib/skills-install.js +3 -2
- package/dist/cli/lib/skills-install.js.map +1 -1
- package/dist/cli/telemetry/events.d.ts +4 -1
- package/dist/cli/telemetry/events.d.ts.map +1 -1
- package/package.json +9 -14
- package/dist/auto/classifier.d.ts +0 -29
- package/dist/auto/classifier.d.ts.map +0 -1
- package/dist/auto/classifier.js +0 -126
- package/dist/auto/classifier.js.map +0 -1
- package/dist/auto/composer.d.ts +0 -105
- package/dist/auto/composer.d.ts.map +0 -1
- package/dist/auto/composer.js +0 -454
- package/dist/auto/composer.js.map +0 -1
- package/dist/auto/director-prompt.d.ts +0 -25
- package/dist/auto/director-prompt.d.ts.map +0 -1
- package/dist/auto/director-prompt.js +0 -53
- package/dist/auto/director-prompt.js.map +0 -1
- package/dist/auto/index.d.ts +0 -15
- package/dist/auto/index.d.ts.map +0 -1
- package/dist/auto/index.js +0 -13
- package/dist/auto/index.js.map +0 -1
- package/dist/cli/commands/local-agent.d.ts +0 -74
- package/dist/cli/commands/local-agent.d.ts.map +0 -1
- package/dist/cli/commands/local-agent.js +0 -969
- package/dist/cli/commands/local-agent.js.map +0 -1
- package/dist/cli/lib/attach-broker.d.ts +0 -17
- package/dist/cli/lib/attach-broker.d.ts.map +0 -1
- package/dist/cli/lib/attach-broker.js +0 -27
- package/dist/cli/lib/attach-broker.js.map +0 -1
- package/dist/cli/lib/attach-drive.d.ts +0 -376
- package/dist/cli/lib/attach-drive.d.ts.map +0 -1
- package/dist/cli/lib/attach-drive.js +0 -1212
- package/dist/cli/lib/attach-drive.js.map +0 -1
- package/dist/cli/lib/attach-fleet-node.d.ts +0 -85
- package/dist/cli/lib/attach-fleet-node.d.ts.map +0 -1
- package/dist/cli/lib/attach-fleet-node.js +0 -1347
- package/dist/cli/lib/attach-fleet-node.js.map +0 -1
- package/dist/cli/lib/attach-input-recovery.d.ts +0 -190
- package/dist/cli/lib/attach-input-recovery.d.ts.map +0 -1
- package/dist/cli/lib/attach-input-recovery.js +0 -559
- package/dist/cli/lib/attach-input-recovery.js.map +0 -1
- package/dist/cli/lib/attach-mode.d.ts +0 -2
- package/dist/cli/lib/attach-mode.d.ts.map +0 -1
- package/dist/cli/lib/attach-mode.js +0 -2
- package/dist/cli/lib/attach-mode.js.map +0 -1
- package/dist/cli/lib/attach-native.d.ts +0 -27
- package/dist/cli/lib/attach-native.d.ts.map +0 -1
- package/dist/cli/lib/attach-native.js +0 -267
- package/dist/cli/lib/attach-native.js.map +0 -1
- package/dist/cli/lib/attach-passthrough.d.ts +0 -193
- package/dist/cli/lib/attach-passthrough.d.ts.map +0 -1
- package/dist/cli/lib/attach-passthrough.js +0 -778
- package/dist/cli/lib/attach-passthrough.js.map +0 -1
- package/dist/cli/lib/attach-remote-node.d.ts +0 -21
- package/dist/cli/lib/attach-remote-node.d.ts.map +0 -1
- package/dist/cli/lib/attach-remote-node.js +0 -133
- package/dist/cli/lib/attach-remote-node.js.map +0 -1
- package/dist/cli/lib/attach-view.d.ts +0 -177
- package/dist/cli/lib/attach-view.d.ts.map +0 -1
- package/dist/cli/lib/attach-view.js +0 -455
- package/dist/cli/lib/attach-view.js.map +0 -1
- package/dist/cli/lib/attach.d.ts +0 -555
- package/dist/cli/lib/attach.d.ts.map +0 -1
- package/dist/cli/lib/attach.js +0 -1180
- package/dist/cli/lib/attach.js.map +0 -1
- package/dist/cli/lib/broker-connection.d.ts +0 -65
- package/dist/cli/lib/broker-connection.d.ts.map +0 -1
- package/dist/cli/lib/broker-connection.js +0 -144
- package/dist/cli/lib/broker-connection.js.map +0 -1
- package/dist/cli/lib/broker-lifecycle.d.ts +0 -220
- package/dist/cli/lib/broker-lifecycle.d.ts.map +0 -1
- package/dist/cli/lib/broker-lifecycle.js +0 -2290
- package/dist/cli/lib/broker-lifecycle.js.map +0 -1
- package/dist/cli/lib/broker-process-identity.d.ts +0 -38
- package/dist/cli/lib/broker-process-identity.d.ts.map +0 -1
- package/dist/cli/lib/broker-process-identity.js +0 -304
- package/dist/cli/lib/broker-process-identity.js.map +0 -1
- package/dist/cli/lib/client-factory.d.ts +0 -44
- package/dist/cli/lib/client-factory.d.ts.map +0 -1
- package/dist/cli/lib/client-factory.js +0 -64
- package/dist/cli/lib/client-factory.js.map +0 -1
- package/dist/cli/lib/collect-with-retry.d.ts +0 -24
- package/dist/cli/lib/collect-with-retry.d.ts.map +0 -1
- package/dist/cli/lib/collect-with-retry.js +0 -33
- package/dist/cli/lib/collect-with-retry.js.map +0 -1
- package/dist/cli/lib/fleet-attach-target.d.ts +0 -18
- package/dist/cli/lib/fleet-attach-target.d.ts.map +0 -1
- package/dist/cli/lib/fleet-attach-target.js +0 -57
- package/dist/cli/lib/fleet-attach-target.js.map +0 -1
- package/dist/cli/lib/fleet-hint.d.ts +0 -49
- package/dist/cli/lib/fleet-hint.d.ts.map +0 -1
- package/dist/cli/lib/fleet-hint.js +0 -113
- package/dist/cli/lib/fleet-hint.js.map +0 -1
- package/dist/cli/lib/fleet-sidecar.d.ts +0 -43
- package/dist/cli/lib/fleet-sidecar.d.ts.map +0 -1
- package/dist/cli/lib/fleet-sidecar.js +0 -84
- package/dist/cli/lib/fleet-sidecar.js.map +0 -1
- package/dist/cli/lib/join-ticket.d.ts +0 -22
- package/dist/cli/lib/join-ticket.d.ts.map +0 -1
- package/dist/cli/lib/join-ticket.js +0 -96
- package/dist/cli/lib/join-ticket.js.map +0 -1
- package/dist/cli/lib/node-claim.d.ts +0 -468
- package/dist/cli/lib/node-claim.d.ts.map +0 -1
- package/dist/cli/lib/node-claim.js +0 -1349
- package/dist/cli/lib/node-claim.js.map +0 -1
- package/dist/cli/lib/node-definition-loader.d.ts +0 -19
- package/dist/cli/lib/node-definition-loader.d.ts.map +0 -1
- package/dist/cli/lib/node-definition-loader.js +0 -143
- package/dist/cli/lib/node-definition-loader.js.map +0 -1
- package/dist/cli/lib/node-provider-child.d.ts +0 -129
- package/dist/cli/lib/node-provider-child.d.ts.map +0 -1
- package/dist/cli/lib/node-provider-child.js +0 -755
- package/dist/cli/lib/node-provider-child.js.map +0 -1
- package/dist/cli/lib/predictive-echo-screen.d.ts +0 -48
- package/dist/cli/lib/predictive-echo-screen.d.ts.map +0 -1
- package/dist/cli/lib/predictive-echo-screen.js +0 -74
- package/dist/cli/lib/predictive-echo-screen.js.map +0 -1
- package/dist/cli/lib/project-broker-client.d.ts +0 -4
- package/dist/cli/lib/project-broker-client.d.ts.map +0 -1
- package/dist/cli/lib/project-broker-client.js +0 -12
- package/dist/cli/lib/project-broker-client.js.map +0 -1
- package/dist/cli/lib/reflex-capture.d.ts +0 -41
- package/dist/cli/lib/reflex-capture.d.ts.map +0 -1
- package/dist/cli/lib/reflex-capture.js +0 -128
- package/dist/cli/lib/reflex-capture.js.map +0 -1
- package/dist/cli/lib/workspace-env.d.ts +0 -8
- package/dist/cli/lib/workspace-env.d.ts.map +0 -1
- package/dist/cli/lib/workspace-env.js +0 -16
- package/dist/cli/lib/workspace-env.js.map +0 -1
|
@@ -1,1212 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `agent-relay drive <name>` — interactive read-write take-over client.
|
|
3
|
-
*
|
|
4
|
-
* Attaches to a running agent, puts it in `auto_inject` inbound delivery mode so
|
|
5
|
-
* relay messages keep reaching it live, and forwards your keystrokes to the
|
|
6
|
-
* worker's PTY. Watching an agent never pauses it: a driven agent goes on
|
|
7
|
-
* receiving its peers' messages exactly as it would unattended, which is what
|
|
8
|
-
* makes it possible to observe a team coordinating instead of freezing it by
|
|
9
|
-
* looking at it.
|
|
10
|
-
*
|
|
11
|
-
* `Ctrl+]` toggles the worker into `manual_flush` when you want the screen to
|
|
12
|
-
* hold still while you type — messages park in a per-worker queue, the status
|
|
13
|
-
* line counts them (`pending=N`), and the next press drains the queue and
|
|
14
|
-
* returns to live delivery. The out-of-band commands `local agent message
|
|
15
|
-
* flush`, `local agent message hold`, and `local agent message auto` still work
|
|
16
|
-
* from another terminal: a bare `flush` during a drive session injects the
|
|
17
|
-
* queued backlog immediately (the broker follows the handoff with a one-shot
|
|
18
|
-
* `flush_injections` frame that exempts it from the interactive hold) while
|
|
19
|
-
* leaving the mode — and the parking of later messages — unchanged. `Ctrl+C`
|
|
20
|
-
* detaches, restores the worker's previous inbound delivery mode, and leaves
|
|
21
|
-
* the agent running under the broker — `drive` never kills the worker.
|
|
22
|
-
*
|
|
23
|
-
* Sequence of operations on attach (subscribe-first, so no output around
|
|
24
|
-
* attach time is lost and none is double-painted):
|
|
25
|
-
*
|
|
26
|
-
* 1. Discover broker connection (CLI flag → env → connection.json).
|
|
27
|
-
* 2. `GET /api/spawned/{name}/delivery-mode` → remember the previous mode.
|
|
28
|
-
* 3. `PUT /api/spawned/{name}/delivery-mode` → assert `auto_inject`.
|
|
29
|
-
* 4. `GET /api/events/replay` → capture the durable-event `sinceSeq` cutoff,
|
|
30
|
-
* then `GET /api/spawned/{name}/pending` → seed the status-line counter
|
|
31
|
-
* and the set of already-queued `event_id`s. Cutoff-first + id-dedupe
|
|
32
|
-
* keeps the counter exact across the attach race (no under/over-count).
|
|
33
|
-
* 5. Open `/ws?sinceSeq=<cutoff>`, subscribe, and buffer live output. The
|
|
34
|
-
* cutoff stops the broker replaying historical durable events that would
|
|
35
|
-
* inflate the pending counter; any replayed `delivery_queued` already in
|
|
36
|
-
* the seed is deduped by `event_id`.
|
|
37
|
-
* 6. On subscribe: `captureAndRenderSnapshot` repaints the agent's current
|
|
38
|
-
* screen; buffered chunks are reconciled against the snapshot's stream
|
|
39
|
-
* offset (drop what the snapshot already shows, apply the rest).
|
|
40
|
-
* 7. Forward the initial terminal size (resize now lands in the live stream,
|
|
41
|
-
* not a dead zone), then open the SDK PTY input stream and switch local
|
|
42
|
-
* stdin to raw mode.
|
|
43
|
-
*
|
|
44
|
-
* On detach (clean or abnormal), best-effort `PUT .../delivery-mode` restores the
|
|
45
|
-
* previous mode so the queue doesn't fill up indefinitely.
|
|
46
|
-
*/
|
|
47
|
-
import { Buffer } from 'node:buffer';
|
|
48
|
-
import { randomUUID } from 'node:crypto';
|
|
49
|
-
import { StringDecoder } from 'node:string_decoder';
|
|
50
|
-
import WebSocket from 'ws';
|
|
51
|
-
import { createInputStreamRecovery, INPUT_REOPEN_BASE_DELAY_MS, INPUT_REOPEN_MAX_ATTEMPTS, } from './attach-input-recovery.js';
|
|
52
|
-
import { captureAndRenderSnapshot, canReserveStatusLine, clampStatusLineText, createBackpressureAwareWriter, DETACH_CLEANUP_DEADLINE_MS, pickInitialTerminalCols, pickInitialTerminalRows, prepareAttachTarget, reserveStatusLineRow, renderChildScrollRegion, resetLocalTerminalOnDetach, restoreInboundDeliveryModeOnDetach, StatusLineController, StreamSyncBuffer, switchInboundDeliveryModeOrAbort, syncInitialPtySize, TerminalScrollRegionTracker, } from '../lib/attach.js';
|
|
53
|
-
import { defaultStateDir, readConnectionFileFromDisk, toWsUrl, } from '../lib/broker-connection.js';
|
|
54
|
-
import { defaultExit, runSignalHandler } from '../lib/exit.js';
|
|
55
|
-
import { resolveFleetHint } from '../lib/fleet-hint.js';
|
|
56
|
-
import { createBrokerClient, mapBrokerSdkFailure, } from '../lib/attach-broker.js';
|
|
57
|
-
import { describeError } from './describe-error.js';
|
|
58
|
-
import { createPredictiveEcho } from './predictive-echo-screen.js';
|
|
59
|
-
function withDefaults(overrides = {}) {
|
|
60
|
-
const fetchFn = overrides.fetch ?? ((input, init) => fetch(input, init));
|
|
61
|
-
const writer = createBackpressureAwareWriter(process.stdout);
|
|
62
|
-
return {
|
|
63
|
-
readConnectionFile: readConnectionFileFromDisk,
|
|
64
|
-
getDefaultStateDir: defaultStateDir,
|
|
65
|
-
env: process.env,
|
|
66
|
-
createWebSocket: (url, headers) => new WebSocket(url, { headers }),
|
|
67
|
-
writeChunk: writer.write,
|
|
68
|
-
disposeWriter: writer.dispose,
|
|
69
|
-
statusRepaintCoalesceMs: 40,
|
|
70
|
-
onSignal: (signal, handler) => {
|
|
71
|
-
const listener = () => runSignalHandler(handler);
|
|
72
|
-
process.on(signal, listener);
|
|
73
|
-
return () => process.off(signal, listener);
|
|
74
|
-
},
|
|
75
|
-
log: (...args) => console.error(...args),
|
|
76
|
-
error: (...args) => console.error(...args),
|
|
77
|
-
exit: defaultExit,
|
|
78
|
-
fetch: fetchFn,
|
|
79
|
-
captureAndRenderSnapshot,
|
|
80
|
-
fleetHint: resolveFleetHint,
|
|
81
|
-
stdin: process.stdin,
|
|
82
|
-
terminal: {
|
|
83
|
-
getSize: () => {
|
|
84
|
-
// process.stdout.isTTY is `true | undefined`; reading
|
|
85
|
-
// rows/columns on a non-TTY returns `undefined`.
|
|
86
|
-
const stdout = process.stdout;
|
|
87
|
-
if (!stdout.isTTY)
|
|
88
|
-
return null;
|
|
89
|
-
const rows = stdout.rows;
|
|
90
|
-
const cols = stdout.columns;
|
|
91
|
-
if (typeof rows !== 'number' || typeof cols !== 'number')
|
|
92
|
-
return null;
|
|
93
|
-
return { rows, cols };
|
|
94
|
-
},
|
|
95
|
-
onResize: (handler) => {
|
|
96
|
-
// Node automatically translates SIGWINCH into a `'resize'`
|
|
97
|
-
// event on `process.stdout` when stdout is a TTY.
|
|
98
|
-
process.stdout.on('resize', handler);
|
|
99
|
-
return () => process.stdout.off('resize', handler);
|
|
100
|
-
},
|
|
101
|
-
},
|
|
102
|
-
openInputStream: (connection, name, options) => openPtyInputStream(connection, name, fetchFn, options),
|
|
103
|
-
getWorkerIdentity: (connection, name) => fetchWorkerIdentity(connection, name, fetchFn),
|
|
104
|
-
createPredictiveEcho,
|
|
105
|
-
...overrides,
|
|
106
|
-
};
|
|
107
|
-
}
|
|
108
|
-
/** ----- HTTP helpers ----- */
|
|
109
|
-
/** `GET /api/spawned/{name}/delivery-mode` → `'manual_flush' | 'auto_inject'` or `null` on failure. */
|
|
110
|
-
export async function getInboundDeliveryMode(connection, name, fetchFn) {
|
|
111
|
-
try {
|
|
112
|
-
return await createBrokerClient(connection, fetchFn).getInboundDeliveryMode(name);
|
|
113
|
-
}
|
|
114
|
-
catch {
|
|
115
|
-
return null;
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
export async function setInboundDeliveryMode(connection, name, mode, fetchFn) {
|
|
119
|
-
try {
|
|
120
|
-
const body = await createBrokerClient(connection, fetchFn).setInboundDeliveryMode(name, mode);
|
|
121
|
-
const flushed = body.flushed;
|
|
122
|
-
return { ok: true, status: 200, flushed };
|
|
123
|
-
}
|
|
124
|
-
catch (err) {
|
|
125
|
-
const failure = mapBrokerSdkFailure(err);
|
|
126
|
-
return { ok: false, status: failure.status, message: failure.message };
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
/**
|
|
130
|
-
* `GET /api/spawned/{name}/pending` → `{ count, eventIds }`, or an empty seed
|
|
131
|
-
* on failure (best-effort). The `eventIds` set carries every pending
|
|
132
|
-
* delivery's `event_id` (deliveries without one are still counted but can't
|
|
133
|
-
* be deduped) so a replayed `delivery_queued` frame for an already-seeded
|
|
134
|
-
* delivery doesn't inflate the counter.
|
|
135
|
-
*/
|
|
136
|
-
export async function getPendingSeed(connection, name, fetchFn) {
|
|
137
|
-
try {
|
|
138
|
-
const pending = await createBrokerClient(connection, fetchFn).getPending(name);
|
|
139
|
-
const eventIds = new Set();
|
|
140
|
-
for (const message of pending) {
|
|
141
|
-
if (typeof message.event_id === 'string')
|
|
142
|
-
eventIds.add(message.event_id);
|
|
143
|
-
}
|
|
144
|
-
return { count: pending.length, eventIds };
|
|
145
|
-
}
|
|
146
|
-
catch {
|
|
147
|
-
return { count: 0, eventIds: new Set() };
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
/**
|
|
151
|
-
* Current durable-event sequence cutoff, used as the event WS `sinceSeq` so
|
|
152
|
-
* the broker does not replay historical durable events (old `delivery_queued`
|
|
153
|
-
* frames) that would otherwise inflate the freshly-seeded pending counter.
|
|
154
|
-
* Returns `0` on failure (best-effort) — the caller then omits `sinceSeq`
|
|
155
|
-
* and behaves as before.
|
|
156
|
-
*/
|
|
157
|
-
export async function getCurrentEventSeq(connection, fetchFn) {
|
|
158
|
-
try {
|
|
159
|
-
return await createBrokerClient(connection, fetchFn).currentEventSeq();
|
|
160
|
-
}
|
|
161
|
-
catch {
|
|
162
|
-
return 0;
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
/** `POST /api/spawned/{name}/flush` → server returns `{ flushed: N }`. */
|
|
166
|
-
export async function flushPending(connection, name, fetchFn) {
|
|
167
|
-
try {
|
|
168
|
-
const body = await createBrokerClient(connection, fetchFn).flushPending(name);
|
|
169
|
-
return { ok: true, flushed: body.flushed };
|
|
170
|
-
}
|
|
171
|
-
catch (err) {
|
|
172
|
-
const failure = mapBrokerSdkFailure(err);
|
|
173
|
-
return { ok: false, message: failure.message };
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
/** `POST /api/input/{name}` body `{ data: "<bytes>" }`. */
|
|
177
|
-
export async function sendInput(connection, name, data, fetchFn) {
|
|
178
|
-
try {
|
|
179
|
-
await createBrokerClient(connection, fetchFn).sendInput(name, data);
|
|
180
|
-
return { ok: true };
|
|
181
|
-
}
|
|
182
|
-
catch (err) {
|
|
183
|
-
const failure = mapBrokerSdkFailure(err);
|
|
184
|
-
return { ok: false, message: failure.message };
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
/**
|
|
188
|
-
* Best-available identity for the worker process behind `name`, or `null` when
|
|
189
|
-
* it cannot be established.
|
|
190
|
-
*
|
|
191
|
-
* The broker exposes no per-instance token for a worker — no `instance_id`,
|
|
192
|
-
* `run_id`, `epoch`, or absolute spawn timestamp reaches the wire (#1454). The
|
|
193
|
-
* only restart-discriminating values on `GET /api/spawned` are two pids, and
|
|
194
|
-
* they are not interchangeable:
|
|
195
|
-
*
|
|
196
|
-
* - `workerPid` (`crates/broker/src/worker.rs:243` = `handle.child.id()`) is the
|
|
197
|
-
* PTY child itself — the process whose terminal we are driving. Present as
|
|
198
|
-
* soon as the worker is spawned.
|
|
199
|
-
* - `pid` (`worker.rs:242` = `handle.harness_pid`) is the *harness* wrapper, and
|
|
200
|
-
* stays null until the worker completes the harness ready handshake
|
|
201
|
-
* (`worker_events.rs:849`). Verified against a live broker: a plain PTY worker
|
|
202
|
-
* reports `pid: null` and `workerPid: 30209`, so keying on `pid` alone would
|
|
203
|
-
* make every reopen unverifiable for exactly the workers this path serves.
|
|
204
|
-
*
|
|
205
|
-
* So prefer `workerPid` and fold in `pid` when the broker also has it — a change
|
|
206
|
-
* in either means the process behind the name changed.
|
|
207
|
-
*
|
|
208
|
-
* This is a heuristic, not a nonce: the OS can reuse a pid. It is used to
|
|
209
|
-
* *reject* a reopen that lands on a visibly different process, never to prove
|
|
210
|
-
* two processes are the same — callers treat `null` as "cannot verify" and
|
|
211
|
-
* fail closed. The durable fix is for the broker to surface the per-spawn
|
|
212
|
-
* identity it already holds in memory (`WorkerHandle.spawned_at`,
|
|
213
|
-
* `PersistedAgent.started_at`, or the `MetricsCollector` spawn counter) — #1454.
|
|
214
|
-
*/
|
|
215
|
-
export async function fetchWorkerIdentity(connection, name, fetchFn) {
|
|
216
|
-
try {
|
|
217
|
-
const agents = await createBrokerClient(connection, fetchFn).listAgents();
|
|
218
|
-
const agent = agents.find((candidate) => candidate.name === name);
|
|
219
|
-
if (!agent)
|
|
220
|
-
return null;
|
|
221
|
-
// `workerPid` is on the wire but absent from the typed contract, so read it
|
|
222
|
-
// off the record defensively rather than widening `ListAgent` here.
|
|
223
|
-
const workerPid = agent.workerPid;
|
|
224
|
-
const parts = [];
|
|
225
|
-
if (typeof workerPid === 'number')
|
|
226
|
-
parts.push(`worker:${workerPid}`);
|
|
227
|
-
if (typeof agent.pid === 'number')
|
|
228
|
-
parts.push(`harness:${agent.pid}`);
|
|
229
|
-
// No pid of either kind means the broker cannot tell us who this is.
|
|
230
|
-
return parts.length > 0 ? parts.join('/') : null;
|
|
231
|
-
}
|
|
232
|
-
catch {
|
|
233
|
-
return null;
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
/** Open the SDK-backed raw PTY input stream for interactive CLI sessions. */
|
|
237
|
-
export function openPtyInputStream(connection, name, fetchFn, options) {
|
|
238
|
-
return createBrokerClient(connection, fetchFn).openInputStream(name, options);
|
|
239
|
-
}
|
|
240
|
-
/**
|
|
241
|
-
* `POST /api/resize/{name}` body `{ rows, cols }`. Forwards the
|
|
242
|
-
* driver's local terminal dimensions so the agent's PTY (and any TUI
|
|
243
|
-
* running in it) sees the size the human is actually looking at.
|
|
244
|
-
* Called once on attach and again on every local-terminal resize.
|
|
245
|
-
*/
|
|
246
|
-
export async function resizeWorker(connection, name, rows, cols, fetchFn, options) {
|
|
247
|
-
try {
|
|
248
|
-
const result = await createBrokerClient(connection, fetchFn).resizePty(name, rows, cols, options);
|
|
249
|
-
return { ok: true, applied: result.applied !== false };
|
|
250
|
-
}
|
|
251
|
-
catch (err) {
|
|
252
|
-
const failure = mapBrokerSdkFailure(err);
|
|
253
|
-
return { ok: false, message: failure.message };
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
/**
|
|
257
|
-
* Release this session's PTY resize ownership on detach (single-resizer
|
|
258
|
-
* policy, #1247), so the next client that attaches can resize the shared PTY.
|
|
259
|
-
* Best-effort: the broker also supersedes a crashed owner after an idle window.
|
|
260
|
-
*
|
|
261
|
-
* `restoreSize` gives back the row and column a writable attach reserved for
|
|
262
|
-
* Relay's status line (see `reserveStatusLineRow`). Without it the worker stays
|
|
263
|
-
* at `rows - 1`/`cols - 1` after the status line disappears, and since a
|
|
264
|
-
* read-only `view` session never resizes the PTY, the agent's TUI would remain
|
|
265
|
-
* one row and column short until the next writable attach. The broker applies
|
|
266
|
-
* the size before dropping ownership, so this stays one round-trip and cannot
|
|
267
|
-
* lose the ordering race a separate resize call would introduce.
|
|
268
|
-
*/
|
|
269
|
-
export async function releaseResizeOwnership(connection, name, sessionId, fetchFn, restoreSize) {
|
|
270
|
-
try {
|
|
271
|
-
// Omitting the dimensions is a pure release — the broker skips the resize,
|
|
272
|
-
// so a session with no local TTY invents no placeholder size.
|
|
273
|
-
await createBrokerClient(connection, fetchFn).resizePty(name, restoreSize?.rows, restoreSize?.cols, {
|
|
274
|
-
sessionId,
|
|
275
|
-
release: true,
|
|
276
|
-
});
|
|
277
|
-
}
|
|
278
|
-
catch {
|
|
279
|
-
// Best-effort — ownership falls back to the broker's idle-takeover net.
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
/** ----- WS message classification ----- */
|
|
283
|
-
function isStringObject(value) {
|
|
284
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
285
|
-
}
|
|
286
|
-
/**
|
|
287
|
-
* Inspect a single WebSocket frame and classify it relative to the agent
|
|
288
|
-
* we're driving. Non-matching / malformed frames return `{ kind: 'other' }`
|
|
289
|
-
* so the caller can ignore them cheaply.
|
|
290
|
-
*
|
|
291
|
-
* Exported for unit testing the filter in isolation.
|
|
292
|
-
*/
|
|
293
|
-
export function classifyWsEvent(rawMessage, name) {
|
|
294
|
-
let parsed;
|
|
295
|
-
try {
|
|
296
|
-
parsed = JSON.parse(rawMessage);
|
|
297
|
-
}
|
|
298
|
-
catch {
|
|
299
|
-
return { kind: 'other' };
|
|
300
|
-
}
|
|
301
|
-
if (!isStringObject(parsed))
|
|
302
|
-
return { kind: 'other' };
|
|
303
|
-
// All three events we care about are scoped by the worker `name` field.
|
|
304
|
-
if (parsed.name !== name)
|
|
305
|
-
return { kind: 'other' };
|
|
306
|
-
if (parsed.kind === 'worker_stream') {
|
|
307
|
-
const chunk = parsed.chunk;
|
|
308
|
-
if (typeof chunk !== 'string')
|
|
309
|
-
return { kind: 'other' };
|
|
310
|
-
const offset = typeof parsed.offset === 'number' ? parsed.offset : undefined;
|
|
311
|
-
return { kind: 'worker_stream', chunk, offset };
|
|
312
|
-
}
|
|
313
|
-
if (parsed.kind === 'delivery_queued') {
|
|
314
|
-
// Two different layers emit `delivery_queued`. Only the inbound hold means
|
|
315
|
-
// "parked in the per-worker pending queue" — the count this status line
|
|
316
|
-
// shows and the one `/api/spawned/{name}/pending` seeds. The harness
|
|
317
|
-
// runtimes emit the same kind for every delivery they enqueue for
|
|
318
|
-
// injection, which is ordinary traffic on its way to the agent; counting
|
|
319
|
-
// those would make `pending` climb on every message the agent receives and
|
|
320
|
-
// never come back down (nothing drains a queue the message was never in).
|
|
321
|
-
if (parsed.reason !== 'inbound_delivery_manual_flush')
|
|
322
|
-
return { kind: 'other' };
|
|
323
|
-
// `event_id` correlates a replayed frame with the pending seed so the
|
|
324
|
-
// counter isn't double-incremented for a delivery already reflected in
|
|
325
|
-
// the seed (see the seed-dedup note in `runDriveSession`). Absent on
|
|
326
|
-
// legacy/mixed frames — treated as "not in the seed" (counted).
|
|
327
|
-
const eventId = typeof parsed.event_id === 'string' ? parsed.event_id : undefined;
|
|
328
|
-
return { kind: 'delivery_queued', eventId };
|
|
329
|
-
}
|
|
330
|
-
if (parsed.kind === 'agent_pending_drained') {
|
|
331
|
-
const count = typeof parsed.count === 'number' ? parsed.count : undefined;
|
|
332
|
-
return { kind: 'agent_pending_drained', count };
|
|
333
|
-
}
|
|
334
|
-
return { kind: 'other' };
|
|
335
|
-
}
|
|
336
|
-
/**
|
|
337
|
-
* Parser for the two local control bytes drive keeps: `Ctrl+C` detaches and
|
|
338
|
-
* `Ctrl+]` toggles inbound delivery between hold and live injection.
|
|
339
|
-
*
|
|
340
|
-
* Semantics:
|
|
341
|
-
* - `Ctrl+C` (0x03) → emit `detach`, never forwarded.
|
|
342
|
-
* - `Ctrl+]` (0x1D) → emit `toggle-delivery`, never forwarded.
|
|
343
|
-
* - Every other byte, including Ctrl+B and Ctrl+G, is forwarded to the agent.
|
|
344
|
-
*
|
|
345
|
-
* Neither byte can appear inside a multi-byte UTF-8 sequence (continuation
|
|
346
|
-
* bytes are ≥ 0x80) or a keyboard escape sequence, so scanning raw bytes is
|
|
347
|
-
* safe.
|
|
348
|
-
*/
|
|
349
|
-
export class KeybindParser {
|
|
350
|
-
/** Process one chunk; returns bytes to forward + actions to take. */
|
|
351
|
-
feed(chunk) {
|
|
352
|
-
const forward = [];
|
|
353
|
-
const actions = [];
|
|
354
|
-
for (const byte of chunk) {
|
|
355
|
-
if (byte === 0x03 /* Ctrl+C */) {
|
|
356
|
-
actions.push('detach');
|
|
357
|
-
break;
|
|
358
|
-
}
|
|
359
|
-
if (byte === 0x1d /* Ctrl+] */) {
|
|
360
|
-
actions.push('toggle-delivery');
|
|
361
|
-
continue;
|
|
362
|
-
}
|
|
363
|
-
forward.push(byte);
|
|
364
|
-
}
|
|
365
|
-
return {
|
|
366
|
-
forward: Buffer.from(forward),
|
|
367
|
-
actions,
|
|
368
|
-
};
|
|
369
|
-
}
|
|
370
|
-
/** Reset the parser (e.g. before tearing down). */
|
|
371
|
-
reset() { }
|
|
372
|
-
}
|
|
373
|
-
/** ----- Status line rendering ----- */
|
|
374
|
-
/**
|
|
375
|
-
* Render the bottom-of-terminal status line for `drive`. Uses ANSI
|
|
376
|
-
* save-cursor / restore-cursor so the agent's output isn't disturbed.
|
|
377
|
-
*
|
|
378
|
-
* Exported for unit testing — `runDriveSession` calls it on every
|
|
379
|
-
* pending-count change.
|
|
380
|
-
*/
|
|
381
|
-
export function renderStatusLine(opts) {
|
|
382
|
-
const row = Math.max(opts.rows ?? 24, 1);
|
|
383
|
-
const scrollTop = Math.max(1, opts.scrollTop ?? 1);
|
|
384
|
-
const scrollBottom = Math.max(scrollTop + 1, opts.scrollBottom ?? row - 1);
|
|
385
|
-
// The Ctrl+] hint names the action the NEXT press performs: in auto_inject
|
|
386
|
-
// (the session default) it holds; in manual_flush it delivers, draining the
|
|
387
|
-
// parked queue and going live again. Without the hint, a parked message is
|
|
388
|
-
// invisible beyond the pending counter and a held agent looks like it never
|
|
389
|
-
// receives replies.
|
|
390
|
-
const toggleHint = opts.mode === 'manual_flush' ? 'Ctrl+] deliver' : 'Ctrl+] hold';
|
|
391
|
-
const text = clampStatusLineText(`[drive ${opts.name} | delivery=${opts.mode} | pending=${opts.pending} | ${toggleHint} | Ctrl+C detach]`, opts.cols, true);
|
|
392
|
-
// ESC 7 = save cursor; ESC[<row>;1H = move to bottom row; ESC[2K = clear line;
|
|
393
|
-
// ESC[7m = reverse video; ESC[0m = reset; ESC 8 = restore cursor.
|
|
394
|
-
// Temporarily restore the full physical scroll region so CUP can reach the
|
|
395
|
-
// reserved row even if autowrap left the cursor below the child margin.
|
|
396
|
-
// Reinstall the child margin before restoring its cursor.
|
|
397
|
-
const restoreOrigin = opts.originMode ? '\x1b[?6h' : '';
|
|
398
|
-
return `\x1b7\x1b[?6l\x1b[r\x1b[${row};1H\x1b[2K\x1b[7m${text}\x1b[0m\x1b[${scrollTop};${scrollBottom}r${restoreOrigin}\x1b8`;
|
|
399
|
-
}
|
|
400
|
-
/**
|
|
401
|
-
* Run the interactive session. Subscribe-first: opens the event WS, buffers
|
|
402
|
-
* live `worker_stream` chunks, then (on subscribe) paints the snapshot,
|
|
403
|
-
* reconciles the buffer against the snapshot offset, forwards the initial
|
|
404
|
-
* resize, and takes over stdin. Restores the worker's previous mode on any
|
|
405
|
-
* exit path. Resolves with the exit code the CLI should propagate.
|
|
406
|
-
*/
|
|
407
|
-
function runDriveSessionLoop(state, deps) {
|
|
408
|
-
const { connection, name, previousMode, seededEventIds } = state;
|
|
409
|
-
// Connect with a `sinceSeq` cutoff so the broker replays only events after
|
|
410
|
-
// attach — historical durable events must not inflate the pending counter.
|
|
411
|
-
// Omit it when the cutoff is 0 (no durable events yet / lookup failed) so
|
|
412
|
-
// the URL and behaviour match the pre-cutoff default.
|
|
413
|
-
const wsUrl = state.cutoffSeq > 0 ? `${toWsUrl(connection.url)}?sinceSeq=${state.cutoffSeq}` : toWsUrl(connection.url);
|
|
414
|
-
const headers = {};
|
|
415
|
-
if (connection.apiKey) {
|
|
416
|
-
headers['X-API-Key'] = connection.apiKey;
|
|
417
|
-
}
|
|
418
|
-
return new Promise((resolve) => {
|
|
419
|
-
let settled = false;
|
|
420
|
-
let rawModeWasSet = false;
|
|
421
|
-
let unsubscribeResize = null;
|
|
422
|
-
// Stable per-attach id for the broker's single-resizer policy (#1247): all
|
|
423
|
-
// of this session's resizes carry it so we own the shared PTY size while
|
|
424
|
-
// driving, and we release it on detach.
|
|
425
|
-
const resizeSessionId = randomUUID();
|
|
426
|
-
// In-flight resize requests. Detach awaits these before releasing ownership
|
|
427
|
-
// so a late-resolving SIGWINCH resize can't re-claim the PTY *after* the
|
|
428
|
-
// release lands (single-resizer detach race, #1247).
|
|
429
|
-
const outstandingResizes = new Set();
|
|
430
|
-
const trackResize = (p) => {
|
|
431
|
-
outstandingResizes.add(p);
|
|
432
|
-
void p.finally(() => outstandingResizes.delete(p));
|
|
433
|
-
};
|
|
434
|
-
// Periodic ownership re-assert timer (see `ownershipReassertMs`).
|
|
435
|
-
let reassertTimer = null;
|
|
436
|
-
let pending = state.initialPending;
|
|
437
|
-
// This session's last-known inbound delivery mode and its broker revision.
|
|
438
|
-
// The attach asserted `auto_inject`; `Ctrl+]` toggles it mid-session, and
|
|
439
|
-
// the detach restore compare-and-sets against whatever this session last
|
|
440
|
-
// wrote so an out-of-band change is never clobbered.
|
|
441
|
-
let currentMode = 'auto_inject';
|
|
442
|
-
let currentRevision = state.sessionRevision;
|
|
443
|
-
let terminalRows = pickInitialTerminalRows(state.initialLocalSize, undefined);
|
|
444
|
-
let terminalCols = pickInitialTerminalCols(state.initialLocalSize, undefined);
|
|
445
|
-
const parser = new KeybindParser();
|
|
446
|
-
// Stateful UTF-8 decoder for forwarded stdin. Decoding each raw stdin chunk
|
|
447
|
-
// independently would turn a multi-byte character split across `data`
|
|
448
|
-
// events (routine in large pastes / IME) into U+FFFD; the StringDecoder
|
|
449
|
-
// buffers a trailing incomplete sequence until the next chunk completes it.
|
|
450
|
-
// Detach scanning still runs on raw bytes upstream (0x03 can't appear inside
|
|
451
|
-
// a multi-byte sequence), so this only touches the forwarded payload.
|
|
452
|
-
let inputDecoder = new StringDecoder('utf8');
|
|
453
|
-
let inputStream = null;
|
|
454
|
-
const cleanupSignals = [];
|
|
455
|
-
const isTtyOutput = state.initialLocalSize !== null;
|
|
456
|
-
// Skip the status line entirely when stdout is not a TTY (e.g. piped to
|
|
457
|
-
// `tee`) — a fabricated row-24 repaint would corrupt the captured log.
|
|
458
|
-
let statusLineEnabled = canReserveStatusLine(state.initialLocalSize);
|
|
459
|
-
// Subscribe-first: buffer live `worker_stream` chunks until the snapshot
|
|
460
|
-
// is painted and reconciled against its per-worker offset.
|
|
461
|
-
const sync = new StreamSyncBuffer();
|
|
462
|
-
// Adaptive predictive echo masks round-trip latency on remote brokers.
|
|
463
|
-
// Seeded with the snapshot (once painted) so its confirmed model matches
|
|
464
|
-
// the screen.
|
|
465
|
-
let initialAgentSize = reserveStatusLineRow(state.initialLocalSize);
|
|
466
|
-
const scrollRegion = new TerminalScrollRegionTracker(initialAgentSize?.rows ?? 1);
|
|
467
|
-
let observeRenderedOutput = (_chunk) => { };
|
|
468
|
-
const predictiveEcho = deps.createPredictiveEcho?.({
|
|
469
|
-
cols: initialAgentSize?.cols ?? 0,
|
|
470
|
-
rows: initialAgentSize?.rows ?? 0,
|
|
471
|
-
write: (chunk) => {
|
|
472
|
-
deps.writeChunk(chunk);
|
|
473
|
-
observeRenderedOutput(chunk);
|
|
474
|
-
},
|
|
475
|
-
getInputSrtt: () => inputStream?.srttMs ?? null,
|
|
476
|
-
}) ?? null;
|
|
477
|
-
// Tee the snapshot's painted bytes so we can seed the predictive-echo
|
|
478
|
-
// model with them — its cursor must match the real screen before we
|
|
479
|
-
// optimistically echo, or predicted glyphs land at the wrong position.
|
|
480
|
-
let snapshotBytes = '';
|
|
481
|
-
// Guard the snapshot paint on `settled`: a Ctrl+C during the snapshot HTTP
|
|
482
|
-
// fetch would otherwise paint the snapshot after teardown began (the render
|
|
483
|
-
// runs inside the awaited `captureAndRenderSnapshot`, past the WS guard).
|
|
484
|
-
const captureWrite = (chunk) => {
|
|
485
|
-
if (settled)
|
|
486
|
-
return;
|
|
487
|
-
deps.writeChunk(chunk);
|
|
488
|
-
snapshotBytes += chunk;
|
|
489
|
-
};
|
|
490
|
-
const correctSetupResize = async (baseline) => {
|
|
491
|
-
const latest = reserveStatusLineRow(deps.terminal.getSize());
|
|
492
|
-
if (!latest || (latest.rows === baseline?.rows && latest.cols === baseline?.cols))
|
|
493
|
-
return;
|
|
494
|
-
const correction = resizeWorker(connection, name, latest.rows, latest.cols, deps.fetch, {
|
|
495
|
-
sessionId: resizeSessionId,
|
|
496
|
-
});
|
|
497
|
-
trackResize(correction);
|
|
498
|
-
const result = await correction;
|
|
499
|
-
if (!result.ok) {
|
|
500
|
-
deps.log(`[drive] setup resize correction failed: ${result.message ?? 'unknown error'}`);
|
|
501
|
-
}
|
|
502
|
-
};
|
|
503
|
-
const beginSubscribedLayout = () => {
|
|
504
|
-
// Install this before the first resize/snapshot await so a local resize
|
|
505
|
-
// during setup cannot be lost.
|
|
506
|
-
unsubscribeResize ??= deps.terminal.onResize(resizeHandler);
|
|
507
|
-
const currentSize = deps.terminal.getSize();
|
|
508
|
-
terminalRows = pickInitialTerminalRows(currentSize, undefined);
|
|
509
|
-
terminalCols = currentSize?.cols;
|
|
510
|
-
statusLineEnabled = canReserveStatusLine(currentSize);
|
|
511
|
-
initialAgentSize = reserveStatusLineRow(currentSize);
|
|
512
|
-
if (initialAgentSize) {
|
|
513
|
-
scrollRegion.setRows(initialAgentSize.rows);
|
|
514
|
-
predictiveEcho?.onResize(initialAgentSize.cols, initialAgentSize.rows);
|
|
515
|
-
}
|
|
516
|
-
if (statusLineEnabled && initialAgentSize) {
|
|
517
|
-
deps.writeChunk(renderChildScrollRegion(initialAgentSize.rows));
|
|
518
|
-
}
|
|
519
|
-
};
|
|
520
|
-
// Boundary-held + coalesced status painter. Holds repaints while the agent
|
|
521
|
-
// is mid escape-sequence (no splicing into a half-sent CSI), rate-limits
|
|
522
|
-
// per-chunk repaints, and skips painting entirely on a non-TTY stdout.
|
|
523
|
-
const statusController = new StatusLineController({
|
|
524
|
-
render: () => {
|
|
525
|
-
const region = scrollRegion.region;
|
|
526
|
-
return renderStatusLine({
|
|
527
|
-
name,
|
|
528
|
-
mode: currentMode,
|
|
529
|
-
pending,
|
|
530
|
-
rows: terminalRows,
|
|
531
|
-
cols: terminalCols,
|
|
532
|
-
scrollTop: region.top,
|
|
533
|
-
scrollBottom: region.bottom,
|
|
534
|
-
originMode: scrollRegion.isOriginMode,
|
|
535
|
-
});
|
|
536
|
-
},
|
|
537
|
-
write: deps.writeChunk,
|
|
538
|
-
enabled: () => statusLineEnabled,
|
|
539
|
-
coalesceMs: deps.statusRepaintCoalesceMs ?? 40,
|
|
540
|
-
});
|
|
541
|
-
const paintStatus = () => {
|
|
542
|
-
statusController.request();
|
|
543
|
-
};
|
|
544
|
-
observeRenderedOutput = (chunk) => {
|
|
545
|
-
scrollRegion.push(chunk);
|
|
546
|
-
statusController.observeOutput(chunk);
|
|
547
|
-
};
|
|
548
|
-
// Route server output through the predictive-echo engine (which owns
|
|
549
|
-
// cursor save/restore) or straight to stdout. Feed every chunk to the
|
|
550
|
-
// status controller for boundary tracking. Repaint after each completed
|
|
551
|
-
// chunk because terminal autowrap can briefly cross a DECSTBM bottom
|
|
552
|
-
// margin. The clipped label cannot autowrap itself, and the child PTY's
|
|
553
|
-
// reserved row prevents cursor-addressed TUI frames from fighting it.
|
|
554
|
-
const applyServerOutput = (chunk) => {
|
|
555
|
-
if (predictiveEcho) {
|
|
556
|
-
void predictiveEcho.onServerOutput(chunk).then(() => {
|
|
557
|
-
paintStatus();
|
|
558
|
-
}, () => {
|
|
559
|
-
paintStatus();
|
|
560
|
-
});
|
|
561
|
-
}
|
|
562
|
-
else {
|
|
563
|
-
deps.writeChunk(chunk);
|
|
564
|
-
observeRenderedOutput(chunk);
|
|
565
|
-
paintStatus();
|
|
566
|
-
}
|
|
567
|
-
};
|
|
568
|
-
// Local-terminal resize handler. Forwards to the broker and
|
|
569
|
-
// repaints the status line at the new bottom-row index. Registered
|
|
570
|
-
// on `socket.on('open')` (same point we take over stdin) so a
|
|
571
|
-
// failed connection doesn't leave a dangling listener; unregistered
|
|
572
|
-
// in `teardownStdin` so detach is clean.
|
|
573
|
-
const resizeHandler = () => {
|
|
574
|
-
const size = deps.terminal.getSize();
|
|
575
|
-
if (!size)
|
|
576
|
-
return;
|
|
577
|
-
terminalRows = size.rows;
|
|
578
|
-
terminalCols = size.cols;
|
|
579
|
-
statusLineEnabled = canReserveStatusLine(size);
|
|
580
|
-
const agentSize = reserveStatusLineRow(size);
|
|
581
|
-
if (!agentSize)
|
|
582
|
-
return;
|
|
583
|
-
scrollRegion.setRows(agentSize.rows);
|
|
584
|
-
predictiveEcho?.onResize(agentSize.cols, agentSize.rows);
|
|
585
|
-
trackResize(resizeWorker(connection, name, agentSize.rows, agentSize.cols, deps.fetch, {
|
|
586
|
-
sessionId: resizeSessionId,
|
|
587
|
-
}).then((res) => {
|
|
588
|
-
if (!res.ok) {
|
|
589
|
-
deps.log(`[drive] resize forward failed: ${res.message ?? 'unknown error'}`);
|
|
590
|
-
}
|
|
591
|
-
else if (res.applied === false) {
|
|
592
|
-
deps.log('[drive] broker did not apply the reserved PTY size; using status repaint fallback');
|
|
593
|
-
}
|
|
594
|
-
}));
|
|
595
|
-
// Repaint regardless of fetch outcome — the local terminal has
|
|
596
|
-
// already moved, so the status line position needs to move with
|
|
597
|
-
// it whether or not the broker accepted the resize.
|
|
598
|
-
paintStatus();
|
|
599
|
-
};
|
|
600
|
-
// In-band delivery toggle (`Ctrl+]`). Flips the worker between
|
|
601
|
-
// `auto_inject` (the session default — messages inject live while you
|
|
602
|
-
// watch) and `manual_flush` (messages park so nothing splices into what
|
|
603
|
-
// you are typing); flipping back drains the parked queue into the PTY.
|
|
604
|
-
//
|
|
605
|
-
// Guarded compare-and-set against this session's last-known revision: if
|
|
606
|
-
// another session or CLI changed the mode out-of-band, the broker no-ops
|
|
607
|
-
// and reports the current mode/revision, which we adopt (the next press
|
|
608
|
-
// toggles from the adopted state). Pending-counter updates come from the
|
|
609
|
-
// broker's `agent_pending_drained` event, not from this response, so the
|
|
610
|
-
// count is never double-subtracted.
|
|
611
|
-
// In-flight toggle request, if any. `finish()` awaits it before the
|
|
612
|
-
// detach restore so a quick Ctrl+] → Ctrl+C can't restore against a
|
|
613
|
-
// stale mode/revision while the toggle PUT is still changing broker
|
|
614
|
-
// state — the session's `currentMode`/`currentRevision` are updated even
|
|
615
|
-
// when teardown began mid-request, precisely so the restore CASes
|
|
616
|
-
// against what this session actually last wrote.
|
|
617
|
-
let deliveryToggleInFlight = null;
|
|
618
|
-
const toggleDeliveryMode = () => {
|
|
619
|
-
if (deliveryToggleInFlight)
|
|
620
|
-
return deliveryToggleInFlight;
|
|
621
|
-
if (settled)
|
|
622
|
-
return Promise.resolve();
|
|
623
|
-
const run = async () => {
|
|
624
|
-
try {
|
|
625
|
-
const target = currentMode === 'manual_flush' ? 'auto_inject' : 'manual_flush';
|
|
626
|
-
// Always guard on the session's last-known mode; add the revision
|
|
627
|
-
// when the broker reports one. A legacy broker without revisions
|
|
628
|
-
// still gets mode-level CAS instead of an unconditional write.
|
|
629
|
-
const result = await createBrokerClient(connection, deps.fetch).setInboundDeliveryMode(name, target, {
|
|
630
|
-
expectedMode: currentMode,
|
|
631
|
-
...(currentRevision !== null ? { expectedRevision: currentRevision } : {}),
|
|
632
|
-
});
|
|
633
|
-
currentMode = result.mode;
|
|
634
|
-
if (result.revision !== null) {
|
|
635
|
-
currentRevision = result.revision;
|
|
636
|
-
}
|
|
637
|
-
if (settled)
|
|
638
|
-
return;
|
|
639
|
-
if (!result.matched) {
|
|
640
|
-
deps.log(`[drive] delivery mode was changed by another session; now ${result.mode}`);
|
|
641
|
-
}
|
|
642
|
-
paintStatus();
|
|
643
|
-
}
|
|
644
|
-
catch (err) {
|
|
645
|
-
if (settled)
|
|
646
|
-
return;
|
|
647
|
-
const failure = mapBrokerSdkFailure(err);
|
|
648
|
-
deps.log(`[drive] could not toggle delivery mode: ${failure.message ?? 'unknown error'}`);
|
|
649
|
-
}
|
|
650
|
-
};
|
|
651
|
-
deliveryToggleInFlight = run().finally(() => {
|
|
652
|
-
deliveryToggleInFlight = null;
|
|
653
|
-
});
|
|
654
|
-
return deliveryToggleInFlight;
|
|
655
|
-
};
|
|
656
|
-
// ---- input-stream liveness ----
|
|
657
|
-
// A closed PTY input stream is a session-liveness event, not a
|
|
658
|
-
// per-keystroke error. See `attach-input-recovery.ts` for why (#1419).
|
|
659
|
-
//
|
|
660
|
-
// Identity of the worker this session attached to, captured once at attach
|
|
661
|
-
// and compared after any reopen. `null` means the broker could not tell us,
|
|
662
|
-
// which is treated as "cannot verify" — never as "verified".
|
|
663
|
-
let attachedWorkerIdentity = null;
|
|
664
|
-
const inputRecovery = createInputStreamRecovery({
|
|
665
|
-
label: 'drive',
|
|
666
|
-
name,
|
|
667
|
-
maxAttempts: deps.inputReopenMaxAttempts ?? INPUT_REOPEN_MAX_ATTEMPTS,
|
|
668
|
-
baseDelayMs: deps.inputReopenBaseDelayMs ?? INPUT_REOPEN_BASE_DELAY_MS,
|
|
669
|
-
log: (message) => deps.log(message),
|
|
670
|
-
error: (message) => deps.error(message),
|
|
671
|
-
isSettled: () => settled,
|
|
672
|
-
getStream: () => inputStream,
|
|
673
|
-
setStream: (stream) => {
|
|
674
|
-
inputStream = stream;
|
|
675
|
-
},
|
|
676
|
-
openStream: () => deps.openInputStream(connection, name),
|
|
677
|
-
onRollback: () => predictiveEcho?.rollback(),
|
|
678
|
-
onBufferedInputDiscarded: () => {
|
|
679
|
-
inputDecoder = new StringDecoder('utf8');
|
|
680
|
-
},
|
|
681
|
-
onExhausted: () => finish(1),
|
|
682
|
-
verifyIdentity: async () => {
|
|
683
|
-
// Fail closed in both directions: if we never learned who we attached
|
|
684
|
-
// to, we cannot claim the replacement is the same process either.
|
|
685
|
-
if (attachedWorkerIdentity === null) {
|
|
686
|
-
return { ok: false, reason: 'worker identity was unavailable at attach' };
|
|
687
|
-
}
|
|
688
|
-
const current = await deps.getWorkerIdentity(connection, name);
|
|
689
|
-
if (current === null) {
|
|
690
|
-
return { ok: false, reason: 'worker identity could not be read after reconnect' };
|
|
691
|
-
}
|
|
692
|
-
if (current !== attachedWorkerIdentity) {
|
|
693
|
-
return { ok: false, reason: `worker process changed (${attachedWorkerIdentity} → ${current})` };
|
|
694
|
-
}
|
|
695
|
-
return { ok: true };
|
|
696
|
-
},
|
|
697
|
-
});
|
|
698
|
-
// ---- stdin handling ----
|
|
699
|
-
let stdinReady = false;
|
|
700
|
-
const stdinDataHandler = (chunk) => {
|
|
701
|
-
// Raw mode starts before snapshot replay so terminal input reports cannot
|
|
702
|
-
// echo. Until the predictive echo model is seeded, discard all input
|
|
703
|
-
// except Ctrl+C: forwarding stale mouse/focus reports (or echoing user
|
|
704
|
-
// input against an unseeded screen) would be worse than dropping it.
|
|
705
|
-
if (!stdinReady) {
|
|
706
|
-
if (chunk.includes(0x03))
|
|
707
|
-
finish(0);
|
|
708
|
-
return;
|
|
709
|
-
}
|
|
710
|
-
const outcome = parser.feed(chunk);
|
|
711
|
-
if (outcome.forward.length > 0) {
|
|
712
|
-
const stream = inputStream;
|
|
713
|
-
// A dead or missing stream is a liveness event, not a per-keystroke
|
|
714
|
-
// error. Recovery announces it once and buffers decoded input behind a
|
|
715
|
-
// strict same-worker identity gate.
|
|
716
|
-
//
|
|
717
|
-
// Skip only the *forwarding*; fall through to the action loop below.
|
|
718
|
-
// Ctrl+C can share a chunk with ordinary bytes, and returning here
|
|
719
|
-
// would swallow the detach — leaving the human unable to escape a
|
|
720
|
-
// broken session, which is worse than the flood.
|
|
721
|
-
if (!inputRecovery.isUsable(stream)) {
|
|
722
|
-
const decoded = inputDecoder.write(outcome.forward);
|
|
723
|
-
inputRecovery.recover('stream closed', decoded);
|
|
724
|
-
}
|
|
725
|
-
else {
|
|
726
|
-
// Decode through the stateful UTF-8 decoder so a multi-byte character
|
|
727
|
-
// split across stdin chunks is forwarded intact rather than as U+FFFD.
|
|
728
|
-
// An incomplete trailing sequence decodes to '' and is held until the
|
|
729
|
-
// next chunk completes it.
|
|
730
|
-
const decoded = inputDecoder.write(outcome.forward);
|
|
731
|
-
if (decoded.length > 0) {
|
|
732
|
-
// Fire-and-forget; don't block the event loop on every keystroke.
|
|
733
|
-
void stream.send(decoded).then(() => inputRecovery.noteSendSuccess(), (err) => {
|
|
734
|
-
if (settled)
|
|
735
|
-
return;
|
|
736
|
-
// Classified, not assumed: backpressure leaves the stream
|
|
737
|
-
// healthy and must not trigger a teardown.
|
|
738
|
-
inputRecovery.handleSendFailure(err);
|
|
739
|
-
});
|
|
740
|
-
}
|
|
741
|
-
predictiveEcho?.onUserInput(outcome.forward);
|
|
742
|
-
}
|
|
743
|
-
}
|
|
744
|
-
for (const action of outcome.actions) {
|
|
745
|
-
switch (action) {
|
|
746
|
-
case 'detach':
|
|
747
|
-
finish(0);
|
|
748
|
-
return;
|
|
749
|
-
case 'toggle-delivery':
|
|
750
|
-
void toggleDeliveryMode();
|
|
751
|
-
break;
|
|
752
|
-
}
|
|
753
|
-
}
|
|
754
|
-
};
|
|
755
|
-
const teardownStdin = () => {
|
|
756
|
-
try {
|
|
757
|
-
if (deps.stdin.off) {
|
|
758
|
-
deps.stdin.off('data', stdinDataHandler);
|
|
759
|
-
}
|
|
760
|
-
else if (deps.stdin.removeListener) {
|
|
761
|
-
deps.stdin.removeListener('data', stdinDataHandler);
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
catch {
|
|
765
|
-
// best effort
|
|
766
|
-
}
|
|
767
|
-
try {
|
|
768
|
-
if (rawModeWasSet && typeof deps.stdin.setRawMode === 'function') {
|
|
769
|
-
deps.stdin.setRawMode(false);
|
|
770
|
-
}
|
|
771
|
-
}
|
|
772
|
-
catch {
|
|
773
|
-
// best effort
|
|
774
|
-
}
|
|
775
|
-
try {
|
|
776
|
-
// Heal the local terminal: the snapshot + live stream may have left it
|
|
777
|
-
// in app-cursor / mouse / bracketed-paste / alt-screen mode. Gate on a
|
|
778
|
-
// TTY stdout (same signal that gates the status line).
|
|
779
|
-
resetLocalTerminalOnDetach(deps.writeChunk, isTtyOutput);
|
|
780
|
-
}
|
|
781
|
-
catch {
|
|
782
|
-
// best effort
|
|
783
|
-
}
|
|
784
|
-
try {
|
|
785
|
-
deps.stdin.pause();
|
|
786
|
-
}
|
|
787
|
-
catch {
|
|
788
|
-
// best effort
|
|
789
|
-
}
|
|
790
|
-
try {
|
|
791
|
-
if (unsubscribeResize) {
|
|
792
|
-
unsubscribeResize();
|
|
793
|
-
unsubscribeResize = null;
|
|
794
|
-
}
|
|
795
|
-
}
|
|
796
|
-
catch {
|
|
797
|
-
// best effort
|
|
798
|
-
}
|
|
799
|
-
try {
|
|
800
|
-
if (reassertTimer) {
|
|
801
|
-
clearInterval(reassertTimer);
|
|
802
|
-
reassertTimer = null;
|
|
803
|
-
}
|
|
804
|
-
}
|
|
805
|
-
catch {
|
|
806
|
-
// best effort
|
|
807
|
-
}
|
|
808
|
-
rawModeWasSet = false;
|
|
809
|
-
};
|
|
810
|
-
const closeInputStream = () => {
|
|
811
|
-
// Cancel any pending reopen backoff so a detach mid-recovery doesn't
|
|
812
|
-
// leave a timer holding a reference to a torn-down session.
|
|
813
|
-
inputRecovery.cancel();
|
|
814
|
-
const stream = inputStream;
|
|
815
|
-
inputStream = null;
|
|
816
|
-
if (!stream)
|
|
817
|
-
return;
|
|
818
|
-
try {
|
|
819
|
-
stream.close(1000, 'drive client exiting');
|
|
820
|
-
}
|
|
821
|
-
catch {
|
|
822
|
-
// best effort
|
|
823
|
-
}
|
|
824
|
-
};
|
|
825
|
-
const finish = (code) => {
|
|
826
|
-
if (settled)
|
|
827
|
-
return;
|
|
828
|
-
settled = true;
|
|
829
|
-
// Stop the status painter first so no queued repaint fires after we
|
|
830
|
-
// restore cooked mode (output would otherwise spray past detach).
|
|
831
|
-
statusController.dispose();
|
|
832
|
-
for (const cleanup of cleanupSignals.splice(0)) {
|
|
833
|
-
try {
|
|
834
|
-
cleanup();
|
|
835
|
-
}
|
|
836
|
-
catch {
|
|
837
|
-
// best effort
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
teardownStdin();
|
|
841
|
-
predictiveEcho?.reset();
|
|
842
|
-
closeInputStream();
|
|
843
|
-
// Release resize ownership so the next client can size the shared PTY.
|
|
844
|
-
// Await any in-flight resizes first: the release must be ordered *after*
|
|
845
|
-
// the last SIGWINCH resize resolves, or that resize could re-claim the
|
|
846
|
-
// PTY just after the release lands (detach race, #1247). `teardownStdin`
|
|
847
|
-
// has already stopped the resize handler and re-assert timer above, so
|
|
848
|
-
// no new resizes are enqueued past this point.
|
|
849
|
-
const releasePromise = (async () => {
|
|
850
|
-
try {
|
|
851
|
-
if (outstandingResizes.size > 0) {
|
|
852
|
-
await Promise.allSettled([...outstandingResizes]);
|
|
853
|
-
}
|
|
854
|
-
// Hand the reserved status row/column back in the same request, so
|
|
855
|
-
// the agent's TUI is not left one row and column short.
|
|
856
|
-
await releaseResizeOwnership(connection, name, resizeSessionId, deps.fetch, deps.terminal.getSize());
|
|
857
|
-
}
|
|
858
|
-
catch {
|
|
859
|
-
// Best-effort — the broker's idle-takeover net still frees ownership.
|
|
860
|
-
}
|
|
861
|
-
})();
|
|
862
|
-
try {
|
|
863
|
-
socket.close(1000, 'drive client exiting');
|
|
864
|
-
}
|
|
865
|
-
catch {
|
|
866
|
-
// best effort
|
|
867
|
-
}
|
|
868
|
-
// Drop the writer's pending queue and unhook its drain listener so no
|
|
869
|
-
// buffered chunk flushes to stdout after detach.
|
|
870
|
-
deps.disposeWriter?.();
|
|
871
|
-
// Best-effort restore: re-read the mode and only revert if it's still
|
|
872
|
-
// what this session set, so an explicit pre-attach `hold` is put back and
|
|
873
|
-
// a change another session made is never clobbered.
|
|
874
|
-
//
|
|
875
|
-
// Await the release alongside the restore before resolving: `resolve`
|
|
876
|
-
// typically ends the process, which aborts any still-pending fetch. The
|
|
877
|
-
// release awaits `outstandingResizes` first, so it would otherwise lose
|
|
878
|
-
// the race to the restore and be aborted, defeating the detach-race fix.
|
|
879
|
-
//
|
|
880
|
-
// Bound the wait: both are best-effort HTTP round-trips that can stall if
|
|
881
|
-
// the broker is down, and terminal exit must not hang on them. Resolve
|
|
882
|
-
// once they settle or after DETACH_CLEANUP_DEADLINE_MS, whichever first.
|
|
883
|
-
const cleanup = Promise.allSettled([
|
|
884
|
-
releasePromise,
|
|
885
|
-
// Compare-and-set against this session's LAST write (`Ctrl+]` may have
|
|
886
|
-
// toggled the mode and bumped the revision since the attach flip) so
|
|
887
|
-
// the restore still matches after an in-session toggle but never
|
|
888
|
-
// clobbers an out-of-band change. Await any in-flight toggle first —
|
|
889
|
-
// a quick Ctrl+] → Ctrl+C must not restore against the pre-toggle
|
|
890
|
-
// mode/revision while the toggle PUT is still landing — and read
|
|
891
|
-
// `currentMode`/`currentRevision` only after it settles.
|
|
892
|
-
(async () => {
|
|
893
|
-
if (deliveryToggleInFlight) {
|
|
894
|
-
try {
|
|
895
|
-
await deliveryToggleInFlight;
|
|
896
|
-
}
|
|
897
|
-
catch {
|
|
898
|
-
// best effort — restore proceeds with the latest known state
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
await restoreInboundDeliveryModeOnDetach(connection, name, previousMode, currentMode, currentRevision, 'drive', deps);
|
|
902
|
-
})(),
|
|
903
|
-
]);
|
|
904
|
-
let deadlineTimer;
|
|
905
|
-
const deadline = new Promise((res) => {
|
|
906
|
-
deadlineTimer = setTimeout(res, DETACH_CLEANUP_DEADLINE_MS);
|
|
907
|
-
});
|
|
908
|
-
void Promise.race([cleanup, deadline]).finally(() => {
|
|
909
|
-
if (deadlineTimer !== undefined)
|
|
910
|
-
clearTimeout(deadlineTimer);
|
|
911
|
-
resolve(code);
|
|
912
|
-
});
|
|
913
|
-
};
|
|
914
|
-
const socket = deps.createWebSocket(wsUrl, headers);
|
|
915
|
-
const openInputStreamAndSetRawMode = async () => {
|
|
916
|
-
try {
|
|
917
|
-
inputStream = deps.openInputStream(connection, name);
|
|
918
|
-
await inputStream.waitUntilOpen();
|
|
919
|
-
if (settled) {
|
|
920
|
-
closeInputStream();
|
|
921
|
-
return;
|
|
922
|
-
}
|
|
923
|
-
// Baseline for the reopen identity gate. Best-effort: a broker that
|
|
924
|
-
// won't tell us leaves this null, which makes any later reopen refuse
|
|
925
|
-
// rather than guess. Not fatal here — the initial attach is the seat
|
|
926
|
-
// the human asked for.
|
|
927
|
-
attachedWorkerIdentity = await deps.getWorkerIdentity(connection, name);
|
|
928
|
-
if (settled) {
|
|
929
|
-
closeInputStream();
|
|
930
|
-
return;
|
|
931
|
-
}
|
|
932
|
-
// Register the temporary input handler before raw mode. Ctrl+C is an
|
|
933
|
-
// ordinary byte in raw mode, so this keeps detach available while a
|
|
934
|
-
// snapshot fetch or initial resize is still pending.
|
|
935
|
-
deps.stdin.resume();
|
|
936
|
-
deps.stdin.on('data', stdinDataHandler);
|
|
937
|
-
if (typeof deps.stdin.setRawMode === 'function' && deps.stdin.isTTY !== false && !deps.stdin.isRaw) {
|
|
938
|
-
deps.stdin.setRawMode(true);
|
|
939
|
-
rawModeWasSet = true;
|
|
940
|
-
}
|
|
941
|
-
}
|
|
942
|
-
catch (err) {
|
|
943
|
-
if (settled)
|
|
944
|
-
return;
|
|
945
|
-
const message = describeError(err);
|
|
946
|
-
deps.error(`[drive] could not open PTY input stream: ${message}`);
|
|
947
|
-
finish(1);
|
|
948
|
-
}
|
|
949
|
-
};
|
|
950
|
-
const takeStdin = () => {
|
|
951
|
-
try {
|
|
952
|
-
if (settled)
|
|
953
|
-
return;
|
|
954
|
-
stdinReady = true;
|
|
955
|
-
// Subscribe to local-terminal resize events at the same point
|
|
956
|
-
// we take over stdin so the lifecycles match — both go away in
|
|
957
|
-
// `teardownStdin` on any exit path.
|
|
958
|
-
// Start the periodic ownership re-assert so an idle-but-live session
|
|
959
|
-
// keeps the single-resizer lease past the broker's stale window. The
|
|
960
|
-
// broker no-ops a same-size re-assert (no SIGWINCH/repaint).
|
|
961
|
-
const reassertMs = deps.ownershipReassertMs ?? 60_000;
|
|
962
|
-
if (reassertMs > 0) {
|
|
963
|
-
reassertTimer = setInterval(() => {
|
|
964
|
-
const size = deps.terminal.getSize() ?? state.initialLocalSize;
|
|
965
|
-
const agentSize = reserveStatusLineRow(size);
|
|
966
|
-
if (!agentSize)
|
|
967
|
-
return;
|
|
968
|
-
trackResize(resizeWorker(connection, name, agentSize.rows, agentSize.cols, deps.fetch, {
|
|
969
|
-
sessionId: resizeSessionId,
|
|
970
|
-
}).then((res) => {
|
|
971
|
-
if (!res.ok) {
|
|
972
|
-
deps.log(`[drive] resize ownership re-assert failed: ${res.message ?? 'unknown error'}`);
|
|
973
|
-
}
|
|
974
|
-
}));
|
|
975
|
-
}, reassertMs);
|
|
976
|
-
// Don't let the keep-alive timer hold the process open on its own.
|
|
977
|
-
reassertTimer.unref?.();
|
|
978
|
-
}
|
|
979
|
-
}
|
|
980
|
-
catch (err) {
|
|
981
|
-
if (settled)
|
|
982
|
-
return;
|
|
983
|
-
const message = describeError(err);
|
|
984
|
-
deps.error(`[drive] could not take terminal input: ${message}`);
|
|
985
|
-
finish(1);
|
|
986
|
-
}
|
|
987
|
-
};
|
|
988
|
-
// Runs once the event WS is subscribed: first reserve the local bottom row
|
|
989
|
-
// and take over stdin before replaying the snapshot. A source TUI can
|
|
990
|
-
// enable mouse/focus/alternate-scroll reporting in that replay, and
|
|
991
|
-
// cooked-mode stdin would echo those reports as visible escape text.
|
|
992
|
-
// The WS is already buffering, so the resize repaint is reconciled against
|
|
993
|
-
// the snapshot without a dead zone.
|
|
994
|
-
const onSubscribed = async () => {
|
|
995
|
-
beginSubscribedLayout();
|
|
996
|
-
await openInputStreamAndSetRawMode();
|
|
997
|
-
if (settled)
|
|
998
|
-
return;
|
|
999
|
-
const initialResize = syncInitialPtySize(connection, name, initialAgentSize, 'drive', deps, {
|
|
1000
|
-
sessionId: resizeSessionId,
|
|
1001
|
-
});
|
|
1002
|
-
trackResize(initialResize);
|
|
1003
|
-
await initialResize;
|
|
1004
|
-
if (settled)
|
|
1005
|
-
return;
|
|
1006
|
-
await correctSetupResize(initialAgentSize);
|
|
1007
|
-
const snapshot = await deps.captureAndRenderSnapshot(connection, name, {
|
|
1008
|
-
fetch: deps.fetch,
|
|
1009
|
-
writeChunk: captureWrite,
|
|
1010
|
-
fleetHint: deps.fleetHint,
|
|
1011
|
-
});
|
|
1012
|
-
if (settled)
|
|
1013
|
-
return;
|
|
1014
|
-
switch (snapshot.status) {
|
|
1015
|
-
case 'ok':
|
|
1016
|
-
break;
|
|
1017
|
-
case 'not_found':
|
|
1018
|
-
deps.error(`Error: ${snapshot.message ?? `no agent named '${name}'`}`);
|
|
1019
|
-
finish(1);
|
|
1020
|
-
return;
|
|
1021
|
-
case 'no_pty':
|
|
1022
|
-
deps.error(`Error: ${snapshot.message ?? `agent '${name}' has no PTY to drive`}`);
|
|
1023
|
-
finish(1);
|
|
1024
|
-
return;
|
|
1025
|
-
case 'unavailable':
|
|
1026
|
-
case 'transport_error':
|
|
1027
|
-
deps.log(`[drive] could not capture initial screen (${snapshot.message ?? snapshot.status}); streaming live output only`);
|
|
1028
|
-
break;
|
|
1029
|
-
}
|
|
1030
|
-
if (predictiveEcho) {
|
|
1031
|
-
try {
|
|
1032
|
-
await predictiveEcho.seed(snapshotBytes);
|
|
1033
|
-
}
|
|
1034
|
-
catch (err) {
|
|
1035
|
-
const message = describeError(err);
|
|
1036
|
-
deps.log(`[drive] could not seed predictive echo: ${message}`);
|
|
1037
|
-
finish(1);
|
|
1038
|
-
return;
|
|
1039
|
-
}
|
|
1040
|
-
if (settled)
|
|
1041
|
-
return;
|
|
1042
|
-
}
|
|
1043
|
-
const currentLocalSize = deps.terminal.getSize();
|
|
1044
|
-
terminalRows = pickInitialTerminalRows(currentLocalSize, snapshot.rows);
|
|
1045
|
-
terminalCols = pickInitialTerminalCols(currentLocalSize, snapshot.cols);
|
|
1046
|
-
// Track the snapshot bytes for boundary state before the first repaint.
|
|
1047
|
-
scrollRegion.push(snapshotBytes);
|
|
1048
|
-
statusController.observeOutput(snapshotBytes);
|
|
1049
|
-
paintStatus();
|
|
1050
|
-
// Reconcile buffered chunks. On `ok`, drop what the snapshot already
|
|
1051
|
-
// reflects (by offset); with no offset this drops the pre-snapshot
|
|
1052
|
-
// buffer (snapshot-authoritative, matching the legacy behaviour). On a
|
|
1053
|
-
// transient snapshot failure nothing was painted, so apply everything.
|
|
1054
|
-
const pendingChunks = snapshot.status === 'ok' ? sync.reconcile(snapshot.offset) : sync.flushAll();
|
|
1055
|
-
for (const chunk of pendingChunks)
|
|
1056
|
-
applyServerOutput(chunk);
|
|
1057
|
-
// Input forwarding starts only after predictive echo has been seeded by
|
|
1058
|
-
// the snapshot. Raw mode was already enabled above, so terminal reports
|
|
1059
|
-
// could not echo during the setup window.
|
|
1060
|
-
takeStdin();
|
|
1061
|
-
};
|
|
1062
|
-
// Hand off from the early restore handlers (installed before the awaited
|
|
1063
|
-
// setup) to the fuller session-loop handlers — no double restore.
|
|
1064
|
-
state.disposeEarlySignals();
|
|
1065
|
-
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
1066
|
-
const cleanup = deps.onSignal(signal, () => finish(0));
|
|
1067
|
-
if (typeof cleanup === 'function')
|
|
1068
|
-
cleanupSignals.push(cleanup);
|
|
1069
|
-
}
|
|
1070
|
-
socket.on('open', () => {
|
|
1071
|
-
void onSubscribed();
|
|
1072
|
-
});
|
|
1073
|
-
socket.on('message', (data) => {
|
|
1074
|
-
// Once teardown has begun, drop inbound frames so we don't write output
|
|
1075
|
-
// or repaint the status line after cooked mode is restored.
|
|
1076
|
-
if (settled)
|
|
1077
|
-
return;
|
|
1078
|
-
const text = typeof data === 'string' ? data : Buffer.isBuffer(data) ? data.toString('utf-8') : String(data);
|
|
1079
|
-
const event = classifyWsEvent(text, name);
|
|
1080
|
-
switch (event.kind) {
|
|
1081
|
-
case 'worker_stream':
|
|
1082
|
-
if (sync.push(event.chunk, event.offset))
|
|
1083
|
-
applyServerOutput(event.chunk);
|
|
1084
|
-
break;
|
|
1085
|
-
case 'delivery_queued':
|
|
1086
|
-
// A replayed frame (seq > cutoff) can still be for a delivery
|
|
1087
|
-
// already reflected in the seeded pending count when it raced the
|
|
1088
|
-
// cutoff/seed capture. Dedupe by `event_id`: count it once, then
|
|
1089
|
-
// forget the id so a genuine re-queue of the same event later still
|
|
1090
|
-
// registers.
|
|
1091
|
-
if (event.eventId !== undefined && seededEventIds.delete(event.eventId)) {
|
|
1092
|
-
break;
|
|
1093
|
-
}
|
|
1094
|
-
pending += 1;
|
|
1095
|
-
paintStatus();
|
|
1096
|
-
break;
|
|
1097
|
-
case 'agent_pending_drained':
|
|
1098
|
-
// Subtract the drained count when the broker reports one: a partial
|
|
1099
|
-
// drain (a failed injection stops the flush mid-queue) leaves the
|
|
1100
|
-
// remainder parked, and zeroing the counter would hide it. A legacy
|
|
1101
|
-
// frame without a count still zeroes.
|
|
1102
|
-
pending = typeof event.count === 'number' ? Math.max(0, pending - event.count) : 0;
|
|
1103
|
-
paintStatus();
|
|
1104
|
-
break;
|
|
1105
|
-
case 'other':
|
|
1106
|
-
break;
|
|
1107
|
-
}
|
|
1108
|
-
});
|
|
1109
|
-
socket.on('error', (err) => {
|
|
1110
|
-
deps.error(`[drive] WebSocket error: ${err.message}`);
|
|
1111
|
-
finish(1);
|
|
1112
|
-
});
|
|
1113
|
-
socket.on('close', (code, reason) => {
|
|
1114
|
-
if (settled)
|
|
1115
|
-
return;
|
|
1116
|
-
const reasonText = reason && reason.length > 0 ? reason.toString('utf-8') : '';
|
|
1117
|
-
if (code === 1000 || code === 1005) {
|
|
1118
|
-
finish(0);
|
|
1119
|
-
}
|
|
1120
|
-
else {
|
|
1121
|
-
deps.error(`[drive] connection closed (code: ${code}${reasonText ? `, reason: ${reasonText}` : ''})`);
|
|
1122
|
-
finish(1);
|
|
1123
|
-
}
|
|
1124
|
-
});
|
|
1125
|
-
});
|
|
1126
|
-
}
|
|
1127
|
-
/**
|
|
1128
|
-
* Open a `drive` session. Resolves with the exit code the CLI should
|
|
1129
|
-
* propagate. Cleans up its own stdin raw-mode and best-effort restores
|
|
1130
|
-
* the worker's previous inbound delivery mode on any exit path.
|
|
1131
|
-
*/
|
|
1132
|
-
export async function runDriveSession(agentName, options, deps) {
|
|
1133
|
-
const target = prepareAttachTarget(agentName, options, deps);
|
|
1134
|
-
if (!target)
|
|
1135
|
-
return 1;
|
|
1136
|
-
const { name, connection } = target;
|
|
1137
|
-
const flipResult = await switchInboundDeliveryModeOrAbort(connection, name, 'auto_inject', `switch '${name}' to auto_inject mode`, deps);
|
|
1138
|
-
if (!flipResult)
|
|
1139
|
-
return 1;
|
|
1140
|
-
const { previousMode, sessionRevision } = flipResult;
|
|
1141
|
-
// The mode is now asserted to `auto_inject`, but the terminal is still cooked
|
|
1142
|
-
// and we have several awaited HTTP round-trips (pending, cutoff, snapshot,
|
|
1143
|
-
// input stream) before the session loop installs its signal handlers. Ctrl+C
|
|
1144
|
-
// in that window would otherwise kill the process with the worker stranded in
|
|
1145
|
-
// this session's mode, silently discarding an explicit `hold` the operator had
|
|
1146
|
-
// set before attaching. Register early restore-and-exit handlers immediately;
|
|
1147
|
-
// the loop disposes them once its own handlers are ready (no double restore —
|
|
1148
|
-
// see `disposeEarlySignals`).
|
|
1149
|
-
let earlyHandled = false;
|
|
1150
|
-
const earlyCleanups = [];
|
|
1151
|
-
const earlyRestore = async () => {
|
|
1152
|
-
if (earlyHandled)
|
|
1153
|
-
return;
|
|
1154
|
-
earlyHandled = true;
|
|
1155
|
-
for (const cleanup of earlyCleanups.splice(0)) {
|
|
1156
|
-
try {
|
|
1157
|
-
cleanup();
|
|
1158
|
-
}
|
|
1159
|
-
catch {
|
|
1160
|
-
// best effort
|
|
1161
|
-
}
|
|
1162
|
-
}
|
|
1163
|
-
await restoreInboundDeliveryModeOnDetach(connection, name, previousMode, 'auto_inject', sessionRevision, 'drive', deps);
|
|
1164
|
-
deps.exit(0);
|
|
1165
|
-
};
|
|
1166
|
-
const disposeEarlySignals = () => {
|
|
1167
|
-
earlyHandled = true;
|
|
1168
|
-
for (const cleanup of earlyCleanups.splice(0)) {
|
|
1169
|
-
try {
|
|
1170
|
-
cleanup();
|
|
1171
|
-
}
|
|
1172
|
-
catch {
|
|
1173
|
-
// best effort
|
|
1174
|
-
}
|
|
1175
|
-
}
|
|
1176
|
-
};
|
|
1177
|
-
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
1178
|
-
const cleanup = deps.onSignal(signal, earlyRestore);
|
|
1179
|
-
if (typeof cleanup === 'function')
|
|
1180
|
-
earlyCleanups.push(cleanup);
|
|
1181
|
-
}
|
|
1182
|
-
const initialLocalSize = deps.terminal.getSize();
|
|
1183
|
-
// Capture the durable-event cutoff *first*, then seed the pending counter.
|
|
1184
|
-
//
|
|
1185
|
-
// The event WS replays durable `delivery_queued` frames with `seq >
|
|
1186
|
-
// cutoffSeq`. Reading the cutoff before the seed guarantees every delivery
|
|
1187
|
-
// NOT captured in the seed has `seq > cutoffSeq` (it was queued after the
|
|
1188
|
-
// cutoff snapshot), so it is replayed and counted — closing the
|
|
1189
|
-
// undercount hole where a delivery racing between the two reads was in
|
|
1190
|
-
// neither the seed nor the replay. The flip side (a delivery that IS in the
|
|
1191
|
-
// seed and also replays because its `seq > cutoffSeq`) is handled by
|
|
1192
|
-
// deduping replayed frames against the seed's `event_id`s (see
|
|
1193
|
-
// `seededEventIds` in the WS handler), so it's counted exactly once.
|
|
1194
|
-
const cutoffSeq = await getCurrentEventSeq(connection, deps.fetch);
|
|
1195
|
-
const { count: initialPending, eventIds: seededEventIds } = await getPendingSeed(connection, name, deps.fetch);
|
|
1196
|
-
return runDriveSessionLoop({
|
|
1197
|
-
connection,
|
|
1198
|
-
name,
|
|
1199
|
-
previousMode,
|
|
1200
|
-
sessionRevision,
|
|
1201
|
-
initialPending,
|
|
1202
|
-
seededEventIds,
|
|
1203
|
-
initialLocalSize,
|
|
1204
|
-
cutoffSeq,
|
|
1205
|
-
disposeEarlySignals,
|
|
1206
|
-
}, deps);
|
|
1207
|
-
}
|
|
1208
|
-
/** Run a drive session with default dependencies. Used by `runtime agent attach --mode drive`. */
|
|
1209
|
-
export function attachDrive(name, options, overrides = {}) {
|
|
1210
|
-
return runDriveSession(name, options, withDefaults(overrides));
|
|
1211
|
-
}
|
|
1212
|
-
//# sourceMappingURL=attach-drive.js.map
|