agent-relay 17.2.0 → 18.0.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 +45 -270
- 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 +1 -1
- package/dist/cli/commands/cloud-worker.d.ts.map +1 -1
- package/dist/cli/commands/cloud-worker.js +42 -31
- 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 +6 -7
- 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 +4 -4
- package/dist/cli/commands/product-surfaces.js.map +1 -1
- 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 +37 -0
- package/dist/cli/lib/agent-relay-cli-reentry.d.ts.map +1 -0
- package/dist/cli/lib/agent-relay-cli-reentry.js +40 -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/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 +10 -15
- 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
package/dist/cli/lib/attach.js
DELETED
|
@@ -1,1180 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Shared helpers for attach-style CLI commands (`view`, `drive`,
|
|
3
|
-
* `passthrough`).
|
|
4
|
-
*
|
|
5
|
-
* - `captureAndRenderSnapshot` renders the agent's current visible screen
|
|
6
|
-
* so the user doesn't attach to a quiet agent and stare at a blank
|
|
7
|
-
* terminal until the next output.
|
|
8
|
-
* - `prepareAttachTarget` / `pickInitialTerminalRows` / `syncInitialPtySize`
|
|
9
|
-
* / `switchInboundDeliveryModeOrAbort` / `captureInitialSnapshot` are
|
|
10
|
-
* the take-over prep steps that `drive` and `passthrough` both run on
|
|
11
|
-
* attach; centralised here so the two verbs stay in lockstep.
|
|
12
|
-
*/
|
|
13
|
-
import { describeMissingBrokerConnection, resolveBrokerConnection, } from './broker-connection.js';
|
|
14
|
-
import { createBrokerClient, mapBrokerSdkFailure } from './attach-broker.js';
|
|
15
|
-
/**
|
|
16
|
-
* Fetch a worker's current visible screen as ANSI reproduction bytes and
|
|
17
|
-
* write them to the caller's output.
|
|
18
|
-
*
|
|
19
|
-
* The attach clients open and subscribe to the WebSocket event stream
|
|
20
|
-
* *first*, buffer incoming `worker_stream` chunks, then call this to paint
|
|
21
|
-
* the snapshot, and finally reconcile the buffer against the snapshot's
|
|
22
|
-
* `offset` (see {@link StreamSyncBuffer}). That ordering closes the gap
|
|
23
|
-
* between the snapshot and the live stream: no output emitted around attach
|
|
24
|
-
* time is lost, and the per-worker byte offset lets the client drop exactly
|
|
25
|
-
* the chunks the snapshot already reflects so nothing is double-applied.
|
|
26
|
-
*
|
|
27
|
-
* On brokers that don't report an `offset`, the clients fall back to
|
|
28
|
-
* snapshot-authoritative behaviour (paint the snapshot, discard chunks that
|
|
29
|
-
* arrived before it), which trades a tiny gap for no duplication — the same
|
|
30
|
-
* bias the pre-offset code had.
|
|
31
|
-
*
|
|
32
|
-
* @returns A status describing the outcome. `ok` means the screen was
|
|
33
|
-
* rendered; other variants carry a message the caller can surface. `offset`
|
|
34
|
-
* is populated on `ok` when the broker reports one.
|
|
35
|
-
*/
|
|
36
|
-
export async function captureAndRenderSnapshot(connection, agentName, deps) {
|
|
37
|
-
let body;
|
|
38
|
-
try {
|
|
39
|
-
body = await createBrokerClient(connection, deps.fetch).snapshot(agentName, 'ansi');
|
|
40
|
-
}
|
|
41
|
-
catch (err) {
|
|
42
|
-
const failure = mapBrokerSdkFailure(err);
|
|
43
|
-
if (failure.status === 404) {
|
|
44
|
-
let hint = null;
|
|
45
|
-
if (deps.fleetHint) {
|
|
46
|
-
try {
|
|
47
|
-
hint = await deps.fleetHint(agentName);
|
|
48
|
-
}
|
|
49
|
-
catch {
|
|
50
|
-
// Best-effort lookup — preserve the existing not-found message.
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
const safeArg = `'${agentName.replace(/'/g, "'\\''")}'`;
|
|
54
|
-
const message = hint
|
|
55
|
-
? `agent '${agentName}' is ${hint}; cross-node attach is not yet supported` +
|
|
56
|
-
` — run \`agent-relay node agent attach ${safeArg}\` on that machine`
|
|
57
|
-
: `no agent named '${agentName}'`;
|
|
58
|
-
return { status: 'not_found', message };
|
|
59
|
-
}
|
|
60
|
-
if (failure.status === 409) {
|
|
61
|
-
return {
|
|
62
|
-
status: 'no_pty',
|
|
63
|
-
message: `agent '${agentName}' has no PTY (headless worker — nothing to view)`,
|
|
64
|
-
};
|
|
65
|
-
}
|
|
66
|
-
if (failure.status === 0 || failure.status === 200) {
|
|
67
|
-
return { status: 'transport_error', message: failure.message };
|
|
68
|
-
}
|
|
69
|
-
return { status: 'unavailable', message: `snapshot returned HTTP ${failure.status}` };
|
|
70
|
-
}
|
|
71
|
-
if (typeof body !== 'object' || body === null) {
|
|
72
|
-
return { status: 'transport_error', message: 'snapshot response was not an object' };
|
|
73
|
-
}
|
|
74
|
-
const obj = body;
|
|
75
|
-
const screen = obj.screen;
|
|
76
|
-
if (typeof screen !== 'string') {
|
|
77
|
-
return { status: 'transport_error', message: "snapshot response missing 'screen' field" };
|
|
78
|
-
}
|
|
79
|
-
// Snapshot bytes are mostly ASCII (escape sequences) plus the cell
|
|
80
|
-
// characters which are valid Unicode codepoints (alacritty stores
|
|
81
|
-
// chars, not bytes). UTF-8 round-trips cleanly.
|
|
82
|
-
const decoded = Buffer.from(screen, 'base64').toString('utf-8');
|
|
83
|
-
deps.writeChunk(decoded);
|
|
84
|
-
const rows = typeof obj.rows === 'number' ? obj.rows : undefined;
|
|
85
|
-
const cols = typeof obj.cols === 'number' ? obj.cols : undefined;
|
|
86
|
-
const offset = typeof obj.offset === 'number' ? obj.offset : undefined;
|
|
87
|
-
const cursorRaw = Array.isArray(obj.cursor) ? obj.cursor : undefined;
|
|
88
|
-
const cursor = cursorRaw &&
|
|
89
|
-
cursorRaw.length === 2 &&
|
|
90
|
-
typeof cursorRaw[0] === 'number' &&
|
|
91
|
-
typeof cursorRaw[1] === 'number'
|
|
92
|
-
? [cursorRaw[0], cursorRaw[1]]
|
|
93
|
-
: undefined;
|
|
94
|
-
return { status: 'ok', rows, cols, cursor, offset };
|
|
95
|
-
}
|
|
96
|
-
/**
|
|
97
|
-
* Reconciles a visible-screen snapshot with the live `worker_stream` byte
|
|
98
|
-
* stream so an attaching client neither loses nor double-applies output
|
|
99
|
-
* around attach time.
|
|
100
|
-
*
|
|
101
|
-
* Usage (subscribe-first):
|
|
102
|
-
*
|
|
103
|
-
* 1. Open + subscribe the event WS. Feed every `worker_stream` chunk to
|
|
104
|
-
* {@link push} as it arrives, applying the chunk only when `push`
|
|
105
|
-
* returns `true`.
|
|
106
|
-
* 2. Fetch and paint the snapshot.
|
|
107
|
-
* 3. Call {@link reconcile} with the snapshot's `offset`. Apply the
|
|
108
|
-
* returned chunks in order. From then on, `push` returns `true` for
|
|
109
|
-
* every chunk (live pass-through).
|
|
110
|
-
*
|
|
111
|
-
* Correlation rule: the snapshot reflects every byte with offset `<=`
|
|
112
|
-
* `snapshotOffset`. A buffered chunk carries the cumulative byte offset at
|
|
113
|
-
* its *end*; if that end offset is `<=` the snapshot offset the chunk is
|
|
114
|
-
* already on screen and is dropped, otherwise it is applied.
|
|
115
|
-
*
|
|
116
|
-
* The snapshot offset is retained as a post-reconcile *watermark*: once
|
|
117
|
-
* buffering ends, {@link push} keeps suppressing any live frame whose end
|
|
118
|
-
* offset is `<=` the watermark. This closes a broker-side race — the PTY
|
|
119
|
-
* reader advances `consumed_offset` and the grid *before* the decoded chunk
|
|
120
|
-
* reaches the broadcast queue, so a chunk with `offset <= snapshotOffset`
|
|
121
|
-
* can still arrive *after* the client reconciles. Offsets are cumulative and
|
|
122
|
-
* monotonic, so the watermark drops exactly those already-painted stragglers
|
|
123
|
-
* without touching genuinely new output.
|
|
124
|
-
*/
|
|
125
|
-
export class StreamSyncBuffer {
|
|
126
|
-
buffering = true;
|
|
127
|
-
buffered = [];
|
|
128
|
-
/**
|
|
129
|
-
* Post-reconcile suppression watermark: the snapshot offset the grid had
|
|
130
|
-
* already painted. `undefined` until {@link reconcile} runs with a defined
|
|
131
|
-
* offset (or forever, on brokers without offset support / after
|
|
132
|
-
* {@link flushAll}), in which case no post-reconcile suppression happens.
|
|
133
|
-
*/
|
|
134
|
-
watermark = undefined;
|
|
135
|
-
/**
|
|
136
|
-
* Record a live `worker_stream` chunk. Returns `true` when the caller
|
|
137
|
-
* should apply the chunk immediately, `false` when the chunk must be held
|
|
138
|
-
* or dropped. While buffering, the chunk is retained for {@link reconcile}.
|
|
139
|
-
* After reconcile, a chunk whose end offset is `<=` the snapshot watermark
|
|
140
|
-
* is a late-arriving straggler the snapshot already painted and is
|
|
141
|
-
* suppressed (see the class docstring's race note); everything else passes
|
|
142
|
-
* through live.
|
|
143
|
-
*/
|
|
144
|
-
push(chunk, offset) {
|
|
145
|
-
if (this.buffering) {
|
|
146
|
-
this.buffered.push({ chunk, offset });
|
|
147
|
-
return false;
|
|
148
|
-
}
|
|
149
|
-
// Live pass-through, minus stragglers the snapshot already reflects.
|
|
150
|
-
if (this.watermark !== undefined && offset !== undefined && offset <= this.watermark) {
|
|
151
|
-
return false;
|
|
152
|
-
}
|
|
153
|
-
return true;
|
|
154
|
-
}
|
|
155
|
-
/**
|
|
156
|
-
* Reconcile the buffered chunks against the painted snapshot's offset and
|
|
157
|
-
* return the chunks to apply, in order. Switches to live pass-through and
|
|
158
|
-
* arms the post-reconcile watermark (see {@link push}).
|
|
159
|
-
*
|
|
160
|
-
* When `snapshotOffset` is `undefined` (broker without offset support) all
|
|
161
|
-
* buffered chunks are discarded: they arrived before the snapshot was
|
|
162
|
-
* painted, so dropping them matches the snapshot-authoritative fallback
|
|
163
|
-
* and avoids double-painting what the snapshot already shows. No watermark
|
|
164
|
-
* is armed in that case — there is no offset to compare live frames to.
|
|
165
|
-
*/
|
|
166
|
-
reconcile(snapshotOffset) {
|
|
167
|
-
const out = [];
|
|
168
|
-
if (snapshotOffset !== undefined) {
|
|
169
|
-
for (const item of this.buffered) {
|
|
170
|
-
// Drop chunks the snapshot already reflects; apply the rest. A chunk
|
|
171
|
-
// with no offset (mixed/legacy frame) is applied rather than risk
|
|
172
|
-
// silently dropping live output.
|
|
173
|
-
if (item.offset !== undefined && item.offset <= snapshotOffset)
|
|
174
|
-
continue;
|
|
175
|
-
out.push(item.chunk);
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
this.watermark = snapshotOffset;
|
|
179
|
-
this.buffered.length = 0;
|
|
180
|
-
this.buffering = false;
|
|
181
|
-
return out;
|
|
182
|
-
}
|
|
183
|
-
/**
|
|
184
|
-
* Return every buffered chunk unchanged and switch to live pass-through.
|
|
185
|
-
* Used when no snapshot was painted (transient snapshot failure): there is
|
|
186
|
-
* nothing to reconcile against, so applying everything preserves output
|
|
187
|
-
* rather than dropping the buffered live stream.
|
|
188
|
-
*/
|
|
189
|
-
flushAll() {
|
|
190
|
-
const out = this.buffered.map((item) => item.chunk);
|
|
191
|
-
this.buffered.length = 0;
|
|
192
|
-
this.buffering = false;
|
|
193
|
-
return out;
|
|
194
|
-
}
|
|
195
|
-
/** True while chunks are still being buffered (before reconcile). */
|
|
196
|
-
get isBuffering() {
|
|
197
|
-
return this.buffering;
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
/**
|
|
201
|
-
* Conservative terminal-reset control sequence emitted on detach (see #1247).
|
|
202
|
-
*
|
|
203
|
-
* A drive/view/passthrough session paints the agent's snapshot (which now
|
|
204
|
-
* re-emits terminal modes) and then relays the live stream, either of which can
|
|
205
|
-
* leave the *local* terminal in application-cursor-keys, mouse-reporting,
|
|
206
|
-
* bracketed-paste, or alt-screen mode. Without a reset on detach the user is
|
|
207
|
-
* dropped back to their shell with arrows emitting escape codes, mouse clicks
|
|
208
|
-
* spewing coordinates, or a blank alt screen.
|
|
209
|
-
*
|
|
210
|
-
* The sequence is intentionally direction-explicit and idempotent. Ordering is
|
|
211
|
-
* load-bearing (see #1251): a few of these controls move the cursor, and
|
|
212
|
-
* `\x1b[?1049l` (leave alt screen) *restores* the main-buffer cursor that was
|
|
213
|
-
* saved on alt-screen entry. Anything that homes the cursor must therefore run
|
|
214
|
-
* *before* the alt-screen leave, or it clobbers that restored position and the
|
|
215
|
-
* next shell prompt lands at top-left. Two controls home the cursor:
|
|
216
|
-
*
|
|
217
|
-
* - `\x1b[r` (DECSTBM scroll-region reset) homes the cursor on xterm/DEC-style
|
|
218
|
-
* terminals. The scroll-region margins are shared terminal state, so
|
|
219
|
-
* resetting them while still in the alt buffer heals a stale region and the
|
|
220
|
-
* homing is harmless (the pending `?1049l` restore supersedes it).
|
|
221
|
-
* - `\x1b[?6l` (DECOM origin-mode reset) also moves the cursor to home per the
|
|
222
|
-
* DEC spec, so it belongs in the same pre-leave group.
|
|
223
|
-
*
|
|
224
|
-
* Everything after the alt-screen leave is position-independent (mode flags
|
|
225
|
-
* that never move the cursor): show cursor, application cursor keys off,
|
|
226
|
-
* autowrap on, every mouse-reporting mode off, bracketed paste off, numeric
|
|
227
|
-
* keypad, and a final SGR reset. Only written when stdout is a TTY, consistent
|
|
228
|
-
* with how the sessions gate raw-mode restore and the status line.
|
|
229
|
-
*/
|
|
230
|
-
export const LOCAL_TERMINAL_RESET_SEQUENCE =
|
|
231
|
-
// --- cursor-homing resets: must precede the alt-screen leave/restore ---
|
|
232
|
-
'\x1b[?6l' + // origin mode off (DECOM) — homes the cursor
|
|
233
|
-
'\x1b[r' + // reset scroll region to full screen (DECSTBM) — homes the cursor
|
|
234
|
-
// --- leave alt screen: restores the main-buffer cursor saved on entry ---
|
|
235
|
-
'\x1b[?1049l' + // leave alternate screen buffer
|
|
236
|
-
// --- position-independent mode resets (none move the cursor) ---
|
|
237
|
-
'\x1b[?25h' + // show cursor (DECTCEM)
|
|
238
|
-
'\x1b[?1l' + // application cursor keys off (DECCKM)
|
|
239
|
-
'\x1b[?7h' + // autowrap on (DECAWM)
|
|
240
|
-
'\x1b[?1000l' + // mouse click reporting off
|
|
241
|
-
'\x1b[?1002l' + // mouse button-event (drag) reporting off
|
|
242
|
-
'\x1b[?1003l' + // mouse any-event (motion) reporting off
|
|
243
|
-
'\x1b[?1004l' + // focus in/out reporting off
|
|
244
|
-
'\x1b[?1005l' + // UTF-8 mouse coordinates off
|
|
245
|
-
'\x1b[?1006l' + // SGR mouse coordinates off
|
|
246
|
-
'\x1b[?1007l' + // alternate scroll off
|
|
247
|
-
'\x1b[?2004l' + // bracketed paste off
|
|
248
|
-
'\x1b>' + // keypad normal (DECKPNM)
|
|
249
|
-
'\x1b[0m'; // reset SGR
|
|
250
|
-
/**
|
|
251
|
-
* Emit {@link LOCAL_TERMINAL_RESET_SEQUENCE} to the local terminal on detach,
|
|
252
|
-
* but only when stdout is a TTY. A no-op for piped/redirected stdout so the
|
|
253
|
-
* reset never corrupts a captured log.
|
|
254
|
-
*/
|
|
255
|
-
export function resetLocalTerminalOnDetach(write, isTty) {
|
|
256
|
-
if (!isTty)
|
|
257
|
-
return;
|
|
258
|
-
write(LOCAL_TERMINAL_RESET_SEQUENCE);
|
|
259
|
-
}
|
|
260
|
-
/**
|
|
261
|
-
* Trim the agent name and resolve the broker connection (flag → env →
|
|
262
|
-
* `connection.json`). Writes the appropriate error and returns `null` on
|
|
263
|
-
* either failure so every interactive attach verb rejects empty or
|
|
264
|
-
* unreachable targets consistently.
|
|
265
|
-
*/
|
|
266
|
-
export function prepareAttachTarget(agentName, options, deps) {
|
|
267
|
-
const name = agentName.trim();
|
|
268
|
-
if (!name) {
|
|
269
|
-
deps.error('Error: agent name is required');
|
|
270
|
-
return null;
|
|
271
|
-
}
|
|
272
|
-
const connection = resolveBrokerConnection(options, deps);
|
|
273
|
-
if (!connection) {
|
|
274
|
-
deps.error(describeMissingBrokerConnection(options, deps));
|
|
275
|
-
return null;
|
|
276
|
-
}
|
|
277
|
-
return { name, connection };
|
|
278
|
-
}
|
|
279
|
-
/**
|
|
280
|
-
* Pick the status-line row. Prefers the LOCAL terminal's height (the
|
|
281
|
-
* status line must land where the human is looking) and falls back to
|
|
282
|
-
* the snapshot's PTY rows, then `undefined` so the renderer applies its
|
|
283
|
-
* own default.
|
|
284
|
-
*/
|
|
285
|
-
export function pickInitialTerminalRows(localSize, snapshotRows) {
|
|
286
|
-
if (localSize)
|
|
287
|
-
return localSize.rows;
|
|
288
|
-
if (typeof snapshotRows === 'number' && snapshotRows > 0)
|
|
289
|
-
return snapshotRows;
|
|
290
|
-
return undefined;
|
|
291
|
-
}
|
|
292
|
-
/**
|
|
293
|
-
* Pick the status-line width. Same precedence as
|
|
294
|
-
* {@link pickInitialTerminalRows} — the LOCAL terminal wins, because the
|
|
295
|
-
* status line has to fit the pane the human is looking at, not the agent's
|
|
296
|
-
* PTY.
|
|
297
|
-
*/
|
|
298
|
-
export function pickInitialTerminalCols(localSize, snapshotCols) {
|
|
299
|
-
if (localSize)
|
|
300
|
-
return localSize.cols;
|
|
301
|
-
if (typeof snapshotCols === 'number' && snapshotCols > 0)
|
|
302
|
-
return snapshotCols;
|
|
303
|
-
return undefined;
|
|
304
|
-
}
|
|
305
|
-
/** Width assumed when the local terminal never reported one. */
|
|
306
|
-
export const DEFAULT_STATUS_LINE_COLS = 80;
|
|
307
|
-
/**
|
|
308
|
-
* Clamp a status-line label to the terminal width.
|
|
309
|
-
*
|
|
310
|
-
* The interactive verbs paint their status line at the bottom row inside an
|
|
311
|
-
* `ESC 7` / `ESC 8` (DECSC/DECRC) pair. That is only safe while the text
|
|
312
|
-
* *fits*: a label wider than the pane wraps past the last row, which scrolls
|
|
313
|
-
* the screen. Because the label is painted on the bottom row, every repaint
|
|
314
|
-
* then scrolls again — promoting the previous status line into the scrollback
|
|
315
|
-
* as content and eating one row of the agent's output each time. A narrow
|
|
316
|
-
* pane therefore turns a single status line into a growing stack of them with
|
|
317
|
-
* the agent's TUI shredded behind it. The `drive` label is 87 columns, so this
|
|
318
|
-
* fired on a standard 80-column terminal too; at 66 columns six repaints cost
|
|
319
|
-
* six rows of agent output.
|
|
320
|
-
*
|
|
321
|
-
* Truncation keeps the paint inside one row, so the wrap — and the scroll
|
|
322
|
-
* cascade it triggers — can never happen. Callers painting a terminal row can
|
|
323
|
-
* reserve the final column as well, avoiding the emulator's wrap-pending state.
|
|
324
|
-
* The tail is the part that carries the key hints, so an over-long label is
|
|
325
|
-
* trimmed from the *middle*: the verb and agent name stay readable and the
|
|
326
|
-
* `Ctrl+…` hints survive.
|
|
327
|
-
*
|
|
328
|
-
* Measured in display columns, not UTF-16 code units: an agent name carrying
|
|
329
|
-
* CJK or emoji is double-width, so a code-unit count would pass a label that
|
|
330
|
-
* still wraps — re-arming the exact cascade this prevents. Slicing is done on
|
|
331
|
-
* whole code points so a surrogate pair is never split in half.
|
|
332
|
-
*/
|
|
333
|
-
export function clampStatusLineText(text, cols, reserveFinalColumn = false) {
|
|
334
|
-
const terminalWidth = typeof cols === 'number' && cols > 0 ? Math.floor(cols) : DEFAULT_STATUS_LINE_COLS;
|
|
335
|
-
const width = reserveFinalColumn ? Math.max(terminalWidth - 1, 0) : terminalWidth;
|
|
336
|
-
if (displayWidth(text) <= width)
|
|
337
|
-
return text;
|
|
338
|
-
// Too narrow to say anything useful — a bare head is still better than a
|
|
339
|
-
// wrap, and `…` alone would be meaningless.
|
|
340
|
-
if (width <= 1)
|
|
341
|
-
return width === 1 ? takeColumns(text, 1).text : '';
|
|
342
|
-
const keep = width - 1; // the ellipsis occupies one column
|
|
343
|
-
const tailBudget = Math.floor(keep / 2);
|
|
344
|
-
const headBudget = keep - tailBudget;
|
|
345
|
-
const head = takeColumns(text, headBudget);
|
|
346
|
-
const tail = tailBudget > 0 ? takeColumns(text, tailBudget, 'end') : { text: '' };
|
|
347
|
-
return `${head.text}…${tail.text}`;
|
|
348
|
-
}
|
|
349
|
-
/**
|
|
350
|
-
* Column width of a string, counting East Asian Wide/Fullwidth characters and
|
|
351
|
-
* emoji as two columns and zero-width joiners/combining marks as none. This is
|
|
352
|
-
* the pragmatic subset a status line needs — it is not a full `wcwidth`.
|
|
353
|
-
*/
|
|
354
|
-
function displayWidth(text) {
|
|
355
|
-
let total = 0;
|
|
356
|
-
for (const char of text)
|
|
357
|
-
total += charWidth(char);
|
|
358
|
-
return total;
|
|
359
|
-
}
|
|
360
|
-
/** Codepoints that occupy no column: combining marks, ZWJ, variation selectors. */
|
|
361
|
-
const ZERO_WIDTH_RANGES = [
|
|
362
|
-
[0x0300, 0x036f],
|
|
363
|
-
[0x200d, 0x200d],
|
|
364
|
-
[0xfe00, 0xfe0f],
|
|
365
|
-
];
|
|
366
|
-
/** East Asian Wide / Fullwidth blocks, plus the emoji planes. */
|
|
367
|
-
const DOUBLE_WIDTH_RANGES = [
|
|
368
|
-
[0x1100, 0x115f],
|
|
369
|
-
[0x2e80, 0xa4cf],
|
|
370
|
-
[0xac00, 0xd7a3],
|
|
371
|
-
[0xf900, 0xfaff],
|
|
372
|
-
[0xfe30, 0xfe6f],
|
|
373
|
-
[0xff00, 0xff60],
|
|
374
|
-
[0xffe0, 0xffe6],
|
|
375
|
-
[0x1f300, 0x1faff],
|
|
376
|
-
[0x20000, 0x3fffd],
|
|
377
|
-
];
|
|
378
|
-
function inRanges(code, ranges) {
|
|
379
|
-
return ranges.some(([lo, hi]) => code >= lo && code <= hi);
|
|
380
|
-
}
|
|
381
|
-
function charWidth(char) {
|
|
382
|
-
const code = char.codePointAt(0) ?? 0;
|
|
383
|
-
if (inRanges(code, ZERO_WIDTH_RANGES))
|
|
384
|
-
return 0;
|
|
385
|
-
return inRanges(code, DOUBLE_WIDTH_RANGES) ? 2 : 1;
|
|
386
|
-
}
|
|
387
|
-
/**
|
|
388
|
-
* Take whole code points from `text` until `budget` columns are used, from the
|
|
389
|
-
* start or the `end`. Never splits a surrogate pair, and never overshoots the
|
|
390
|
-
* budget — a double-width character that would exceed it is dropped.
|
|
391
|
-
*/
|
|
392
|
-
function takeColumns(text, budget, from = 'start') {
|
|
393
|
-
const chars = Array.from(text);
|
|
394
|
-
const ordered = from === 'end' ? chars.slice().reverse() : chars;
|
|
395
|
-
const taken = [];
|
|
396
|
-
let used = 0;
|
|
397
|
-
for (const char of ordered) {
|
|
398
|
-
const w = charWidth(char);
|
|
399
|
-
if (used + w > budget)
|
|
400
|
-
break;
|
|
401
|
-
used += w;
|
|
402
|
-
taken.push(char);
|
|
403
|
-
}
|
|
404
|
-
return { text: (from === 'end' ? taken.reverse() : taken).join('') };
|
|
405
|
-
}
|
|
406
|
-
/**
|
|
407
|
-
* Reserve the local terminal's final row for an attach status line.
|
|
408
|
-
*
|
|
409
|
-
* Full-screen CLIs treat every PTY row as application-owned. If the remote PTY
|
|
410
|
-
* is resized to the local terminal's full height and Relay then paints a status
|
|
411
|
-
* line over its final row, both renderers continually overwrite each other.
|
|
412
|
-
* The result is the duplicated status text and torn TUI frames seen in drive
|
|
413
|
-
* and passthrough sessions. Give the child one fewer row and column: the row
|
|
414
|
-
* prevents cursor-addressed overlap, while the spare column prevents terminal
|
|
415
|
-
* autowrap from stepping past the child scroll margin into Relay's row.
|
|
416
|
-
*/
|
|
417
|
-
export function reserveStatusLineRow(localSize) {
|
|
418
|
-
if (!localSize)
|
|
419
|
-
return null;
|
|
420
|
-
// A terminal can report a degenerate size: `script(1)` with no winsize, a
|
|
421
|
-
// minimized window, a size not yet reported after attach, or a teardown race
|
|
422
|
-
// all surface as 0 (or worse) rows/cols while `stdout.isTTY` is still true.
|
|
423
|
-
// Forwarding that verbatim made every attach mode POST `{rows: 0, cols: 0}`
|
|
424
|
-
// and collect `rows and cols must be positive integers` from the broker —
|
|
425
|
-
// harmless but alarming noise that has sent more than one investigation down
|
|
426
|
-
// the wrong path (relay#1597). Treat it the same as "no local size": skip the
|
|
427
|
-
// resize entirely rather than inventing dimensions the operator never had.
|
|
428
|
-
if (localSize.rows < 1 || localSize.cols < 1)
|
|
429
|
-
return null;
|
|
430
|
-
if (localSize.rows < 3 || localSize.cols < 2)
|
|
431
|
-
return localSize;
|
|
432
|
-
return {
|
|
433
|
-
rows: localSize.rows - 1,
|
|
434
|
-
cols: localSize.cols - 1,
|
|
435
|
-
};
|
|
436
|
-
}
|
|
437
|
-
/** Whether a terminal is large enough to dedicate a non-wrapping status row. */
|
|
438
|
-
export function canReserveStatusLine(localSize) {
|
|
439
|
-
return localSize !== null && localSize.rows >= 3 && localSize.cols >= 2;
|
|
440
|
-
}
|
|
441
|
-
/**
|
|
442
|
-
* Constrain local scrolling to the child PTY's rows while preserving the
|
|
443
|
-
* current cursor. DECSTBM otherwise defaults to the physical terminal height,
|
|
444
|
-
* which includes Relay's status row.
|
|
445
|
-
*/
|
|
446
|
-
export function renderChildScrollRegion(rows) {
|
|
447
|
-
// CSI s/u save only the cursor. DEC ESC 7/8 also preserve terminal state in
|
|
448
|
-
// common emulators and would therefore undo the newly installed margins.
|
|
449
|
-
return `\x1b[s\x1b[1;${Math.max(1, Math.floor(rows))}r\x1b[u`;
|
|
450
|
-
}
|
|
451
|
-
/**
|
|
452
|
-
* Keep a status label strictly inside one terminal row.
|
|
453
|
-
*
|
|
454
|
-
* Writing the final column with autowrap enabled advances to the next row and,
|
|
455
|
-
* on the terminal's bottom row, scrolls the entire TUI. Leave one cell unused
|
|
456
|
-
* and conservatively count non-ASCII code points as two cells so even unusual
|
|
457
|
-
* agent names cannot trigger a wrap.
|
|
458
|
-
*/
|
|
459
|
-
function conservativeTerminalCellWidth(character) {
|
|
460
|
-
const codePoint = character.codePointAt(0) ?? 0;
|
|
461
|
-
return codePoint >= 0x20 && codePoint <= 0x7e ? 1 : 2;
|
|
462
|
-
}
|
|
463
|
-
export function fitStatusLineText(text, columns) {
|
|
464
|
-
if (columns === undefined || !Number.isFinite(columns))
|
|
465
|
-
return text;
|
|
466
|
-
const available = Math.max(0, Math.floor(columns) - 1);
|
|
467
|
-
if (available === 0)
|
|
468
|
-
return '';
|
|
469
|
-
let width = 0;
|
|
470
|
-
let result = '';
|
|
471
|
-
let truncated = false;
|
|
472
|
-
for (const character of text) {
|
|
473
|
-
const characterWidth = conservativeTerminalCellWidth(character);
|
|
474
|
-
if (width + characterWidth > available) {
|
|
475
|
-
truncated = true;
|
|
476
|
-
break;
|
|
477
|
-
}
|
|
478
|
-
result += character;
|
|
479
|
-
width += characterWidth;
|
|
480
|
-
}
|
|
481
|
-
if (!truncated)
|
|
482
|
-
return result;
|
|
483
|
-
while (width + 1 > available && result.length > 0) {
|
|
484
|
-
const characters = Array.from(result);
|
|
485
|
-
const removed = characters.pop() ?? '';
|
|
486
|
-
width -= conservativeTerminalCellWidth(removed);
|
|
487
|
-
result = characters.join('');
|
|
488
|
-
}
|
|
489
|
-
return `${result}~`;
|
|
490
|
-
}
|
|
491
|
-
/**
|
|
492
|
-
* Sync the agent's PTY to the driver's local terminal size. tmux /
|
|
493
|
-
* screen / ssh all do this — without it a TUI in the agent renders into
|
|
494
|
-
* the size the PTY was spawned with, ignoring the human's viewport.
|
|
495
|
-
* Best-effort: a failure is annoying but not fatal. Skipped entirely
|
|
496
|
-
* when `localSize` is `null` (stdout isn't a TTY).
|
|
497
|
-
*/
|
|
498
|
-
export async function syncInitialPtySize(connection, name, localSize, verb, deps, options) {
|
|
499
|
-
if (!localSize)
|
|
500
|
-
return false;
|
|
501
|
-
try {
|
|
502
|
-
const result = await createBrokerClient(connection, deps.fetch).resizePty(name, localSize.rows, localSize.cols, options);
|
|
503
|
-
if (result.applied === false) {
|
|
504
|
-
deps.log(`[${verb}] broker did not apply the reserved PTY size; using status repaint fallback`);
|
|
505
|
-
return false;
|
|
506
|
-
}
|
|
507
|
-
return true;
|
|
508
|
-
}
|
|
509
|
-
catch (err) {
|
|
510
|
-
const failure = mapBrokerSdkFailure(err);
|
|
511
|
-
deps.log(`[${verb}] could not sync agent PTY size to local terminal (${failure.message ?? 'unknown'}); continuing`);
|
|
512
|
-
return false;
|
|
513
|
-
}
|
|
514
|
-
}
|
|
515
|
-
/**
|
|
516
|
-
* Read the worker's prior inbound delivery mode and flip it to
|
|
517
|
-
* `targetMode`. Returns the previous mode on success so the caller can
|
|
518
|
-
* restore it on detach; returns `null` (and writes an error) when the
|
|
519
|
-
* request fails or the broker reports that the requested transition did not
|
|
520
|
-
* complete, so the caller bails before touching the terminal.
|
|
521
|
-
*
|
|
522
|
-
* Non-404 errors are surfaced as `Error: could not ${actionPhrase}:
|
|
523
|
-
* ${message}` so callers pass verb-appropriate wording (e.g. "switch to
|
|
524
|
-
* manual_flush mode" or "ensure passthrough session"). 404s get a
|
|
525
|
-
* uniform "no agent named X" message.
|
|
526
|
-
*/
|
|
527
|
-
export async function switchInboundDeliveryModeOrAbort(connection, name, targetMode, actionPhrase, deps) {
|
|
528
|
-
let previousMode = null;
|
|
529
|
-
try {
|
|
530
|
-
previousMode = await createBrokerClient(connection, deps.fetch).getInboundDeliveryMode(name);
|
|
531
|
-
}
|
|
532
|
-
catch {
|
|
533
|
-
// Best-effort — fall through with null; the caller restores to
|
|
534
|
-
// `auto_inject` in that case so the queue can't grow indefinitely.
|
|
535
|
-
}
|
|
536
|
-
try {
|
|
537
|
-
const result = await createBrokerClient(connection, deps.fetch).setInboundDeliveryMode(name, targetMode);
|
|
538
|
-
// A manual_flush → auto_inject transition can fail partway through when
|
|
539
|
-
// draining a parked message into the harness fails. The broker deliberately
|
|
540
|
-
// keeps and reports manual_flush in that case even though the PUT itself
|
|
541
|
-
// succeeded. Starting an attach session as if the target mode landed would
|
|
542
|
-
// render false state and make its first guarded toggle a no-op.
|
|
543
|
-
if (result.mode !== targetMode) {
|
|
544
|
-
deps.error(`Error: could not ${actionPhrase}: broker remained in ${result.mode} mode while draining queued messages`);
|
|
545
|
-
return null;
|
|
546
|
-
}
|
|
547
|
-
return { previousMode, sessionRevision: result.revision };
|
|
548
|
-
}
|
|
549
|
-
catch (err) {
|
|
550
|
-
const failure = mapBrokerSdkFailure(err);
|
|
551
|
-
if (failure.status === 404) {
|
|
552
|
-
let hint = null;
|
|
553
|
-
if (deps.fleetHint) {
|
|
554
|
-
try {
|
|
555
|
-
hint = await deps.fleetHint(name);
|
|
556
|
-
}
|
|
557
|
-
catch {
|
|
558
|
-
// Best-effort lookup — preserve the existing not-found message.
|
|
559
|
-
}
|
|
560
|
-
}
|
|
561
|
-
if (hint) {
|
|
562
|
-
const safeArg = `'${name.replace(/'/g, "'\\''")}'`;
|
|
563
|
-
deps.error(`Error: agent '${name}' is ${hint}; cross-node attach is not yet supported` +
|
|
564
|
-
` — run \`agent-relay node agent attach ${safeArg}\` on that machine`);
|
|
565
|
-
}
|
|
566
|
-
else {
|
|
567
|
-
deps.error(`Error: no agent named '${name}'`);
|
|
568
|
-
}
|
|
569
|
-
}
|
|
570
|
-
else {
|
|
571
|
-
deps.error(`Error: could not ${actionPhrase}: ${failure.message ?? 'unknown error'}`);
|
|
572
|
-
}
|
|
573
|
-
return null;
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
/**
|
|
577
|
-
* Upper bound (ms) on the best-effort detach teardown — resize-ownership
|
|
578
|
-
* release and inbound-delivery-mode restore. Both are HTTP round-trips to the
|
|
579
|
-
* broker that can stall if the broker is down; the terminal must still exit
|
|
580
|
-
* promptly, so `finish()` resolves the exit code once these settle *or* this
|
|
581
|
-
* deadline elapses, whichever comes first. The broker's idle-takeover net
|
|
582
|
-
* still frees any ownership left behind.
|
|
583
|
-
*/
|
|
584
|
-
export const DETACH_CLEANUP_DEADLINE_MS = 2000;
|
|
585
|
-
/**
|
|
586
|
-
* Best-effort restore of a worker's inbound delivery mode on detach.
|
|
587
|
-
*
|
|
588
|
-
* Two hazards this guards against (see #1247):
|
|
589
|
-
*
|
|
590
|
-
* 1. Concurrent-change race — a second session attaching while this one is
|
|
591
|
-
* active would read *this* session's mode as the "previous" one, so blindly
|
|
592
|
-
* writing `previousMode` back on detach can clobber a change another
|
|
593
|
-
* session/CLI made in the meantime. We restore via the broker's atomic
|
|
594
|
-
* compare-and-set (`expectedMode: sessionMode`): the broker applies
|
|
595
|
-
* `previousMode` only if the worker's current mode still equals what *this*
|
|
596
|
-
* session set, and no-ops (`matched: false`) otherwise. This removes the
|
|
597
|
-
* read-then-set TOCTOU a client-side re-read still had (a change landing
|
|
598
|
-
* between the read and the restore PUT).
|
|
599
|
-
* 2. Failed initial read — when the pre-attach mode was never learned
|
|
600
|
-
* (`previousMode === null`), forcing a default (`auto_inject`) would
|
|
601
|
-
* silently cancel an explicit `agent message hold`. In that case we leave
|
|
602
|
-
* the mode untouched and warn.
|
|
603
|
-
*
|
|
604
|
-
* The broker's monotonic mode revision closes ABA races where another session
|
|
605
|
-
* changes the mode away and back to `sessionMode` before this restore.
|
|
606
|
-
*/
|
|
607
|
-
export async function restoreInboundDeliveryModeOnDetach(connection, name, previousMode, sessionMode, sessionRevision, verb, deps) {
|
|
608
|
-
if (previousMode === null) {
|
|
609
|
-
deps.log(`[${verb}] could not restore '${name}' inbound delivery mode (pre-attach mode was unknown); leaving it unchanged`);
|
|
610
|
-
return;
|
|
611
|
-
}
|
|
612
|
-
if (sessionRevision === null) {
|
|
613
|
-
deps.log(`[${verb}] could not safely restore '${name}' inbound delivery mode (broker did not report a mode revision); leaving it unchanged`);
|
|
614
|
-
return;
|
|
615
|
-
}
|
|
616
|
-
try {
|
|
617
|
-
// Atomic compare-and-set: restore only if both the mode and its monotonic
|
|
618
|
-
// revision still match this session's write. If another session changed it
|
|
619
|
-
// (including an ABA away-and-back), the broker no-ops.
|
|
620
|
-
const result = await createBrokerClient(connection, deps.fetch).setInboundDeliveryMode(name, previousMode, {
|
|
621
|
-
expectedMode: sessionMode,
|
|
622
|
-
expectedRevision: sessionRevision,
|
|
623
|
-
});
|
|
624
|
-
if (!result.matched) {
|
|
625
|
-
deps.log(`[${verb}] did not restore '${name}' inbound delivery mode because another session changed it; leaving it unchanged`);
|
|
626
|
-
}
|
|
627
|
-
}
|
|
628
|
-
catch {
|
|
629
|
-
// best-effort
|
|
630
|
-
}
|
|
631
|
-
}
|
|
632
|
-
/**
|
|
633
|
-
* Streaming scanner that tracks whether a byte stream currently *ends* inside
|
|
634
|
-
* an incomplete ANSI escape sequence (ESC, CSI, OSC, or DCS/SOS/PM/APC string).
|
|
635
|
-
*
|
|
636
|
-
* The attach status line wraps its repaint in cursor save/restore controls;
|
|
637
|
-
* splicing that in while the agent is mid-transmission of its own CSI sequence
|
|
638
|
-
* corrupts the agent's output. Feeding every server chunk through this scanner
|
|
639
|
-
* lets the status painter hold its repaint until the stream is back at a
|
|
640
|
-
* sequence boundary. State persists across chunks (a sequence may span several
|
|
641
|
-
* `worker_stream` frames).
|
|
642
|
-
*
|
|
643
|
-
* Only ASCII control bytes drive the state machine; multi-byte UTF-8 payload
|
|
644
|
-
* bytes are printable in the ground state and never appear inside a CSI/escape
|
|
645
|
-
* sequence, so scanning UTF-16 code units is safe here.
|
|
646
|
-
*/
|
|
647
|
-
export class AnsiBoundaryScanner {
|
|
648
|
-
state = 'ground';
|
|
649
|
-
push(chunk) {
|
|
650
|
-
for (let i = 0; i < chunk.length; i += 1) {
|
|
651
|
-
this.step(chunk.charCodeAt(i));
|
|
652
|
-
}
|
|
653
|
-
}
|
|
654
|
-
reset() {
|
|
655
|
-
this.state = 'ground';
|
|
656
|
-
}
|
|
657
|
-
/** True when the stream ends at a safe boundary (not mid-sequence). */
|
|
658
|
-
get atBoundary() {
|
|
659
|
-
return this.state === 'ground';
|
|
660
|
-
}
|
|
661
|
-
step(c) {
|
|
662
|
-
switch (this.state) {
|
|
663
|
-
case 'ground':
|
|
664
|
-
if (c === 0x1b)
|
|
665
|
-
this.state = 'esc';
|
|
666
|
-
else if (c === 0x9b)
|
|
667
|
-
this.state = 'csi';
|
|
668
|
-
else if (c === 0x9d)
|
|
669
|
-
this.state = 'osc';
|
|
670
|
-
else if (c === 0x90 || c === 0x98 || c === 0x9e || c === 0x9f)
|
|
671
|
-
this.state = 'str';
|
|
672
|
-
return;
|
|
673
|
-
case 'esc':
|
|
674
|
-
if (c === 0x5b)
|
|
675
|
-
this.state = 'csi'; // ESC [
|
|
676
|
-
else if (c === 0x5d)
|
|
677
|
-
this.state = 'osc'; // ESC ]
|
|
678
|
-
else if (c === 0x50 || c === 0x58 || c === 0x5e || c === 0x5f)
|
|
679
|
-
this.state = 'str'; // DCS / SOS / PM / APC
|
|
680
|
-
else
|
|
681
|
-
this.state = 'ground'; // 2-byte escape (ESC 7, ESC 8, ESC c, …)
|
|
682
|
-
return;
|
|
683
|
-
case 'csi':
|
|
684
|
-
if (c === 0x18 || c === 0x1a)
|
|
685
|
-
this.state = 'ground'; // CAN / SUB cancel the sequence
|
|
686
|
-
else if (c === 0x1b)
|
|
687
|
-
this.state = 'esc'; // stray ESC restarts
|
|
688
|
-
else if (c >= 0x40 && c <= 0x7e)
|
|
689
|
-
this.state = 'ground'; // final byte ends the CSI
|
|
690
|
-
return;
|
|
691
|
-
case 'osc':
|
|
692
|
-
if (c === 0x07 || c === 0x9c || c === 0x18 || c === 0x1a)
|
|
693
|
-
this.state = 'ground'; // BEL terminator
|
|
694
|
-
else if (c === 0x1b)
|
|
695
|
-
this.state = 'osc_esc'; // possible ST (ESC \)
|
|
696
|
-
return;
|
|
697
|
-
case 'osc_esc':
|
|
698
|
-
this.state =
|
|
699
|
-
c === 0x5c || c === 0x9c || c === 0x18 || c === 0x1a ? 'ground' : c === 0x1b ? 'osc_esc' : 'osc';
|
|
700
|
-
return;
|
|
701
|
-
case 'str':
|
|
702
|
-
if (c === 0x9c || c === 0x18 || c === 0x1a)
|
|
703
|
-
this.state = 'ground';
|
|
704
|
-
else if (c === 0x1b)
|
|
705
|
-
this.state = 'str_esc';
|
|
706
|
-
return;
|
|
707
|
-
case 'str_esc':
|
|
708
|
-
this.state =
|
|
709
|
-
c === 0x5c || c === 0x9c || c === 0x18 || c === 0x1a ? 'ground' : c === 0x1b ? 'str_esc' : 'str';
|
|
710
|
-
return;
|
|
711
|
-
}
|
|
712
|
-
}
|
|
713
|
-
}
|
|
714
|
-
/**
|
|
715
|
-
* Detect terminal controls that can erase or replace Relay's reserved status
|
|
716
|
-
* row even though the child PTY itself is one row shorter.
|
|
717
|
-
*
|
|
718
|
-
* Cursor-addressed TUI drawing stays inside the child grid, but erase-display,
|
|
719
|
-
* terminal reset, and alternate-screen switches act on the local terminal as a
|
|
720
|
-
* whole. Attach clients reinstall their child scroll region after those
|
|
721
|
-
* operations; the status controller separately repaints at a safe ANSI
|
|
722
|
-
* boundary. A short carry handles controls split across WS frames.
|
|
723
|
-
*/
|
|
724
|
-
export class StatusLineInvalidationScanner {
|
|
725
|
-
carry = '';
|
|
726
|
-
push(chunk) {
|
|
727
|
-
const input = this.carry + chunk;
|
|
728
|
-
const esc = String.fromCharCode(0x1b);
|
|
729
|
-
const privateModes = new RegExp(`${esc}\\[\\?([0-9;]+)[hl]`, 'g');
|
|
730
|
-
let invalidatesDisplay = false;
|
|
731
|
-
let privateMatch;
|
|
732
|
-
while ((privateMatch = privateModes.exec(input)) !== null) {
|
|
733
|
-
if (privateMatch[1].split(';').some((mode) => ['47', '1047', '1049'].includes(mode))) {
|
|
734
|
-
invalidatesDisplay = true;
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
// Retain only an incomplete candidate control. Keeping arbitrary completed
|
|
738
|
-
// output would rediscover the same erase on later chunks and recreate the
|
|
739
|
-
// repaint storm this scanner exists to prevent.
|
|
740
|
-
const lastEscape = input.lastIndexOf(esc);
|
|
741
|
-
const suffix = lastEscape >= 0 ? input.slice(lastEscape) : '';
|
|
742
|
-
const incompleteCsi = suffix.startsWith(`${esc}[`) && /^[?0-9;]*$/.test(suffix.slice(2));
|
|
743
|
-
this.carry = suffix === esc || incompleteCsi ? suffix : '';
|
|
744
|
-
return (
|
|
745
|
-
// ED 0/default clears from the cursor through the reserved final row;
|
|
746
|
-
// ED 2 clears the full display.
|
|
747
|
-
input.includes(`${esc}[J`) ||
|
|
748
|
-
input.includes(`${esc}[0J`) ||
|
|
749
|
-
input.includes(`${esc}[2J`) ||
|
|
750
|
-
// Alternate-screen changes replace the entire visible buffer.
|
|
751
|
-
invalidatesDisplay ||
|
|
752
|
-
// RIS resets the terminal and clears the active display.
|
|
753
|
-
input.includes(`${esc}c`));
|
|
754
|
-
}
|
|
755
|
-
}
|
|
756
|
-
/** Track the child application's active DECSTBM margins across streamed ANSI. */
|
|
757
|
-
export class TerminalScrollRegionTracker {
|
|
758
|
-
parserState = 'ground';
|
|
759
|
-
csiParams = '';
|
|
760
|
-
csiSupported = true;
|
|
761
|
-
stringAllowsBel = false;
|
|
762
|
-
rows;
|
|
763
|
-
top = 1;
|
|
764
|
-
bottom;
|
|
765
|
-
originMode = false;
|
|
766
|
-
alternateActive = false;
|
|
767
|
-
primaryRegion;
|
|
768
|
-
alternateRegion;
|
|
769
|
-
constructor(rows) {
|
|
770
|
-
this.rows = Math.max(1, Math.floor(rows));
|
|
771
|
-
this.bottom = this.rows;
|
|
772
|
-
this.primaryRegion = { top: 1, bottom: this.rows };
|
|
773
|
-
this.alternateRegion = { top: 1, bottom: this.rows };
|
|
774
|
-
}
|
|
775
|
-
setRows(rows) {
|
|
776
|
-
this.rows = Math.max(1, Math.floor(rows));
|
|
777
|
-
this.top = 1;
|
|
778
|
-
this.bottom = this.rows;
|
|
779
|
-
this.primaryRegion = { top: 1, bottom: this.rows };
|
|
780
|
-
this.alternateRegion = { top: 1, bottom: this.rows };
|
|
781
|
-
}
|
|
782
|
-
push(chunk) {
|
|
783
|
-
for (const character of chunk)
|
|
784
|
-
this.consumeCharacter(character);
|
|
785
|
-
}
|
|
786
|
-
get region() {
|
|
787
|
-
return { top: this.top, bottom: this.bottom };
|
|
788
|
-
}
|
|
789
|
-
get isOriginMode() {
|
|
790
|
-
return this.originMode;
|
|
791
|
-
}
|
|
792
|
-
consumeCharacter(character) {
|
|
793
|
-
switch (this.parserState) {
|
|
794
|
-
case 'ground':
|
|
795
|
-
this.consumeGround(character);
|
|
796
|
-
break;
|
|
797
|
-
case 'escape':
|
|
798
|
-
this.consumeEscape(character);
|
|
799
|
-
break;
|
|
800
|
-
case 'csi':
|
|
801
|
-
this.consumeCsi(character);
|
|
802
|
-
break;
|
|
803
|
-
case 'string':
|
|
804
|
-
this.consumeString(character);
|
|
805
|
-
break;
|
|
806
|
-
case 'string_escape':
|
|
807
|
-
this.consumeStringEscape(character);
|
|
808
|
-
break;
|
|
809
|
-
}
|
|
810
|
-
}
|
|
811
|
-
consumeString(character) {
|
|
812
|
-
if (character === '\x1b') {
|
|
813
|
-
this.parserState = 'string_escape';
|
|
814
|
-
return;
|
|
815
|
-
}
|
|
816
|
-
if (character === '\x9c' ||
|
|
817
|
-
character === '\x18' ||
|
|
818
|
-
character === '\x1a' ||
|
|
819
|
-
(this.stringAllowsBel && character === '\x07')) {
|
|
820
|
-
this.parserState = 'ground';
|
|
821
|
-
}
|
|
822
|
-
}
|
|
823
|
-
consumeStringEscape(character) {
|
|
824
|
-
if (character === '\\' || character === '\x9c' || character === '\x18' || character === '\x1a') {
|
|
825
|
-
this.parserState = 'ground';
|
|
826
|
-
}
|
|
827
|
-
else {
|
|
828
|
-
this.parserState = character === '\x1b' ? 'string_escape' : 'string';
|
|
829
|
-
}
|
|
830
|
-
}
|
|
831
|
-
consumeGround(character) {
|
|
832
|
-
if (character === '\x1b')
|
|
833
|
-
this.parserState = 'escape';
|
|
834
|
-
else if (character === '\x9b')
|
|
835
|
-
this.beginCsi();
|
|
836
|
-
else if (['\x90', '\x98', '\x9d', '\x9e', '\x9f'].includes(character)) {
|
|
837
|
-
this.beginString(character === '\x9d');
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
consumeEscape(character) {
|
|
841
|
-
if (character === '[')
|
|
842
|
-
this.beginCsi();
|
|
843
|
-
else if (['P', 'X', ']', '^', '_'].includes(character))
|
|
844
|
-
this.beginString(character === ']');
|
|
845
|
-
else {
|
|
846
|
-
if (character === 'c')
|
|
847
|
-
this.resetTrackedState();
|
|
848
|
-
this.parserState = character === '\x1b' ? 'escape' : 'ground';
|
|
849
|
-
}
|
|
850
|
-
}
|
|
851
|
-
beginCsi() {
|
|
852
|
-
this.parserState = 'csi';
|
|
853
|
-
this.csiParams = '';
|
|
854
|
-
this.csiSupported = true;
|
|
855
|
-
}
|
|
856
|
-
beginString(allowsBel) {
|
|
857
|
-
this.parserState = 'string';
|
|
858
|
-
this.stringAllowsBel = allowsBel;
|
|
859
|
-
}
|
|
860
|
-
consumeCsi(character) {
|
|
861
|
-
if (character === '\x18' || character === '\x1a') {
|
|
862
|
-
this.parserState = 'ground';
|
|
863
|
-
return;
|
|
864
|
-
}
|
|
865
|
-
if (character === '\x1b') {
|
|
866
|
-
this.parserState = 'escape';
|
|
867
|
-
return;
|
|
868
|
-
}
|
|
869
|
-
const code = character.codePointAt(0) ?? 0;
|
|
870
|
-
if (code >= 0x30 && code <= 0x3f) {
|
|
871
|
-
this.csiParams += character;
|
|
872
|
-
return;
|
|
873
|
-
}
|
|
874
|
-
if (code >= 0x20 && code <= 0x2f) {
|
|
875
|
-
this.csiSupported = false;
|
|
876
|
-
return;
|
|
877
|
-
}
|
|
878
|
-
if (code >= 0x40 && code <= 0x7e) {
|
|
879
|
-
if (this.csiSupported)
|
|
880
|
-
this.applyCsi(this.csiParams, character);
|
|
881
|
-
this.parserState = 'ground';
|
|
882
|
-
}
|
|
883
|
-
}
|
|
884
|
-
applyCsi(params, final) {
|
|
885
|
-
if ((final === 'h' || final === 'l') && params.startsWith('?')) {
|
|
886
|
-
this.applyPrivateModes(params.slice(1).split(';'), final === 'h');
|
|
887
|
-
return;
|
|
888
|
-
}
|
|
889
|
-
if (final !== 'r' || params.startsWith('?'))
|
|
890
|
-
return;
|
|
891
|
-
const [topRaw = '', bottomRaw = ''] = params.split(';');
|
|
892
|
-
const parsedTop = topRaw === '' ? 0 : Number.parseInt(topRaw, 10);
|
|
893
|
-
const parsedBottom = bottomRaw === '' ? 0 : Number.parseInt(bottomRaw, 10);
|
|
894
|
-
const top = parsedTop === 0 ? 1 : parsedTop;
|
|
895
|
-
const bottom = parsedBottom === 0 ? this.rows : parsedBottom;
|
|
896
|
-
if (Number.isFinite(top) && Number.isFinite(bottom) && top >= 1 && bottom > top) {
|
|
897
|
-
const clampedTop = Math.min(top, this.rows);
|
|
898
|
-
const clampedBottom = Math.min(bottom, this.rows);
|
|
899
|
-
if (clampedBottom > clampedTop) {
|
|
900
|
-
this.top = clampedTop;
|
|
901
|
-
this.bottom = clampedBottom;
|
|
902
|
-
}
|
|
903
|
-
}
|
|
904
|
-
}
|
|
905
|
-
applyPrivateModes(modes, enabled) {
|
|
906
|
-
if (modes.includes('6'))
|
|
907
|
-
this.originMode = enabled;
|
|
908
|
-
if (modes.some((mode) => ['47', '1047', '1049'].includes(mode))) {
|
|
909
|
-
this.switchScreenBuffer(enabled, enabled);
|
|
910
|
-
}
|
|
911
|
-
}
|
|
912
|
-
resetTrackedState() {
|
|
913
|
-
this.top = 1;
|
|
914
|
-
this.bottom = this.rows;
|
|
915
|
-
this.originMode = false;
|
|
916
|
-
this.alternateActive = false;
|
|
917
|
-
this.primaryRegion = { top: 1, bottom: this.rows };
|
|
918
|
-
this.alternateRegion = { top: 1, bottom: this.rows };
|
|
919
|
-
}
|
|
920
|
-
switchScreenBuffer(enterAlternate, resetAlternate) {
|
|
921
|
-
if (enterAlternate === this.alternateActive)
|
|
922
|
-
return;
|
|
923
|
-
if (resetAlternate) {
|
|
924
|
-
this.alternateRegion = { top: 1, bottom: this.rows };
|
|
925
|
-
}
|
|
926
|
-
if (this.alternateActive) {
|
|
927
|
-
this.alternateRegion = { top: this.top, bottom: this.bottom };
|
|
928
|
-
}
|
|
929
|
-
else {
|
|
930
|
-
this.primaryRegion = { top: this.top, bottom: this.bottom };
|
|
931
|
-
}
|
|
932
|
-
this.alternateActive = enterAlternate;
|
|
933
|
-
const region = enterAlternate ? this.alternateRegion : this.primaryRegion;
|
|
934
|
-
this.top = region.top;
|
|
935
|
-
this.bottom = region.bottom;
|
|
936
|
-
}
|
|
937
|
-
}
|
|
938
|
-
/**
|
|
939
|
-
* Coordinates status-line repaints for the interactive attach clients.
|
|
940
|
-
*
|
|
941
|
-
* Correctness properties (see #1247):
|
|
942
|
-
* - **Non-TTY skip** — when `enabled` is false, nothing is ever written.
|
|
943
|
-
* - **Boundary-hold** — a repaint is deferred while the observed output ends
|
|
944
|
-
* mid ANSI escape sequence, so the status line never splices into a
|
|
945
|
-
* half-transmitted CSI. It paints only after a later chunk returns the
|
|
946
|
-
* stream to a real boundary.
|
|
947
|
-
* - **Coalescing** — repaints are rate-limited to at most one per
|
|
948
|
-
* `coalesceMs`, shrinking the window in which our save/restore-cursor wrap
|
|
949
|
-
* can clobber the agent's own pending DECSC.
|
|
950
|
-
* - **Teardown-safe** — after {@link dispose} no further writes happen.
|
|
951
|
-
*
|
|
952
|
-
* Residual risk (documented): ESC 7/ESC 8 (and CSI s/u) share a single
|
|
953
|
-
* saved-cursor slot on many terminals, so a repaint landing between the
|
|
954
|
-
* agent's DECSC and DECRC can still restore to the wrong spot. Boundary-hold +
|
|
955
|
-
* coalescing shrink but do not eliminate that window.
|
|
956
|
-
*/
|
|
957
|
-
export class StatusLineController {
|
|
958
|
-
opts;
|
|
959
|
-
scanner = new AnsiBoundaryScanner();
|
|
960
|
-
timer = null;
|
|
961
|
-
wantPaint = false;
|
|
962
|
-
lastPaintAt = Number.NEGATIVE_INFINITY;
|
|
963
|
-
disposed = false;
|
|
964
|
-
constructor(opts) {
|
|
965
|
-
this.opts = opts;
|
|
966
|
-
}
|
|
967
|
-
isEnabled() {
|
|
968
|
-
return typeof this.opts.enabled === 'function' ? this.opts.enabled() : this.opts.enabled;
|
|
969
|
-
}
|
|
970
|
-
/** Record server output for boundary tracking; flush a held repaint if the
|
|
971
|
-
* stream is now back at a sequence boundary. */
|
|
972
|
-
observeOutput(chunk) {
|
|
973
|
-
if (this.disposed)
|
|
974
|
-
return;
|
|
975
|
-
this.scanner.push(chunk);
|
|
976
|
-
if (!this.isEnabled()) {
|
|
977
|
-
this.wantPaint = false;
|
|
978
|
-
this.clearTimer();
|
|
979
|
-
return;
|
|
980
|
-
}
|
|
981
|
-
if (this.wantPaint)
|
|
982
|
-
this.flush();
|
|
983
|
-
}
|
|
984
|
-
/** Request a repaint (coalesced + boundary-held). */
|
|
985
|
-
request() {
|
|
986
|
-
if (this.disposed || !this.isEnabled())
|
|
987
|
-
return;
|
|
988
|
-
this.wantPaint = true;
|
|
989
|
-
this.flush();
|
|
990
|
-
}
|
|
991
|
-
/** Stop all painting and cancel any pending timer. */
|
|
992
|
-
dispose() {
|
|
993
|
-
this.disposed = true;
|
|
994
|
-
this.wantPaint = false;
|
|
995
|
-
this.clearTimer();
|
|
996
|
-
}
|
|
997
|
-
now() {
|
|
998
|
-
return (this.opts.now ?? Date.now)();
|
|
999
|
-
}
|
|
1000
|
-
flush() {
|
|
1001
|
-
if (this.disposed || !this.wantPaint || !this.isEnabled())
|
|
1002
|
-
return;
|
|
1003
|
-
if (!this.scanner.atBoundary) {
|
|
1004
|
-
return;
|
|
1005
|
-
}
|
|
1006
|
-
const elapsed = this.now() - this.lastPaintAt;
|
|
1007
|
-
if (elapsed >= this.opts.coalesceMs) {
|
|
1008
|
-
this.paintNow();
|
|
1009
|
-
}
|
|
1010
|
-
else {
|
|
1011
|
-
this.arm(this.opts.coalesceMs - elapsed);
|
|
1012
|
-
}
|
|
1013
|
-
}
|
|
1014
|
-
paintNow() {
|
|
1015
|
-
this.clearTimer();
|
|
1016
|
-
if (!this.isEnabled()) {
|
|
1017
|
-
this.wantPaint = false;
|
|
1018
|
-
return;
|
|
1019
|
-
}
|
|
1020
|
-
this.wantPaint = false;
|
|
1021
|
-
this.lastPaintAt = this.now();
|
|
1022
|
-
this.opts.write(this.opts.render());
|
|
1023
|
-
}
|
|
1024
|
-
arm(ms) {
|
|
1025
|
-
if (this.timer)
|
|
1026
|
-
return;
|
|
1027
|
-
const set = this.opts.setTimer ??
|
|
1028
|
-
((fn, delay) => {
|
|
1029
|
-
const t = setTimeout(fn, delay);
|
|
1030
|
-
t.unref?.();
|
|
1031
|
-
return t;
|
|
1032
|
-
});
|
|
1033
|
-
this.timer = set(() => {
|
|
1034
|
-
this.timer = null;
|
|
1035
|
-
if (this.disposed || !this.wantPaint || !this.isEnabled()) {
|
|
1036
|
-
this.wantPaint = false;
|
|
1037
|
-
return;
|
|
1038
|
-
}
|
|
1039
|
-
this.flush();
|
|
1040
|
-
}, ms);
|
|
1041
|
-
}
|
|
1042
|
-
clearTimer() {
|
|
1043
|
-
if (this.timer) {
|
|
1044
|
-
(this.opts.clearTimer ?? clearTimeout)(this.timer);
|
|
1045
|
-
this.timer = null;
|
|
1046
|
-
}
|
|
1047
|
-
}
|
|
1048
|
-
}
|
|
1049
|
-
/**
|
|
1050
|
-
* Default stdout writer that respects backpressure (see #1247, item 7).
|
|
1051
|
-
*
|
|
1052
|
-
* When the underlying stream reports saturation (`write()` returns false) we
|
|
1053
|
-
* hold subsequent chunks in a bounded in-memory queue and flush them on
|
|
1054
|
-
* `'drain'`, rather than letting Node's stdout buffer grow without limit under
|
|
1055
|
-
* a fast agent + slow terminal.
|
|
1056
|
-
*
|
|
1057
|
-
* FIFO is preserved even when our own queue reaches `maxQueuedBytes`: rather
|
|
1058
|
-
* than writing the overflow chunk straight through (which would jump it ahead
|
|
1059
|
-
* of older queued chunks and reorder/split the PTY byte stream), we first flush
|
|
1060
|
-
* the entire local queue into stdout's internal buffer — `stdout.write` buffers
|
|
1061
|
-
* internally when saturated, so ignoring its return value here is safe — then
|
|
1062
|
-
* write the new chunk last. Bounded extra buffering, never dropped or reordered
|
|
1063
|
-
* output. Documented residual risk: under sustained overload Node's internal
|
|
1064
|
-
* stdout buffer can still grow.
|
|
1065
|
-
*/
|
|
1066
|
-
export function createBackpressureAwareWriter(stdout, maxQueuedBytes = 4 * 1024 * 1024) {
|
|
1067
|
-
let paused = false;
|
|
1068
|
-
let disposed = false;
|
|
1069
|
-
let queue = [];
|
|
1070
|
-
let queuedBytes = 0;
|
|
1071
|
-
const flushQueue = () => {
|
|
1072
|
-
if (disposed)
|
|
1073
|
-
return;
|
|
1074
|
-
while (queue.length > 0) {
|
|
1075
|
-
const next = queue.shift();
|
|
1076
|
-
queuedBytes -= Buffer.byteLength(next, 'utf8');
|
|
1077
|
-
if (!stdout.write(next)) {
|
|
1078
|
-
stdout.once('drain', flushQueue);
|
|
1079
|
-
return;
|
|
1080
|
-
}
|
|
1081
|
-
}
|
|
1082
|
-
paused = false;
|
|
1083
|
-
};
|
|
1084
|
-
const write = (chunk) => {
|
|
1085
|
-
if (disposed)
|
|
1086
|
-
return;
|
|
1087
|
-
if (paused) {
|
|
1088
|
-
const bytes = Buffer.byteLength(chunk, 'utf8');
|
|
1089
|
-
if (queuedBytes + bytes <= maxQueuedBytes) {
|
|
1090
|
-
queue.push(chunk);
|
|
1091
|
-
queuedBytes += bytes;
|
|
1092
|
-
return;
|
|
1093
|
-
}
|
|
1094
|
-
// Queue cap hit. Preserve FIFO: flush the whole local queue into
|
|
1095
|
-
// stdout's internal buffer first (write buffers internally when
|
|
1096
|
-
// saturated, so the return value is intentionally ignored), then write
|
|
1097
|
-
// the new chunk last so it never jumps ahead of older output.
|
|
1098
|
-
for (const queued of queue)
|
|
1099
|
-
stdout.write(queued);
|
|
1100
|
-
queue = [];
|
|
1101
|
-
queuedBytes = 0;
|
|
1102
|
-
stdout.write(chunk);
|
|
1103
|
-
return;
|
|
1104
|
-
}
|
|
1105
|
-
if (!stdout.write(chunk)) {
|
|
1106
|
-
paused = true;
|
|
1107
|
-
stdout.once('drain', flushQueue);
|
|
1108
|
-
}
|
|
1109
|
-
};
|
|
1110
|
-
const dispose = () => {
|
|
1111
|
-
if (disposed)
|
|
1112
|
-
return;
|
|
1113
|
-
disposed = true;
|
|
1114
|
-
queue = [];
|
|
1115
|
-
queuedBytes = 0;
|
|
1116
|
-
paused = false;
|
|
1117
|
-
const off = stdout.off ?? stdout.removeListener;
|
|
1118
|
-
off?.call(stdout, 'drain', flushQueue);
|
|
1119
|
-
};
|
|
1120
|
-
const flush = () => {
|
|
1121
|
-
if (disposed || queue.length === 0)
|
|
1122
|
-
return;
|
|
1123
|
-
const pending = queue;
|
|
1124
|
-
queue = [];
|
|
1125
|
-
queuedBytes = 0;
|
|
1126
|
-
paused = false;
|
|
1127
|
-
const off = stdout.off ?? stdout.removeListener;
|
|
1128
|
-
off?.call(stdout, 'drain', flushQueue);
|
|
1129
|
-
// `stdout.write` queues asynchronously on pipes. Preserving JSON records
|
|
1130
|
-
// is more important than applying another local backpressure pause here;
|
|
1131
|
-
// exitAfterFlush writes a final sentinel and waits (bounded) for that
|
|
1132
|
-
// stream queue after command completion.
|
|
1133
|
-
for (const chunk of pending)
|
|
1134
|
-
stdout.write(chunk);
|
|
1135
|
-
};
|
|
1136
|
-
return { write, flush, dispose };
|
|
1137
|
-
}
|
|
1138
|
-
/**
|
|
1139
|
-
* Render the agent's current visible screen, then dispatch on the
|
|
1140
|
-
* outcome. Hard errors (`not_found`, `no_pty`) abort: this helper
|
|
1141
|
-
* best-effort restores the prior delivery mode and writes the
|
|
1142
|
-
* appropriate error before returning `null` so the caller bails.
|
|
1143
|
-
* Transient errors warn and proceed. Returns `{ snapshotRows }` on the
|
|
1144
|
-
* happy path so the caller can seed the status-line row fallback.
|
|
1145
|
-
*
|
|
1146
|
-
* `noPtyAction` is the verb phrase used in the no-PTY message
|
|
1147
|
-
* (`agent 'X' has no PTY to ${noPtyAction}`) — e.g. "drive" or
|
|
1148
|
-
* "attach to".
|
|
1149
|
-
*/
|
|
1150
|
-
export async function captureInitialSnapshot(connection, name, previousMode, verb, noPtyAction, deps) {
|
|
1151
|
-
const render = deps.captureAndRenderSnapshot ?? captureAndRenderSnapshot;
|
|
1152
|
-
const snapshot = await render(connection, name, {
|
|
1153
|
-
fetch: deps.fetch,
|
|
1154
|
-
writeChunk: deps.writeChunk,
|
|
1155
|
-
fleetHint: deps.fleetHint,
|
|
1156
|
-
});
|
|
1157
|
-
switch (snapshot.status) {
|
|
1158
|
-
case 'ok':
|
|
1159
|
-
return { snapshotRows: snapshot.rows };
|
|
1160
|
-
case 'not_found':
|
|
1161
|
-
case 'no_pty': {
|
|
1162
|
-
try {
|
|
1163
|
-
await createBrokerClient(connection, deps.fetch).setInboundDeliveryMode(name, previousMode ?? 'auto_inject');
|
|
1164
|
-
}
|
|
1165
|
-
catch {
|
|
1166
|
-
// best-effort restore
|
|
1167
|
-
}
|
|
1168
|
-
const fallback = snapshot.status === 'not_found'
|
|
1169
|
-
? `no agent named '${name}'`
|
|
1170
|
-
: `agent '${name}' has no PTY to ${noPtyAction}`;
|
|
1171
|
-
deps.error(`Error: ${snapshot.message ?? fallback}`);
|
|
1172
|
-
return null;
|
|
1173
|
-
}
|
|
1174
|
-
case 'unavailable':
|
|
1175
|
-
case 'transport_error':
|
|
1176
|
-
deps.log(`[${verb}] could not capture initial screen (${snapshot.message ?? snapshot.status}); streaming live output only`);
|
|
1177
|
-
return { snapshotRows: snapshot.rows };
|
|
1178
|
-
}
|
|
1179
|
-
}
|
|
1180
|
-
//# sourceMappingURL=attach.js.map
|