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,778 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* `agent-relay passthrough <name>` — read-write attach in passthrough session.
|
|
3
|
-
*
|
|
4
|
-
* The broker auto-injects inbound relay messages into the agent's PTY
|
|
5
|
-
* while the human also types; both writers race. That's the point —
|
|
6
|
-
* passthrough is for observe-and-occasionally-nudge sessions
|
|
7
|
-
* while the broker does its coordination thing. For exclusive
|
|
8
|
-
* deterministic control with no auto-inject, use `drive` instead.
|
|
9
|
-
*
|
|
10
|
-
* On attach, ensures the worker is in `auto_inject` delivery mode (it's the
|
|
11
|
-
* broker default, but if someone left a `drive` session the worker may
|
|
12
|
-
* be in `manual_flush` mode — `passthrough` flips it back for the session's
|
|
13
|
-
* duration and restores the prior mode on detach). On detach, restores
|
|
14
|
-
* the prior mode and leaves the agent running.
|
|
15
|
-
*
|
|
16
|
-
* The session loop (snapshot-on-attach, raw stdin, resize forwarding,
|
|
17
|
-
* Ctrl+C detach) mirrors the shape of
|
|
18
|
-
* `drive.ts` minus the pending-queue UI and manual delivery controls
|
|
19
|
-
* (there's no queue in passthrough session). `drive.ts` is the more
|
|
20
|
-
* heavily-commented version of the shared shape; this module
|
|
21
|
-
* duplicates rather than abstracts because the trimmed surface is
|
|
22
|
-
* small enough that an extra layer of indirection would cost more
|
|
23
|
-
* clarity than it saves.
|
|
24
|
-
*/
|
|
25
|
-
import { Buffer } from 'node:buffer';
|
|
26
|
-
import { randomUUID } from 'node:crypto';
|
|
27
|
-
import { StringDecoder } from 'node:string_decoder';
|
|
28
|
-
import WebSocket from 'ws';
|
|
29
|
-
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';
|
|
30
|
-
import { defaultStateDir, readConnectionFileFromDisk, toWsUrl, } from '../lib/broker-connection.js';
|
|
31
|
-
import { defaultExit, runSignalHandler } from '../lib/exit.js';
|
|
32
|
-
import { resolveFleetHint } from '../lib/fleet-hint.js';
|
|
33
|
-
import { createInputStreamRecovery, INPUT_REOPEN_BASE_DELAY_MS, INPUT_REOPEN_MAX_ATTEMPTS, } from './attach-input-recovery.js';
|
|
34
|
-
import { fetchWorkerIdentity, openPtyInputStream, releaseResizeOwnership, resizeWorker, } from './attach-drive.js';
|
|
35
|
-
import { describeError } from './describe-error.js';
|
|
36
|
-
import { createPredictiveEcho } from './predictive-echo-screen.js';
|
|
37
|
-
function withDefaults(overrides = {}) {
|
|
38
|
-
const fetchFn = overrides.fetch ?? ((input, init) => fetch(input, init));
|
|
39
|
-
const writer = createBackpressureAwareWriter(process.stdout);
|
|
40
|
-
return {
|
|
41
|
-
readConnectionFile: readConnectionFileFromDisk,
|
|
42
|
-
getDefaultStateDir: defaultStateDir,
|
|
43
|
-
env: process.env,
|
|
44
|
-
createWebSocket: (url, headers) => new WebSocket(url, { headers }),
|
|
45
|
-
writeChunk: writer.write,
|
|
46
|
-
disposeWriter: writer.dispose,
|
|
47
|
-
statusRepaintCoalesceMs: 40,
|
|
48
|
-
onSignal: (signal, handler) => {
|
|
49
|
-
const listener = () => runSignalHandler(handler);
|
|
50
|
-
process.on(signal, listener);
|
|
51
|
-
return () => process.off(signal, listener);
|
|
52
|
-
},
|
|
53
|
-
log: (...args) => console.error(...args),
|
|
54
|
-
error: (...args) => console.error(...args),
|
|
55
|
-
exit: defaultExit,
|
|
56
|
-
fetch: fetchFn,
|
|
57
|
-
captureAndRenderSnapshot,
|
|
58
|
-
fleetHint: resolveFleetHint,
|
|
59
|
-
stdin: process.stdin,
|
|
60
|
-
terminal: {
|
|
61
|
-
getSize: () => {
|
|
62
|
-
const stdout = process.stdout;
|
|
63
|
-
if (!stdout.isTTY)
|
|
64
|
-
return null;
|
|
65
|
-
const rows = stdout.rows;
|
|
66
|
-
const cols = stdout.columns;
|
|
67
|
-
if (typeof rows !== 'number' || typeof cols !== 'number')
|
|
68
|
-
return null;
|
|
69
|
-
return { rows, cols };
|
|
70
|
-
},
|
|
71
|
-
onResize: (handler) => {
|
|
72
|
-
process.stdout.on('resize', handler);
|
|
73
|
-
return () => process.stdout.off('resize', handler);
|
|
74
|
-
},
|
|
75
|
-
},
|
|
76
|
-
openInputStream: (connection, name) => openPtyInputStream(connection, name, fetchFn),
|
|
77
|
-
getWorkerIdentity: (connection, name) => fetchWorkerIdentity(connection, name, fetchFn),
|
|
78
|
-
createPredictiveEcho,
|
|
79
|
-
...overrides,
|
|
80
|
-
};
|
|
81
|
-
}
|
|
82
|
-
/** ----- WS message classification ----- */
|
|
83
|
-
function isStringObject(value) {
|
|
84
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
85
|
-
}
|
|
86
|
-
/**
|
|
87
|
-
* Inspect a single WebSocket frame and classify it relative to the
|
|
88
|
-
* agent we're following. Non-matching / malformed frames return
|
|
89
|
-
* `{ kind: 'other' }` so the caller can ignore them cheaply.
|
|
90
|
-
*/
|
|
91
|
-
export function classifyWsEvent(rawMessage, name) {
|
|
92
|
-
let parsed;
|
|
93
|
-
try {
|
|
94
|
-
parsed = JSON.parse(rawMessage);
|
|
95
|
-
}
|
|
96
|
-
catch {
|
|
97
|
-
return { kind: 'other' };
|
|
98
|
-
}
|
|
99
|
-
if (!isStringObject(parsed))
|
|
100
|
-
return { kind: 'other' };
|
|
101
|
-
if (parsed.name !== name)
|
|
102
|
-
return { kind: 'other' };
|
|
103
|
-
if (parsed.kind === 'worker_stream') {
|
|
104
|
-
const chunk = parsed.chunk;
|
|
105
|
-
if (typeof chunk !== 'string')
|
|
106
|
-
return { kind: 'other' };
|
|
107
|
-
const offset = typeof parsed.offset === 'number' ? parsed.offset : undefined;
|
|
108
|
-
return { kind: 'worker_stream', chunk, offset };
|
|
109
|
-
}
|
|
110
|
-
return { kind: 'other' };
|
|
111
|
-
}
|
|
112
|
-
/**
|
|
113
|
-
* Parser for the one local control byte passthrough keeps: `Ctrl+C` detaches.
|
|
114
|
-
*
|
|
115
|
-
* Semantics:
|
|
116
|
-
* - `Ctrl+C` (0x03) → emit `detach`, never forwarded.
|
|
117
|
-
* - Every other byte, including Ctrl+B and Ctrl+G, is forwarded to the agent.
|
|
118
|
-
*/
|
|
119
|
-
export class PassthroughKeybindParser {
|
|
120
|
-
feed(chunk) {
|
|
121
|
-
const forward = [];
|
|
122
|
-
const actions = [];
|
|
123
|
-
for (const byte of chunk) {
|
|
124
|
-
if (byte === 0x03 /* Ctrl+C */) {
|
|
125
|
-
actions.push('detach');
|
|
126
|
-
break;
|
|
127
|
-
}
|
|
128
|
-
forward.push(byte);
|
|
129
|
-
}
|
|
130
|
-
return { forward: Buffer.from(forward), actions };
|
|
131
|
-
}
|
|
132
|
-
reset() { }
|
|
133
|
-
}
|
|
134
|
-
/** ----- Status line rendering ----- */
|
|
135
|
-
/**
|
|
136
|
-
* Render the bottom-of-terminal status line for `passthrough`. Same
|
|
137
|
-
* save/restore-cursor trick as `drive`, no pending counter (there
|
|
138
|
-
* isn't one in passthrough session).
|
|
139
|
-
*/
|
|
140
|
-
export function renderStatusLine(opts) {
|
|
141
|
-
const row = Math.max(opts.rows ?? 24, 1);
|
|
142
|
-
const scrollTop = Math.max(1, opts.scrollTop ?? 1);
|
|
143
|
-
const scrollBottom = Math.max(scrollTop + 1, opts.scrollBottom ?? row - 1);
|
|
144
|
-
const text = clampStatusLineText(`[passthrough ${opts.name} | delivery=${opts.mode} | Ctrl+C detach]`, opts.cols, true);
|
|
145
|
-
const restoreOrigin = opts.originMode ? '\x1b[?6h' : '';
|
|
146
|
-
return `\x1b7\x1b[?6l\x1b[r\x1b[${row};1H\x1b[2K\x1b[7m${text}\x1b[0m\x1b[${scrollTop};${scrollBottom}r${restoreOrigin}\x1b8`;
|
|
147
|
-
}
|
|
148
|
-
/** ----- Main session runner ----- */
|
|
149
|
-
/**
|
|
150
|
-
* Open a `passthrough` session. Resolves with the exit code the CLI
|
|
151
|
-
* should propagate. Cleans up its own stdin raw-mode and best-effort
|
|
152
|
-
* restores the worker's previous inbound delivery mode on any exit path.
|
|
153
|
-
*/
|
|
154
|
-
export async function runPassthroughSession(agentName, options, deps) {
|
|
155
|
-
const target = prepareAttachTarget(agentName, options, deps);
|
|
156
|
-
if (!target)
|
|
157
|
-
return 1;
|
|
158
|
-
const { name, connection } = target;
|
|
159
|
-
// Even when the worker is already in `auto_inject` we still issue the
|
|
160
|
-
// PUT — it's idempotent on the broker and gives us an early hard
|
|
161
|
-
// failure on missing-agent before we touch the terminal.
|
|
162
|
-
const flipResult = await switchInboundDeliveryModeOrAbort(connection, name, 'auto_inject', `ensure '${name}' is in passthrough session`, deps);
|
|
163
|
-
if (!flipResult)
|
|
164
|
-
return 1;
|
|
165
|
-
const { previousMode, sessionRevision } = flipResult;
|
|
166
|
-
// The mode is now flipped to `auto_inject`. If the user had an explicit
|
|
167
|
-
// `agent message hold` (manual_flush) active, killing the process with Ctrl+C
|
|
168
|
-
// before the session loop installs its handlers would strand the worker in
|
|
169
|
-
// auto_inject, silently cancelling their hold. Register early restore-and-exit
|
|
170
|
-
// handlers immediately; the loop disposes them once its own handlers are up.
|
|
171
|
-
let earlyHandled = false;
|
|
172
|
-
const earlyCleanups = [];
|
|
173
|
-
const earlyRestore = async () => {
|
|
174
|
-
if (earlyHandled)
|
|
175
|
-
return;
|
|
176
|
-
earlyHandled = true;
|
|
177
|
-
for (const cleanup of earlyCleanups.splice(0)) {
|
|
178
|
-
try {
|
|
179
|
-
cleanup();
|
|
180
|
-
}
|
|
181
|
-
catch {
|
|
182
|
-
// best effort
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
await restoreInboundDeliveryModeOnDetach(connection, name, previousMode, 'auto_inject', sessionRevision, 'passthrough', deps);
|
|
186
|
-
deps.exit(0);
|
|
187
|
-
};
|
|
188
|
-
const disposeEarlySignals = () => {
|
|
189
|
-
earlyHandled = true;
|
|
190
|
-
for (const cleanup of earlyCleanups.splice(0)) {
|
|
191
|
-
try {
|
|
192
|
-
cleanup();
|
|
193
|
-
}
|
|
194
|
-
catch {
|
|
195
|
-
// best effort
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
};
|
|
199
|
-
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
200
|
-
const cleanup = deps.onSignal(signal, earlyRestore);
|
|
201
|
-
if (typeof cleanup === 'function')
|
|
202
|
-
earlyCleanups.push(cleanup);
|
|
203
|
-
}
|
|
204
|
-
const initialLocalSize = deps.terminal.getSize();
|
|
205
|
-
const wsUrl = toWsUrl(connection.url);
|
|
206
|
-
const headers = {};
|
|
207
|
-
if (connection.apiKey) {
|
|
208
|
-
headers['X-API-Key'] = connection.apiKey;
|
|
209
|
-
}
|
|
210
|
-
return new Promise((resolve) => {
|
|
211
|
-
let settled = false;
|
|
212
|
-
let rawModeWasSet = false;
|
|
213
|
-
let unsubscribeResize = null;
|
|
214
|
-
// Per-attach id for the single-resizer policy (#1247). See attach-drive.ts.
|
|
215
|
-
const resizeSessionId = randomUUID();
|
|
216
|
-
// In-flight resize requests, awaited before release on detach so a late
|
|
217
|
-
// SIGWINCH resize can't re-claim after the release (detach race, #1247).
|
|
218
|
-
const outstandingResizes = new Set();
|
|
219
|
-
const trackResize = (p) => {
|
|
220
|
-
outstandingResizes.add(p);
|
|
221
|
-
void p.finally(() => outstandingResizes.delete(p));
|
|
222
|
-
};
|
|
223
|
-
// Periodic ownership re-assert timer (see `ownershipReassertMs`).
|
|
224
|
-
let reassertTimer = null;
|
|
225
|
-
const parser = new PassthroughKeybindParser();
|
|
226
|
-
// Stateful UTF-8 decoder for forwarded stdin — a multi-byte character split
|
|
227
|
-
// across stdin chunks would otherwise become U+FFFD. See attach-drive.ts.
|
|
228
|
-
let inputDecoder = new StringDecoder('utf8');
|
|
229
|
-
let inputStream = null;
|
|
230
|
-
const cleanupSignals = [];
|
|
231
|
-
const isTtyOutput = initialLocalSize !== null;
|
|
232
|
-
// Skip the status line entirely when stdout is not a TTY (piped output).
|
|
233
|
-
let statusLineEnabled = canReserveStatusLine(initialLocalSize);
|
|
234
|
-
// Subscribe-first: buffer live `worker_stream` chunks until the snapshot
|
|
235
|
-
// is painted and reconciled against its per-worker offset (no lost/dup
|
|
236
|
-
// output around attach time). See StreamSyncBuffer.
|
|
237
|
-
const sync = new StreamSyncBuffer();
|
|
238
|
-
let terminalRows = pickInitialTerminalRows(initialLocalSize, undefined);
|
|
239
|
-
let terminalCols = pickInitialTerminalCols(initialLocalSize, undefined);
|
|
240
|
-
// Adaptive predictive echo masks round-trip latency on remote brokers.
|
|
241
|
-
// Seeded with the snapshot (after it is painted) so its confirmed model
|
|
242
|
-
// matches the screen.
|
|
243
|
-
let initialAgentSize = reserveStatusLineRow(initialLocalSize);
|
|
244
|
-
const scrollRegion = new TerminalScrollRegionTracker(initialAgentSize?.rows ?? 1);
|
|
245
|
-
let observeRenderedOutput = (_chunk) => { };
|
|
246
|
-
const predictiveEcho = deps.createPredictiveEcho?.({
|
|
247
|
-
cols: initialAgentSize?.cols ?? 0,
|
|
248
|
-
rows: initialAgentSize?.rows ?? 0,
|
|
249
|
-
write: (chunk) => {
|
|
250
|
-
deps.writeChunk(chunk);
|
|
251
|
-
observeRenderedOutput(chunk);
|
|
252
|
-
},
|
|
253
|
-
getInputSrtt: () => inputStream?.srttMs ?? null,
|
|
254
|
-
}) ?? null;
|
|
255
|
-
// Tee the snapshot's painted bytes so we can seed the predictive-echo
|
|
256
|
-
// model with them — its cursor must match the real screen before we
|
|
257
|
-
// optimistically echo, or predicted glyphs land at the wrong position.
|
|
258
|
-
let snapshotBytes = '';
|
|
259
|
-
// Guard the snapshot paint on `settled`: a Ctrl+C during the snapshot HTTP
|
|
260
|
-
// fetch would otherwise paint the snapshot after teardown began (the render
|
|
261
|
-
// runs inside the awaited `captureAndRenderSnapshot`, past the WS guard).
|
|
262
|
-
const captureWrite = (chunk) => {
|
|
263
|
-
if (settled)
|
|
264
|
-
return;
|
|
265
|
-
deps.writeChunk(chunk);
|
|
266
|
-
snapshotBytes += chunk;
|
|
267
|
-
};
|
|
268
|
-
const correctSetupResize = async (baseline) => {
|
|
269
|
-
const latest = reserveStatusLineRow(deps.terminal.getSize());
|
|
270
|
-
if (!latest || (latest.rows === baseline?.rows && latest.cols === baseline?.cols))
|
|
271
|
-
return;
|
|
272
|
-
const correction = resizeWorker(connection, name, latest.rows, latest.cols, deps.fetch, {
|
|
273
|
-
sessionId: resizeSessionId,
|
|
274
|
-
});
|
|
275
|
-
trackResize(correction);
|
|
276
|
-
const result = await correction;
|
|
277
|
-
if (!result.ok) {
|
|
278
|
-
deps.log(`[passthrough] setup resize correction failed: ${result.message ?? 'unknown error'}`);
|
|
279
|
-
}
|
|
280
|
-
};
|
|
281
|
-
const beginSubscribedLayout = () => {
|
|
282
|
-
unsubscribeResize ??= deps.terminal.onResize(resizeHandler);
|
|
283
|
-
const currentSize = deps.terminal.getSize();
|
|
284
|
-
terminalRows = pickInitialTerminalRows(currentSize, undefined);
|
|
285
|
-
terminalCols = currentSize?.cols;
|
|
286
|
-
statusLineEnabled = canReserveStatusLine(currentSize);
|
|
287
|
-
initialAgentSize = reserveStatusLineRow(currentSize);
|
|
288
|
-
if (initialAgentSize) {
|
|
289
|
-
scrollRegion.setRows(initialAgentSize.rows);
|
|
290
|
-
predictiveEcho?.onResize(initialAgentSize.cols, initialAgentSize.rows);
|
|
291
|
-
}
|
|
292
|
-
if (statusLineEnabled && initialAgentSize) {
|
|
293
|
-
deps.writeChunk(renderChildScrollRegion(initialAgentSize.rows));
|
|
294
|
-
}
|
|
295
|
-
};
|
|
296
|
-
// Boundary-held + coalesced status painter (skips non-TTY stdout).
|
|
297
|
-
const statusController = new StatusLineController({
|
|
298
|
-
render: () => {
|
|
299
|
-
const region = scrollRegion.region;
|
|
300
|
-
return renderStatusLine({
|
|
301
|
-
name,
|
|
302
|
-
mode: 'auto_inject',
|
|
303
|
-
rows: terminalRows,
|
|
304
|
-
cols: terminalCols,
|
|
305
|
-
scrollTop: region.top,
|
|
306
|
-
scrollBottom: region.bottom,
|
|
307
|
-
originMode: scrollRegion.isOriginMode,
|
|
308
|
-
});
|
|
309
|
-
},
|
|
310
|
-
write: deps.writeChunk,
|
|
311
|
-
enabled: () => statusLineEnabled,
|
|
312
|
-
coalesceMs: deps.statusRepaintCoalesceMs ?? 40,
|
|
313
|
-
});
|
|
314
|
-
const paintStatus = () => {
|
|
315
|
-
statusController.request();
|
|
316
|
-
};
|
|
317
|
-
observeRenderedOutput = (chunk) => {
|
|
318
|
-
scrollRegion.push(chunk);
|
|
319
|
-
statusController.observeOutput(chunk);
|
|
320
|
-
};
|
|
321
|
-
// Route server output through the predictive-echo engine (which owns
|
|
322
|
-
// cursor save/restore) or straight to stdout. Repaint at safe ANSI
|
|
323
|
-
// boundaries after each chunk: cursor-addressed output remains confined
|
|
324
|
-
// to the smaller PTY, while this restores the row after terminal autowrap.
|
|
325
|
-
const applyServerOutput = (chunk) => {
|
|
326
|
-
if (predictiveEcho) {
|
|
327
|
-
void predictiveEcho.onServerOutput(chunk).then(() => {
|
|
328
|
-
paintStatus();
|
|
329
|
-
}, () => {
|
|
330
|
-
paintStatus();
|
|
331
|
-
});
|
|
332
|
-
}
|
|
333
|
-
else {
|
|
334
|
-
deps.writeChunk(chunk);
|
|
335
|
-
observeRenderedOutput(chunk);
|
|
336
|
-
paintStatus();
|
|
337
|
-
}
|
|
338
|
-
};
|
|
339
|
-
const resizeHandler = () => {
|
|
340
|
-
const size = deps.terminal.getSize();
|
|
341
|
-
if (!size)
|
|
342
|
-
return;
|
|
343
|
-
terminalRows = size.rows;
|
|
344
|
-
terminalCols = size.cols;
|
|
345
|
-
statusLineEnabled = canReserveStatusLine(size);
|
|
346
|
-
const agentSize = reserveStatusLineRow(size);
|
|
347
|
-
if (!agentSize)
|
|
348
|
-
return;
|
|
349
|
-
scrollRegion.setRows(agentSize.rows);
|
|
350
|
-
predictiveEcho?.onResize(agentSize.cols, agentSize.rows);
|
|
351
|
-
trackResize(resizeWorker(connection, name, agentSize.rows, agentSize.cols, deps.fetch, {
|
|
352
|
-
sessionId: resizeSessionId,
|
|
353
|
-
}).then((res) => {
|
|
354
|
-
if (!res.ok) {
|
|
355
|
-
deps.log(`[passthrough] resize forward failed: ${res.message ?? 'unknown error'}`);
|
|
356
|
-
}
|
|
357
|
-
else if (res.applied === false) {
|
|
358
|
-
deps.log('[passthrough] broker did not apply the reserved PTY size; using status repaint fallback');
|
|
359
|
-
}
|
|
360
|
-
}));
|
|
361
|
-
paintStatus();
|
|
362
|
-
};
|
|
363
|
-
// ---- input-stream liveness ----
|
|
364
|
-
// Same defect and same contract as drive; see `attach-input-recovery.ts`.
|
|
365
|
-
// Identity of the worker this session attached to; see attach-drive.ts.
|
|
366
|
-
let attachedWorkerIdentity = null;
|
|
367
|
-
const inputRecovery = createInputStreamRecovery({
|
|
368
|
-
label: 'passthrough',
|
|
369
|
-
name,
|
|
370
|
-
maxAttempts: deps.inputReopenMaxAttempts ?? INPUT_REOPEN_MAX_ATTEMPTS,
|
|
371
|
-
baseDelayMs: deps.inputReopenBaseDelayMs ?? INPUT_REOPEN_BASE_DELAY_MS,
|
|
372
|
-
log: (message) => deps.log(message),
|
|
373
|
-
error: (message) => deps.error(message),
|
|
374
|
-
isSettled: () => settled,
|
|
375
|
-
getStream: () => inputStream,
|
|
376
|
-
setStream: (stream) => {
|
|
377
|
-
inputStream = stream;
|
|
378
|
-
},
|
|
379
|
-
openStream: () => deps.openInputStream(connection, name),
|
|
380
|
-
onRollback: () => predictiveEcho?.rollback(),
|
|
381
|
-
onBufferedInputDiscarded: () => {
|
|
382
|
-
inputDecoder = new StringDecoder('utf8');
|
|
383
|
-
},
|
|
384
|
-
onExhausted: () => finish(1),
|
|
385
|
-
verifyIdentity: async () => {
|
|
386
|
-
if (attachedWorkerIdentity === null) {
|
|
387
|
-
return { ok: false, reason: 'worker identity was unavailable at attach' };
|
|
388
|
-
}
|
|
389
|
-
const current = await deps.getWorkerIdentity(connection, name);
|
|
390
|
-
if (current === null) {
|
|
391
|
-
return { ok: false, reason: 'worker identity could not be read after reconnect' };
|
|
392
|
-
}
|
|
393
|
-
if (current !== attachedWorkerIdentity) {
|
|
394
|
-
return {
|
|
395
|
-
ok: false,
|
|
396
|
-
reason: `worker process changed (${attachedWorkerIdentity} → ${current})`,
|
|
397
|
-
};
|
|
398
|
-
}
|
|
399
|
-
return { ok: true };
|
|
400
|
-
},
|
|
401
|
-
});
|
|
402
|
-
let stdinReady = false;
|
|
403
|
-
const stdinDataHandler = (chunk) => {
|
|
404
|
-
// Raw mode starts before snapshot replay so terminal input reports cannot
|
|
405
|
-
// echo. Until the predictive echo model is seeded, discard all input
|
|
406
|
-
// except Ctrl+C: forwarding stale mouse/focus reports (or echoing user
|
|
407
|
-
// input against an unseeded screen) would be worse than dropping it.
|
|
408
|
-
if (!stdinReady) {
|
|
409
|
-
if (chunk.includes(0x03))
|
|
410
|
-
finish(0);
|
|
411
|
-
return;
|
|
412
|
-
}
|
|
413
|
-
const outcome = parser.feed(chunk);
|
|
414
|
-
if (outcome.forward.length > 0) {
|
|
415
|
-
const stream = inputStream;
|
|
416
|
-
// A dead or missing stream is a liveness event, not a per-keystroke
|
|
417
|
-
// error — see `attach-input-recovery.ts` (#1419). Recovery buffers the
|
|
418
|
-
// decoded input and replays it only after the worker identity matches.
|
|
419
|
-
//
|
|
420
|
-
// Skip only the *forwarding* and fall through to the action loop:
|
|
421
|
-
// Ctrl+C can share a chunk with ordinary bytes, and returning here
|
|
422
|
-
// would swallow the detach mid-outage.
|
|
423
|
-
if (!inputRecovery.isUsable(stream)) {
|
|
424
|
-
const decoded = inputDecoder.write(outcome.forward);
|
|
425
|
-
inputRecovery.recover('stream closed', decoded);
|
|
426
|
-
}
|
|
427
|
-
else {
|
|
428
|
-
// Decode through the stateful UTF-8 decoder so a multi-byte character
|
|
429
|
-
// split across stdin chunks is forwarded intact rather than as U+FFFD.
|
|
430
|
-
const decoded = inputDecoder.write(outcome.forward);
|
|
431
|
-
if (decoded.length > 0) {
|
|
432
|
-
void stream.send(decoded).then(() => inputRecovery.noteSendSuccess(), (err) => {
|
|
433
|
-
if (settled)
|
|
434
|
-
return;
|
|
435
|
-
inputRecovery.handleSendFailure(err);
|
|
436
|
-
});
|
|
437
|
-
}
|
|
438
|
-
predictiveEcho?.onUserInput(outcome.forward);
|
|
439
|
-
}
|
|
440
|
-
}
|
|
441
|
-
for (const action of outcome.actions) {
|
|
442
|
-
switch (action) {
|
|
443
|
-
case 'detach':
|
|
444
|
-
finish(0);
|
|
445
|
-
return;
|
|
446
|
-
}
|
|
447
|
-
}
|
|
448
|
-
};
|
|
449
|
-
const teardownStdin = () => {
|
|
450
|
-
try {
|
|
451
|
-
if (deps.stdin.off) {
|
|
452
|
-
deps.stdin.off('data', stdinDataHandler);
|
|
453
|
-
}
|
|
454
|
-
else if (deps.stdin.removeListener) {
|
|
455
|
-
deps.stdin.removeListener('data', stdinDataHandler);
|
|
456
|
-
}
|
|
457
|
-
}
|
|
458
|
-
catch {
|
|
459
|
-
// best effort
|
|
460
|
-
}
|
|
461
|
-
try {
|
|
462
|
-
if (rawModeWasSet && typeof deps.stdin.setRawMode === 'function') {
|
|
463
|
-
deps.stdin.setRawMode(false);
|
|
464
|
-
}
|
|
465
|
-
}
|
|
466
|
-
catch {
|
|
467
|
-
// best effort
|
|
468
|
-
}
|
|
469
|
-
try {
|
|
470
|
-
// Heal the local terminal on detach: the snapshot + live stream may
|
|
471
|
-
// have left it in app-cursor / mouse / bracketed-paste / alt-screen
|
|
472
|
-
// mode. Gate on TTY stdout (same signal as the status line).
|
|
473
|
-
resetLocalTerminalOnDetach(deps.writeChunk, isTtyOutput);
|
|
474
|
-
}
|
|
475
|
-
catch {
|
|
476
|
-
// best effort
|
|
477
|
-
}
|
|
478
|
-
try {
|
|
479
|
-
deps.stdin.pause();
|
|
480
|
-
}
|
|
481
|
-
catch {
|
|
482
|
-
// best effort
|
|
483
|
-
}
|
|
484
|
-
try {
|
|
485
|
-
if (unsubscribeResize) {
|
|
486
|
-
unsubscribeResize();
|
|
487
|
-
unsubscribeResize = null;
|
|
488
|
-
}
|
|
489
|
-
}
|
|
490
|
-
catch {
|
|
491
|
-
// best effort
|
|
492
|
-
}
|
|
493
|
-
try {
|
|
494
|
-
if (reassertTimer) {
|
|
495
|
-
clearInterval(reassertTimer);
|
|
496
|
-
reassertTimer = null;
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
catch {
|
|
500
|
-
// best effort
|
|
501
|
-
}
|
|
502
|
-
rawModeWasSet = false;
|
|
503
|
-
};
|
|
504
|
-
const closeInputStream = () => {
|
|
505
|
-
// Cancel any pending reopen backoff so a detach mid-recovery doesn't
|
|
506
|
-
// leave a timer holding a reference to a torn-down session.
|
|
507
|
-
inputRecovery.cancel();
|
|
508
|
-
const stream = inputStream;
|
|
509
|
-
inputStream = null;
|
|
510
|
-
if (!stream)
|
|
511
|
-
return;
|
|
512
|
-
try {
|
|
513
|
-
stream.close(1000, 'passthrough client exiting');
|
|
514
|
-
}
|
|
515
|
-
catch {
|
|
516
|
-
// best effort
|
|
517
|
-
}
|
|
518
|
-
};
|
|
519
|
-
const finish = (code) => {
|
|
520
|
-
if (settled)
|
|
521
|
-
return;
|
|
522
|
-
settled = true;
|
|
523
|
-
// Stop the status painter before restoring cooked mode so no queued
|
|
524
|
-
// repaint sprays output past detach.
|
|
525
|
-
statusController.dispose();
|
|
526
|
-
for (const cleanup of cleanupSignals.splice(0)) {
|
|
527
|
-
try {
|
|
528
|
-
cleanup();
|
|
529
|
-
}
|
|
530
|
-
catch {
|
|
531
|
-
// best effort
|
|
532
|
-
}
|
|
533
|
-
}
|
|
534
|
-
teardownStdin();
|
|
535
|
-
predictiveEcho?.reset();
|
|
536
|
-
closeInputStream();
|
|
537
|
-
// Release resize ownership so the next client can size the shared PTY.
|
|
538
|
-
// Await any in-flight resizes first so a late one can't re-claim the PTY
|
|
539
|
-
// after the release lands (detach race, #1247). `teardownStdin` already
|
|
540
|
-
// stopped the resize handler and re-assert timer, so nothing new is
|
|
541
|
-
// enqueued past this point.
|
|
542
|
-
const releasePromise = (async () => {
|
|
543
|
-
try {
|
|
544
|
-
if (outstandingResizes.size > 0) {
|
|
545
|
-
await Promise.allSettled([...outstandingResizes]);
|
|
546
|
-
}
|
|
547
|
-
// Hand the reserved status row/column back in the same request, so
|
|
548
|
-
// the agent's TUI is not left one row and column short.
|
|
549
|
-
await releaseResizeOwnership(connection, name, resizeSessionId, deps.fetch, deps.terminal.getSize());
|
|
550
|
-
}
|
|
551
|
-
catch {
|
|
552
|
-
// Best-effort — the broker's idle-takeover net still frees ownership.
|
|
553
|
-
}
|
|
554
|
-
})();
|
|
555
|
-
try {
|
|
556
|
-
socket.close(1000, 'passthrough client exiting');
|
|
557
|
-
}
|
|
558
|
-
catch {
|
|
559
|
-
// best effort
|
|
560
|
-
}
|
|
561
|
-
// Drop the writer's pending queue and unhook its drain listener so no
|
|
562
|
-
// buffered chunk flushes to stdout after detach.
|
|
563
|
-
deps.disposeWriter?.();
|
|
564
|
-
// Best-effort restore: re-read and only revert if the mode is still what
|
|
565
|
-
// this session set, so we don't clobber another session's change or
|
|
566
|
-
// force a default when the pre-attach mode was unknown.
|
|
567
|
-
//
|
|
568
|
-
// Await the release alongside the restore before resolving: `resolve`
|
|
569
|
-
// typically ends the process, which aborts any still-pending fetch. The
|
|
570
|
-
// release awaits `outstandingResizes` first, so it would otherwise lose
|
|
571
|
-
// the race to the restore and be aborted, defeating the detach-race fix.
|
|
572
|
-
//
|
|
573
|
-
// Bound the wait: both are best-effort HTTP round-trips that can stall if
|
|
574
|
-
// the broker is down, and terminal exit must not hang on them. Resolve
|
|
575
|
-
// once they settle or after DETACH_CLEANUP_DEADLINE_MS, whichever first.
|
|
576
|
-
const cleanup = Promise.allSettled([
|
|
577
|
-
releasePromise,
|
|
578
|
-
restoreInboundDeliveryModeOnDetach(connection, name, previousMode, 'auto_inject', sessionRevision, 'passthrough', deps),
|
|
579
|
-
]);
|
|
580
|
-
let deadlineTimer;
|
|
581
|
-
const deadline = new Promise((res) => {
|
|
582
|
-
deadlineTimer = setTimeout(res, DETACH_CLEANUP_DEADLINE_MS);
|
|
583
|
-
});
|
|
584
|
-
void Promise.race([cleanup, deadline]).finally(() => {
|
|
585
|
-
if (deadlineTimer !== undefined)
|
|
586
|
-
clearTimeout(deadlineTimer);
|
|
587
|
-
resolve(code);
|
|
588
|
-
});
|
|
589
|
-
};
|
|
590
|
-
const socket = deps.createWebSocket(wsUrl, headers);
|
|
591
|
-
const openInputStreamAndSetRawMode = async () => {
|
|
592
|
-
try {
|
|
593
|
-
inputStream = deps.openInputStream(connection, name);
|
|
594
|
-
await inputStream.waitUntilOpen();
|
|
595
|
-
if (settled) {
|
|
596
|
-
closeInputStream();
|
|
597
|
-
return;
|
|
598
|
-
}
|
|
599
|
-
// Baseline for the reopen identity gate; null makes a later reopen
|
|
600
|
-
// refuse rather than guess. See attach-drive.ts.
|
|
601
|
-
attachedWorkerIdentity = await deps.getWorkerIdentity(connection, name);
|
|
602
|
-
if (settled) {
|
|
603
|
-
closeInputStream();
|
|
604
|
-
return;
|
|
605
|
-
}
|
|
606
|
-
// Register the temporary input handler before raw mode. Ctrl+C is an
|
|
607
|
-
// ordinary byte in raw mode, so this keeps detach available while a
|
|
608
|
-
// snapshot fetch or initial resize is still pending.
|
|
609
|
-
deps.stdin.resume();
|
|
610
|
-
deps.stdin.on('data', stdinDataHandler);
|
|
611
|
-
if (typeof deps.stdin.setRawMode === 'function' && deps.stdin.isTTY !== false && !deps.stdin.isRaw) {
|
|
612
|
-
deps.stdin.setRawMode(true);
|
|
613
|
-
rawModeWasSet = true;
|
|
614
|
-
}
|
|
615
|
-
}
|
|
616
|
-
catch (err) {
|
|
617
|
-
if (settled)
|
|
618
|
-
return;
|
|
619
|
-
const message = describeError(err);
|
|
620
|
-
deps.error(`[passthrough] could not open PTY input stream: ${message}`);
|
|
621
|
-
finish(1);
|
|
622
|
-
}
|
|
623
|
-
};
|
|
624
|
-
const takeStdin = () => {
|
|
625
|
-
try {
|
|
626
|
-
if (settled)
|
|
627
|
-
return;
|
|
628
|
-
stdinReady = true;
|
|
629
|
-
// Periodic ownership re-assert (see `ownershipReassertMs`): keeps the
|
|
630
|
-
// single-resizer lease alive on an idle-but-live session; the broker
|
|
631
|
-
// no-ops a same-size re-assert (no SIGWINCH/repaint).
|
|
632
|
-
const reassertMs = deps.ownershipReassertMs ?? 60_000;
|
|
633
|
-
if (reassertMs > 0) {
|
|
634
|
-
reassertTimer = setInterval(() => {
|
|
635
|
-
const size = deps.terminal.getSize() ?? initialLocalSize;
|
|
636
|
-
const agentSize = reserveStatusLineRow(size);
|
|
637
|
-
if (!agentSize)
|
|
638
|
-
return;
|
|
639
|
-
trackResize(resizeWorker(connection, name, agentSize.rows, agentSize.cols, deps.fetch, {
|
|
640
|
-
sessionId: resizeSessionId,
|
|
641
|
-
}).then((res) => {
|
|
642
|
-
if (!res.ok) {
|
|
643
|
-
deps.log(`[passthrough] resize ownership re-assert failed: ${res.message ?? 'unknown error'}`);
|
|
644
|
-
}
|
|
645
|
-
}));
|
|
646
|
-
}, reassertMs);
|
|
647
|
-
reassertTimer.unref?.();
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
catch (err) {
|
|
651
|
-
if (settled)
|
|
652
|
-
return;
|
|
653
|
-
const message = describeError(err);
|
|
654
|
-
deps.error(`[passthrough] could not take terminal input: ${message}`);
|
|
655
|
-
finish(1);
|
|
656
|
-
}
|
|
657
|
-
};
|
|
658
|
-
// Runs once the event WS is subscribed: first reserve the local bottom row
|
|
659
|
-
// and take over stdin before replaying the snapshot. A source TUI can
|
|
660
|
-
// enable mouse/focus/alternate-scroll reporting in that replay, and
|
|
661
|
-
// cooked-mode stdin would echo those reports as visible escape text. The
|
|
662
|
-
// subscribed WS buffers the resize repaint for reconciliation.
|
|
663
|
-
const onSubscribed = async () => {
|
|
664
|
-
beginSubscribedLayout();
|
|
665
|
-
await openInputStreamAndSetRawMode();
|
|
666
|
-
if (settled)
|
|
667
|
-
return;
|
|
668
|
-
const initialResize = syncInitialPtySize(connection, name, initialAgentSize, 'passthrough', deps, {
|
|
669
|
-
sessionId: resizeSessionId,
|
|
670
|
-
});
|
|
671
|
-
trackResize(initialResize);
|
|
672
|
-
await initialResize;
|
|
673
|
-
if (settled)
|
|
674
|
-
return;
|
|
675
|
-
await correctSetupResize(initialAgentSize);
|
|
676
|
-
const snapshot = await deps.captureAndRenderSnapshot(connection, name, {
|
|
677
|
-
fetch: deps.fetch,
|
|
678
|
-
writeChunk: captureWrite,
|
|
679
|
-
fleetHint: deps.fleetHint,
|
|
680
|
-
});
|
|
681
|
-
if (settled)
|
|
682
|
-
return;
|
|
683
|
-
switch (snapshot.status) {
|
|
684
|
-
case 'ok':
|
|
685
|
-
break;
|
|
686
|
-
case 'not_found':
|
|
687
|
-
deps.error(`Error: ${snapshot.message ?? `no agent named '${name}'`}`);
|
|
688
|
-
finish(1);
|
|
689
|
-
return;
|
|
690
|
-
case 'no_pty':
|
|
691
|
-
deps.error(`Error: ${snapshot.message ?? `agent '${name}' has no PTY to attach to`}`);
|
|
692
|
-
finish(1);
|
|
693
|
-
return;
|
|
694
|
-
case 'unavailable':
|
|
695
|
-
case 'transport_error':
|
|
696
|
-
deps.log(`[passthrough] could not capture initial screen (${snapshot.message ?? snapshot.status}); streaming live output only`);
|
|
697
|
-
break;
|
|
698
|
-
}
|
|
699
|
-
if (predictiveEcho) {
|
|
700
|
-
try {
|
|
701
|
-
await predictiveEcho.seed(snapshotBytes);
|
|
702
|
-
}
|
|
703
|
-
catch (err) {
|
|
704
|
-
const message = describeError(err);
|
|
705
|
-
deps.log(`[passthrough] could not seed predictive echo: ${message}`);
|
|
706
|
-
finish(1);
|
|
707
|
-
return;
|
|
708
|
-
}
|
|
709
|
-
if (settled)
|
|
710
|
-
return;
|
|
711
|
-
}
|
|
712
|
-
const currentLocalSize = deps.terminal.getSize();
|
|
713
|
-
terminalRows = pickInitialTerminalRows(currentLocalSize, snapshot.rows);
|
|
714
|
-
terminalCols = pickInitialTerminalCols(currentLocalSize, snapshot.cols);
|
|
715
|
-
// Track the snapshot bytes for boundary state before the first repaint.
|
|
716
|
-
scrollRegion.push(snapshotBytes);
|
|
717
|
-
statusController.observeOutput(snapshotBytes);
|
|
718
|
-
paintStatus();
|
|
719
|
-
// Reconcile buffered chunks. On `ok`, drop what the snapshot already
|
|
720
|
-
// reflects (by offset); with no offset this drops the pre-snapshot
|
|
721
|
-
// buffer (snapshot-authoritative, matching the legacy behaviour). On a
|
|
722
|
-
// transient snapshot failure nothing was painted, so apply everything.
|
|
723
|
-
const pending = snapshot.status === 'ok' ? sync.reconcile(snapshot.offset) : sync.flushAll();
|
|
724
|
-
for (const chunk of pending)
|
|
725
|
-
applyServerOutput(chunk);
|
|
726
|
-
// Input forwarding starts only after predictive echo has been seeded by
|
|
727
|
-
// the snapshot. Raw mode was already enabled above, so terminal reports
|
|
728
|
-
// could not echo during the setup window.
|
|
729
|
-
takeStdin();
|
|
730
|
-
};
|
|
731
|
-
// Hand off from the early restore handlers to the fuller loop handlers.
|
|
732
|
-
disposeEarlySignals();
|
|
733
|
-
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
734
|
-
const cleanup = deps.onSignal(signal, () => finish(0));
|
|
735
|
-
if (typeof cleanup === 'function')
|
|
736
|
-
cleanupSignals.push(cleanup);
|
|
737
|
-
}
|
|
738
|
-
socket.on('open', () => {
|
|
739
|
-
void onSubscribed();
|
|
740
|
-
});
|
|
741
|
-
socket.on('message', (data) => {
|
|
742
|
-
// Drop inbound frames once teardown has begun (no output past detach).
|
|
743
|
-
if (settled)
|
|
744
|
-
return;
|
|
745
|
-
const text = typeof data === 'string' ? data : Buffer.isBuffer(data) ? data.toString('utf-8') : String(data);
|
|
746
|
-
const event = classifyWsEvent(text, name);
|
|
747
|
-
switch (event.kind) {
|
|
748
|
-
case 'worker_stream':
|
|
749
|
-
if (sync.push(event.chunk, event.offset))
|
|
750
|
-
applyServerOutput(event.chunk);
|
|
751
|
-
break;
|
|
752
|
-
case 'other':
|
|
753
|
-
break;
|
|
754
|
-
}
|
|
755
|
-
});
|
|
756
|
-
socket.on('error', (err) => {
|
|
757
|
-
deps.error(`[passthrough] WebSocket error: ${err.message}`);
|
|
758
|
-
finish(1);
|
|
759
|
-
});
|
|
760
|
-
socket.on('close', (code, reason) => {
|
|
761
|
-
if (settled)
|
|
762
|
-
return;
|
|
763
|
-
const reasonText = reason && reason.length > 0 ? reason.toString('utf-8') : '';
|
|
764
|
-
if (code === 1000 || code === 1005) {
|
|
765
|
-
finish(0);
|
|
766
|
-
}
|
|
767
|
-
else {
|
|
768
|
-
deps.error(`[passthrough] connection closed (code: ${code}${reasonText ? `, reason: ${reasonText}` : ''})`);
|
|
769
|
-
finish(1);
|
|
770
|
-
}
|
|
771
|
-
});
|
|
772
|
-
});
|
|
773
|
-
}
|
|
774
|
-
/** Run a passthrough session with default dependencies. Used by `runtime agent attach --mode passthrough`. */
|
|
775
|
-
export function attachPassthrough(name, options, overrides = {}) {
|
|
776
|
-
return runPassthroughSession(name, options, withDefaults(overrides));
|
|
777
|
-
}
|
|
778
|
-
//# sourceMappingURL=attach-passthrough.js.map
|