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.
Files changed (251) hide show
  1. package/README.md +74 -266
  2. package/dist/cli/agent-relay-mcp.d.ts.map +1 -1
  3. package/dist/cli/agent-relay-mcp.js +6 -5
  4. package/dist/cli/agent-relay-mcp.js.map +1 -1
  5. package/dist/cli/bootstrap.d.ts +1 -1
  6. package/dist/cli/bootstrap.d.ts.map +1 -1
  7. package/dist/cli/bootstrap.js +11 -29
  8. package/dist/cli/bootstrap.js.map +1 -1
  9. package/dist/cli/commands/agent.d.ts.map +1 -1
  10. package/dist/cli/commands/agent.js +3 -2
  11. package/dist/cli/commands/agent.js.map +1 -1
  12. package/dist/cli/commands/cloud-integration.d.ts.map +1 -1
  13. package/dist/cli/commands/cloud-integration.js +2 -1
  14. package/dist/cli/commands/cloud-integration.js.map +1 -1
  15. package/dist/cli/commands/cloud-room.d.ts.map +1 -1
  16. package/dist/cli/commands/cloud-room.js +2 -1
  17. package/dist/cli/commands/cloud-room.js.map +1 -1
  18. package/dist/cli/commands/cloud-v1-deprecations.d.ts +4 -6
  19. package/dist/cli/commands/cloud-v1-deprecations.d.ts.map +1 -1
  20. package/dist/cli/commands/cloud-v1-deprecations.js +4 -6
  21. package/dist/cli/commands/cloud-v1-deprecations.js.map +1 -1
  22. package/dist/cli/commands/cloud-worker.d.ts +6 -2
  23. package/dist/cli/commands/cloud-worker.d.ts.map +1 -1
  24. package/dist/cli/commands/cloud-worker.js +74 -37
  25. package/dist/cli/commands/cloud-worker.js.map +1 -1
  26. package/dist/cli/commands/cloud.d.ts.map +1 -1
  27. package/dist/cli/commands/cloud.js +20 -18
  28. package/dist/cli/commands/cloud.js.map +1 -1
  29. package/dist/cli/commands/core.d.ts +3 -91
  30. package/dist/cli/commands/core.d.ts.map +1 -1
  31. package/dist/cli/commands/core.js +5 -254
  32. package/dist/cli/commands/core.js.map +1 -1
  33. package/dist/cli/commands/fleet-agent.d.ts +9 -54
  34. package/dist/cli/commands/fleet-agent.d.ts.map +1 -1
  35. package/dist/cli/commands/fleet-agent.js +105 -314
  36. package/dist/cli/commands/fleet-agent.js.map +1 -1
  37. package/dist/cli/commands/fleet.d.ts +0 -3
  38. package/dist/cli/commands/fleet.d.ts.map +1 -1
  39. package/dist/cli/commands/fleet.js +48 -267
  40. package/dist/cli/commands/fleet.js.map +1 -1
  41. package/dist/cli/commands/init.js +1 -1
  42. package/dist/cli/commands/init.js.map +1 -1
  43. package/dist/cli/commands/integration-cleanup-journal.d.ts +6 -2
  44. package/dist/cli/commands/integration-cleanup-journal.d.ts.map +1 -1
  45. package/dist/cli/commands/integration-cleanup-journal.js +611 -134
  46. package/dist/cli/commands/integration-cleanup-journal.js.map +1 -1
  47. package/dist/cli/commands/integration-recipient.d.ts +0 -17
  48. package/dist/cli/commands/integration-recipient.d.ts.map +1 -1
  49. package/dist/cli/commands/integration-recipient.js +1 -104
  50. package/dist/cli/commands/integration-recipient.js.map +1 -1
  51. package/dist/cli/commands/integration.d.ts +7 -3
  52. package/dist/cli/commands/integration.d.ts.map +1 -1
  53. package/dist/cli/commands/integration.js +37 -82
  54. package/dist/cli/commands/integration.js.map +1 -1
  55. package/dist/cli/commands/local-workflow.d.ts +1 -1
  56. package/dist/cli/commands/local-workflow.d.ts.map +1 -1
  57. package/dist/cli/commands/local-workflow.js +20 -6
  58. package/dist/cli/commands/local-workflow.js.map +1 -1
  59. package/dist/cli/commands/node.d.ts +18 -20
  60. package/dist/cli/commands/node.d.ts.map +1 -1
  61. package/dist/cli/commands/node.js +42 -272
  62. package/dist/cli/commands/node.js.map +1 -1
  63. package/dist/cli/commands/product-surfaces.js +2 -2
  64. package/dist/cli/commands/session.d.ts.map +1 -1
  65. package/dist/cli/commands/session.js +2 -1
  66. package/dist/cli/commands/session.js.map +1 -1
  67. package/dist/cli/commands/skills.d.ts.map +1 -1
  68. package/dist/cli/commands/skills.js +2 -1
  69. package/dist/cli/commands/skills.js.map +1 -1
  70. package/dist/cli/commands/status.d.ts +1 -7
  71. package/dist/cli/commands/status.d.ts.map +1 -1
  72. package/dist/cli/commands/status.js +2 -28
  73. package/dist/cli/commands/status.js.map +1 -1
  74. package/dist/cli/commands/workspace.d.ts.map +1 -1
  75. package/dist/cli/commands/workspace.js +2 -2
  76. package/dist/cli/commands/workspace.js.map +1 -1
  77. package/dist/cli/index.d.ts.map +1 -1
  78. package/dist/cli/index.js +1 -3
  79. package/dist/cli/index.js.map +1 -1
  80. package/dist/cli/lib/agent-relay-cli-reentry.d.ts +40 -0
  81. package/dist/cli/lib/agent-relay-cli-reentry.d.ts.map +1 -0
  82. package/dist/cli/lib/agent-relay-cli-reentry.js +47 -0
  83. package/dist/cli/lib/agent-relay-cli-reentry.js.map +1 -0
  84. package/dist/cli/lib/agent-tools-mcp.d.ts.map +1 -1
  85. package/dist/cli/lib/agent-tools-mcp.js +3 -2
  86. package/dist/cli/lib/agent-tools-mcp.js.map +1 -1
  87. package/dist/cli/lib/cloud-worker-authored-runtime.d.ts +3 -0
  88. package/dist/cli/lib/cloud-worker-authored-runtime.d.ts.map +1 -0
  89. package/dist/cli/lib/cloud-worker-authored-runtime.js +67 -0
  90. package/dist/cli/lib/cloud-worker-authored-runtime.js.map +1 -0
  91. package/dist/cli/lib/cloud-worker-enrollment-token.d.ts +13 -0
  92. package/dist/cli/lib/cloud-worker-enrollment-token.d.ts.map +1 -0
  93. package/dist/cli/lib/cloud-worker-enrollment-token.js +88 -0
  94. package/dist/cli/lib/cloud-worker-enrollment-token.js.map +1 -0
  95. package/dist/cli/lib/core-maintenance.d.ts +2 -3
  96. package/dist/cli/lib/core-maintenance.d.ts.map +1 -1
  97. package/dist/cli/lib/core-maintenance.js +3 -37
  98. package/dist/cli/lib/core-maintenance.js.map +1 -1
  99. package/dist/cli/lib/desktop-presence.js +1 -1
  100. package/dist/cli/lib/desktop-presence.js.map +1 -1
  101. package/dist/cli/lib/install-paths.d.ts +100 -0
  102. package/dist/cli/lib/install-paths.d.ts.map +1 -0
  103. package/dist/cli/lib/install-paths.js +157 -0
  104. package/dist/cli/lib/install-paths.js.map +1 -0
  105. package/dist/cli/lib/product-surface-store.d.ts.map +1 -1
  106. package/dist/cli/lib/product-surface-store.js +4 -1
  107. package/dist/cli/lib/product-surface-store.js.map +1 -1
  108. package/dist/cli/lib/relay-node.d.ts +7 -34
  109. package/dist/cli/lib/relay-node.d.ts.map +1 -1
  110. package/dist/cli/lib/relay-node.js +7 -182
  111. package/dist/cli/lib/relay-node.js.map +1 -1
  112. package/dist/cli/lib/removed-broker-command.d.ts +7 -0
  113. package/dist/cli/lib/removed-broker-command.d.ts.map +1 -0
  114. package/dist/cli/lib/removed-broker-command.js +13 -0
  115. package/dist/cli/lib/removed-broker-command.js.map +1 -0
  116. package/dist/cli/lib/sdk-client.d.ts +4 -4
  117. package/dist/cli/lib/sdk-client.js +4 -4
  118. package/dist/cli/lib/self-update.d.ts +8 -19
  119. package/dist/cli/lib/self-update.d.ts.map +1 -1
  120. package/dist/cli/lib/self-update.js +14 -28
  121. package/dist/cli/lib/self-update.js.map +1 -1
  122. package/dist/cli/lib/skills-install.d.ts.map +1 -1
  123. package/dist/cli/lib/skills-install.js +3 -2
  124. package/dist/cli/lib/skills-install.js.map +1 -1
  125. package/dist/cli/telemetry/events.d.ts +4 -1
  126. package/dist/cli/telemetry/events.d.ts.map +1 -1
  127. package/package.json +9 -14
  128. package/dist/auto/classifier.d.ts +0 -29
  129. package/dist/auto/classifier.d.ts.map +0 -1
  130. package/dist/auto/classifier.js +0 -126
  131. package/dist/auto/classifier.js.map +0 -1
  132. package/dist/auto/composer.d.ts +0 -105
  133. package/dist/auto/composer.d.ts.map +0 -1
  134. package/dist/auto/composer.js +0 -454
  135. package/dist/auto/composer.js.map +0 -1
  136. package/dist/auto/director-prompt.d.ts +0 -25
  137. package/dist/auto/director-prompt.d.ts.map +0 -1
  138. package/dist/auto/director-prompt.js +0 -53
  139. package/dist/auto/director-prompt.js.map +0 -1
  140. package/dist/auto/index.d.ts +0 -15
  141. package/dist/auto/index.d.ts.map +0 -1
  142. package/dist/auto/index.js +0 -13
  143. package/dist/auto/index.js.map +0 -1
  144. package/dist/cli/commands/local-agent.d.ts +0 -74
  145. package/dist/cli/commands/local-agent.d.ts.map +0 -1
  146. package/dist/cli/commands/local-agent.js +0 -969
  147. package/dist/cli/commands/local-agent.js.map +0 -1
  148. package/dist/cli/lib/attach-broker.d.ts +0 -17
  149. package/dist/cli/lib/attach-broker.d.ts.map +0 -1
  150. package/dist/cli/lib/attach-broker.js +0 -27
  151. package/dist/cli/lib/attach-broker.js.map +0 -1
  152. package/dist/cli/lib/attach-drive.d.ts +0 -376
  153. package/dist/cli/lib/attach-drive.d.ts.map +0 -1
  154. package/dist/cli/lib/attach-drive.js +0 -1212
  155. package/dist/cli/lib/attach-drive.js.map +0 -1
  156. package/dist/cli/lib/attach-fleet-node.d.ts +0 -85
  157. package/dist/cli/lib/attach-fleet-node.d.ts.map +0 -1
  158. package/dist/cli/lib/attach-fleet-node.js +0 -1347
  159. package/dist/cli/lib/attach-fleet-node.js.map +0 -1
  160. package/dist/cli/lib/attach-input-recovery.d.ts +0 -190
  161. package/dist/cli/lib/attach-input-recovery.d.ts.map +0 -1
  162. package/dist/cli/lib/attach-input-recovery.js +0 -559
  163. package/dist/cli/lib/attach-input-recovery.js.map +0 -1
  164. package/dist/cli/lib/attach-mode.d.ts +0 -2
  165. package/dist/cli/lib/attach-mode.d.ts.map +0 -1
  166. package/dist/cli/lib/attach-mode.js +0 -2
  167. package/dist/cli/lib/attach-mode.js.map +0 -1
  168. package/dist/cli/lib/attach-native.d.ts +0 -27
  169. package/dist/cli/lib/attach-native.d.ts.map +0 -1
  170. package/dist/cli/lib/attach-native.js +0 -267
  171. package/dist/cli/lib/attach-native.js.map +0 -1
  172. package/dist/cli/lib/attach-passthrough.d.ts +0 -193
  173. package/dist/cli/lib/attach-passthrough.d.ts.map +0 -1
  174. package/dist/cli/lib/attach-passthrough.js +0 -778
  175. package/dist/cli/lib/attach-passthrough.js.map +0 -1
  176. package/dist/cli/lib/attach-remote-node.d.ts +0 -21
  177. package/dist/cli/lib/attach-remote-node.d.ts.map +0 -1
  178. package/dist/cli/lib/attach-remote-node.js +0 -133
  179. package/dist/cli/lib/attach-remote-node.js.map +0 -1
  180. package/dist/cli/lib/attach-view.d.ts +0 -177
  181. package/dist/cli/lib/attach-view.d.ts.map +0 -1
  182. package/dist/cli/lib/attach-view.js +0 -455
  183. package/dist/cli/lib/attach-view.js.map +0 -1
  184. package/dist/cli/lib/attach.d.ts +0 -555
  185. package/dist/cli/lib/attach.d.ts.map +0 -1
  186. package/dist/cli/lib/attach.js +0 -1180
  187. package/dist/cli/lib/attach.js.map +0 -1
  188. package/dist/cli/lib/broker-connection.d.ts +0 -65
  189. package/dist/cli/lib/broker-connection.d.ts.map +0 -1
  190. package/dist/cli/lib/broker-connection.js +0 -144
  191. package/dist/cli/lib/broker-connection.js.map +0 -1
  192. package/dist/cli/lib/broker-lifecycle.d.ts +0 -220
  193. package/dist/cli/lib/broker-lifecycle.d.ts.map +0 -1
  194. package/dist/cli/lib/broker-lifecycle.js +0 -2290
  195. package/dist/cli/lib/broker-lifecycle.js.map +0 -1
  196. package/dist/cli/lib/broker-process-identity.d.ts +0 -38
  197. package/dist/cli/lib/broker-process-identity.d.ts.map +0 -1
  198. package/dist/cli/lib/broker-process-identity.js +0 -304
  199. package/dist/cli/lib/broker-process-identity.js.map +0 -1
  200. package/dist/cli/lib/client-factory.d.ts +0 -44
  201. package/dist/cli/lib/client-factory.d.ts.map +0 -1
  202. package/dist/cli/lib/client-factory.js +0 -64
  203. package/dist/cli/lib/client-factory.js.map +0 -1
  204. package/dist/cli/lib/collect-with-retry.d.ts +0 -24
  205. package/dist/cli/lib/collect-with-retry.d.ts.map +0 -1
  206. package/dist/cli/lib/collect-with-retry.js +0 -33
  207. package/dist/cli/lib/collect-with-retry.js.map +0 -1
  208. package/dist/cli/lib/fleet-attach-target.d.ts +0 -18
  209. package/dist/cli/lib/fleet-attach-target.d.ts.map +0 -1
  210. package/dist/cli/lib/fleet-attach-target.js +0 -57
  211. package/dist/cli/lib/fleet-attach-target.js.map +0 -1
  212. package/dist/cli/lib/fleet-hint.d.ts +0 -49
  213. package/dist/cli/lib/fleet-hint.d.ts.map +0 -1
  214. package/dist/cli/lib/fleet-hint.js +0 -113
  215. package/dist/cli/lib/fleet-hint.js.map +0 -1
  216. package/dist/cli/lib/fleet-sidecar.d.ts +0 -43
  217. package/dist/cli/lib/fleet-sidecar.d.ts.map +0 -1
  218. package/dist/cli/lib/fleet-sidecar.js +0 -84
  219. package/dist/cli/lib/fleet-sidecar.js.map +0 -1
  220. package/dist/cli/lib/join-ticket.d.ts +0 -22
  221. package/dist/cli/lib/join-ticket.d.ts.map +0 -1
  222. package/dist/cli/lib/join-ticket.js +0 -96
  223. package/dist/cli/lib/join-ticket.js.map +0 -1
  224. package/dist/cli/lib/node-claim.d.ts +0 -468
  225. package/dist/cli/lib/node-claim.d.ts.map +0 -1
  226. package/dist/cli/lib/node-claim.js +0 -1349
  227. package/dist/cli/lib/node-claim.js.map +0 -1
  228. package/dist/cli/lib/node-definition-loader.d.ts +0 -19
  229. package/dist/cli/lib/node-definition-loader.d.ts.map +0 -1
  230. package/dist/cli/lib/node-definition-loader.js +0 -143
  231. package/dist/cli/lib/node-definition-loader.js.map +0 -1
  232. package/dist/cli/lib/node-provider-child.d.ts +0 -129
  233. package/dist/cli/lib/node-provider-child.d.ts.map +0 -1
  234. package/dist/cli/lib/node-provider-child.js +0 -755
  235. package/dist/cli/lib/node-provider-child.js.map +0 -1
  236. package/dist/cli/lib/predictive-echo-screen.d.ts +0 -48
  237. package/dist/cli/lib/predictive-echo-screen.d.ts.map +0 -1
  238. package/dist/cli/lib/predictive-echo-screen.js +0 -74
  239. package/dist/cli/lib/predictive-echo-screen.js.map +0 -1
  240. package/dist/cli/lib/project-broker-client.d.ts +0 -4
  241. package/dist/cli/lib/project-broker-client.d.ts.map +0 -1
  242. package/dist/cli/lib/project-broker-client.js +0 -12
  243. package/dist/cli/lib/project-broker-client.js.map +0 -1
  244. package/dist/cli/lib/reflex-capture.d.ts +0 -41
  245. package/dist/cli/lib/reflex-capture.d.ts.map +0 -1
  246. package/dist/cli/lib/reflex-capture.js +0 -128
  247. package/dist/cli/lib/reflex-capture.js.map +0 -1
  248. package/dist/cli/lib/workspace-env.d.ts +0 -8
  249. package/dist/cli/lib/workspace-env.d.ts.map +0 -1
  250. package/dist/cli/lib/workspace-env.js +0 -16
  251. package/dist/cli/lib/workspace-env.js.map +0 -1
@@ -1,1347 +0,0 @@
1
- /**
2
- * Ticketed fleet-node attach adapter.
3
- *
4
- * The established attach clients intentionally continue to speak the local
5
- * broker HTTP/WebSocket contract. This short-lived loopback adapter maps that
6
- * contract onto Relaycast's authenticated terminal session, so view/drive and
7
- * passthrough retain their behaviour without exposing a remote broker listener
8
- * or copying a broker API key off a physical or Daytona node.
9
- */
10
- import { createServer } from 'node:http';
11
- import { once } from 'node:events';
12
- import { Buffer } from 'node:buffer';
13
- import { randomBytes } from 'node:crypto';
14
- import WebSocket, { WebSocketServer } from 'ws';
15
- import { AGENT37_RELAYCAST_ORIGIN, ARMADILLO_RELAYCAST_ORIGIN, CANONICAL_RELAYCAST_ORIGIN, } from '@agent-relay/cloud';
16
- import { collectWithRetry } from './collect-with-retry.js';
17
- import { resolveWorkspaceTransport } from './sdk-client.js';
18
- const MAX_BUFFERED_BYTES = 1024 * 1024;
19
- const MAX_WEBSOCKET_CLOSE_REASON_BYTES = 123;
20
- // Use the same finite 30s request window as the broker's Relaycast HTTP calls.
21
- // Terminal-session creation can exceed the shorter startup-handshake latency
22
- // under load, and this POST cannot be replayed safely after an ambiguous client
23
- // timeout because allocation may have completed server-side.
24
- const SESSION_REQUEST_TIMEOUT_MS = 30_000;
25
- // Immediate structured reachability failures still receive the complete
26
- // five-attempt/31.2s retry schedule, while slow responses cannot multiply the
27
- // per-attempt timeout into a roughly three-minute CLI hang.
28
- const SESSION_REQUEST_TOTAL_TIMEOUT_MS = 90_000;
29
- const SESSION_REQUEST_RETRIES = 4;
30
- // The fleet node publishes liveness every 12s. With four retries, the helper's
31
- // deterministic delays are 6s, 7.2s, 8.4s, and 9.6s: 31.2s total. That spans
32
- // more than two heartbeat intervals and matches the established terminal
33
- // transport's bounded recovery window instead of exhausting every retry inside
34
- // the same stale control-plane read.
35
- const SESSION_REQUEST_RETRY_DELAY_MS = 6_000;
36
- const TERMINAL_CONNECT_TIMEOUT_MS = 10_000;
37
- const INITIAL_RECONNECT_DELAY_MS = 500;
38
- const MAX_RECONNECT_DELAY_MS = 30_000;
39
- // Six delays (0.5s + 1s + 2s + 4s + 8s + 16s) cover the node terminal
40
- // transport's independent 30s maximum reconnect backoff without leaving this
41
- // client unbounded. Five attempts previously stopped after only 15.5s.
42
- const MAX_RECONNECT_ATTEMPTS = 6;
43
- // Bounds the acknowledgement for a delivery-mode command after readiness.
44
- // The command is not replayable across reconnects, so this is intentionally a
45
- // separate post-readiness phase rather than another full reconnect window.
46
- const DELIVERY_MODE_TIMEOUT_MS = 10_000;
47
- // The caller starts its HTTP deadline before the loopback handler starts its
48
- // readiness timer. Leave a small response-delivery margin so the proxy's
49
- // actionable readiness error wins that race.
50
- const LOOPBACK_REQUEST_TIMEOUT_MARGIN_MS = 1_000;
51
- function gapDiagnosticsFromFrame(frame) {
52
- return {
53
- ...(typeof frame.blocked_reason_code === 'string'
54
- ? { blocked_reason_code: frame.blocked_reason_code }
55
- : {}),
56
- ...(typeof frame.head_sequence === 'number' ? { head_sequence: frame.head_sequence } : {}),
57
- ...(typeof frame.acked_up_to_sequence === 'number'
58
- ? { acked_up_to_sequence: frame.acked_up_to_sequence }
59
- : {}),
60
- ...(typeof frame.received_up_to_sequence === 'number'
61
- ? { received_up_to_sequence: frame.received_up_to_sequence }
62
- : {}),
63
- ...(typeof frame.next_ackable_sequence === 'number'
64
- ? { next_ackable_sequence: frame.next_ackable_sequence }
65
- : {}),
66
- ...(typeof frame.reconciliation_action === 'string'
67
- ? { reconciliation_action: frame.reconciliation_action }
68
- : {}),
69
- };
70
- }
71
- export class FleetNodeAttachError extends Error {
72
- code;
73
- constructor(message, code) {
74
- super(message);
75
- this.code = code;
76
- this.name = 'FleetNodeAttachError';
77
- }
78
- }
79
- const TRUSTED_RELAYCAST_ORIGINS = new Set([
80
- CANONICAL_RELAYCAST_ORIGIN,
81
- ARMADILLO_RELAYCAST_ORIGIN,
82
- AGENT37_RELAYCAST_ORIGIN,
83
- ]);
84
- export function validateFleetAttachBaseUrl(value) {
85
- let parsed;
86
- try {
87
- parsed = new URL(value);
88
- }
89
- catch {
90
- throw new FleetNodeAttachError('Fleet node attach requires a trusted Relaycast origin.');
91
- }
92
- if (parsed.protocol !== 'https:' ||
93
- parsed.username ||
94
- parsed.password ||
95
- parsed.port ||
96
- parsed.search ||
97
- parsed.hash ||
98
- (parsed.pathname !== '' && parsed.pathname !== '/') ||
99
- !TRUSTED_RELAYCAST_ORIGINS.has(parsed.origin)) {
100
- throw new FleetNodeAttachError('Fleet node attach requires a trusted Relaycast origin.');
101
- }
102
- return parsed.origin;
103
- }
104
- class TerminalSessionAttemptError extends FleetNodeAttachError {
105
- status;
106
- retryable;
107
- completionUnknown;
108
- constructor(message, code, status, retryable, completionUnknown) {
109
- super(message, code);
110
- this.status = status;
111
- this.retryable = retryable;
112
- this.completionUnknown = completionUnknown;
113
- }
114
- }
115
- /**
116
- * Canonical HTTP status for a terminal failure code.
117
- *
118
- * `agent_not_found` must stay 404: {@link switchInboundDeliveryModeOrAbort}
119
- * only emits the "no agent named X" message and the cross-node placement hint
120
- * on a 404, so collapsing it into 503 replaces actionable guidance with an
121
- * opaque unreachable-node error. `unsupported_runtime` stays 409. Everything
122
- * else is a transport-level failure and reports 503.
123
- */
124
- function terminalErrorStatus(code) {
125
- if (code === 'agent_not_found')
126
- return 404;
127
- if (code === 'unsupported_runtime')
128
- return 409;
129
- return 503;
130
- }
131
- function json(response, status, payload) {
132
- response.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
133
- response.end(JSON.stringify(payload));
134
- }
135
- function readBody(request) {
136
- return new Promise((resolve) => {
137
- let settled = false;
138
- const finish = (body) => {
139
- if (settled)
140
- return;
141
- settled = true;
142
- resolve(body);
143
- };
144
- let body = '';
145
- request.setEncoding('utf8');
146
- request.on('data', (chunk) => {
147
- body += chunk;
148
- });
149
- request.on('end', () => {
150
- try {
151
- const parsed = JSON.parse(body);
152
- finish(parsed && typeof parsed === 'object' && !Array.isArray(parsed)
153
- ? parsed
154
- : {});
155
- }
156
- catch {
157
- finish({});
158
- }
159
- });
160
- request.on('error', () => finish({}));
161
- request.on('aborted', () => finish({}));
162
- });
163
- }
164
- function asWsUrl(value) {
165
- const lower = value.toLowerCase();
166
- if (lower.startsWith('https://'))
167
- return 'wss://' + value.slice(8);
168
- if (lower.startsWith('http://'))
169
- return 'ws://' + value.slice(7);
170
- return value;
171
- }
172
- function safeNodePath(node) {
173
- const trimmed = node.trim().replace(/^#/, '');
174
- if (!trimmed)
175
- throw new FleetNodeAttachError('Error: --node requires a node name or id.', 'invalid_node');
176
- return encodeURIComponent(trimmed);
177
- }
178
- function parseFrame(data) {
179
- try {
180
- const parsed = JSON.parse(rawDataToString(data));
181
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
182
- }
183
- catch {
184
- return null;
185
- }
186
- }
187
- /**
188
- * Decode a `terminal.ready` / `terminal.snapshot` `screen` field into the raw
189
- * ANSI bytes a terminal can render.
190
- *
191
- * The two payloads this adapter bridges are encoded differently and the
192
- * difference is invisible at the type level — both are `string`:
193
- *
194
- * - `screen` is the visible grid rendered by `Snapshot::to_ansi()` and then
195
- * **base64-encoded**, because the broker asks the worker for
196
- * `format: "ansi"` (`fleet.rs`) and that arm encodes (`pty_worker.rs`).
197
- * Broker HTTP snapshot consumers decode it (`attach.ts` `captureAndRender…`).
198
- * - `worker_stream.chunk` (and `terminal.output.chunk`, which is the same
199
- * value forwarded) is **raw PTY bytes**. Attach clients write it to stdout
200
- * verbatim (`applyServerOutput` in `attach-drive.ts`).
201
- *
202
- * Handing an undecoded `screen` to {@link workerStreamEvent} therefore prints
203
- * the base64 text itself into the operator's terminal — the reconnect flood in
204
- * relay#1829. Returns `null` when the payload is not canonical base64, so a
205
- * malformed or protocol-violating frame is dropped rather than rendered: a
206
- * stale-but-coherent screen beats writing unintelligible bytes to a live TTY.
207
- */
208
- export function decodeAnsiScreenPayload(screen) {
209
- if (screen === '')
210
- return '';
211
- if (screen.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(screen))
212
- return null;
213
- const decoded = Buffer.from(screen, 'base64');
214
- // `Buffer.from(…, 'base64')` silently skips characters outside the alphabet,
215
- // so the round-trip is what actually rejects a non-base64 payload.
216
- if (decoded.toString('base64') !== screen)
217
- return null;
218
- return decoded.toString('utf8');
219
- }
220
- /**
221
- * Mirror of the broker's `pty_input_error_is_connection_fatal`
222
- * (`crates/broker/src/listen_api.rs`). The two lists must agree, because the
223
- * SDK's `PtyInputStream` latches `closed` **only** when its socket closes
224
- * (`harness-driver/src/transport.ts`): a fatal error delivered on a socket
225
- * that stays open leaves `isUsable()` true forever.
226
- *
227
- * That matters most for a fatal error that arrives with **no write in
228
- * flight** — the session-scoped `terminal.error` path below. The client's
229
- * `failAll()` then has nothing to reject, so nothing marks the stream dead:
230
- * the drive session never enters recovery and keeps writing into a stream the
231
- * node has already declared unusable. Closing the socket, as the broker does,
232
- * is what turns that into a reported outage the session can recover from.
233
- */
234
- export function inputErrorIsConnectionFatal(code) {
235
- return code !== 'worker_timeout' && code !== 'pty_write_queue_full';
236
- }
237
- function rawDataToString(data) {
238
- if (Buffer.isBuffer(data))
239
- return data.toString('utf8');
240
- if (data instanceof ArrayBuffer)
241
- return Buffer.from(data).toString('utf8');
242
- if (Array.isArray(data))
243
- return Buffer.concat(data).toString('utf8');
244
- return String(data);
245
- }
246
- function diagnosticEndpoint(value) {
247
- try {
248
- const url = new URL(value);
249
- url.username = '';
250
- url.password = '';
251
- url.search = '';
252
- url.hash = '';
253
- return url.toString();
254
- }
255
- catch {
256
- return '(invalid endpoint)';
257
- }
258
- }
259
- function diagnosticEndpointOrigin(value) {
260
- try {
261
- return new URL(value).origin;
262
- }
263
- catch {
264
- return '(invalid endpoint)';
265
- }
266
- }
267
- function boundedWebSocketCloseReason(reason) {
268
- const encoded = Buffer.from(reason, 'utf8');
269
- if (encoded.length <= MAX_WEBSOCKET_CLOSE_REASON_BYTES)
270
- return reason;
271
- const suffix = Buffer.from('…', 'utf8');
272
- let end = MAX_WEBSOCKET_CLOSE_REASON_BYTES - suffix.length;
273
- // Do not cut through a UTF-8 continuation sequence. Excluding the leading
274
- // byte at this boundary also excludes the incomplete code point.
275
- while (end > 0 && (encoded[end] & 0xc0) === 0x80)
276
- end -= 1;
277
- return Buffer.concat([encoded.subarray(0, end), suffix]).toString('utf8');
278
- }
279
- function diagnosticValue(value) {
280
- // JSON quoting keeps node names and upstream text from injecting terminal
281
- // control characters into the operator-facing error.
282
- return JSON.stringify(value);
283
- }
284
- function resolvedNodeIdFromTerminalUrl(value) {
285
- try {
286
- const match = /^\/v1\/nodes\/([^/]+)\/terminal\/connect$/.exec(new URL(value).pathname);
287
- return match?.[1] ? decodeURIComponent(match[1]) : undefined;
288
- }
289
- catch {
290
- return undefined;
291
- }
292
- }
293
- function retryDelayBudgetMs(attempts, initialMs, maxMs) {
294
- let total = 0;
295
- for (let attempt = 0; attempt < attempts; attempt += 1) {
296
- total += Math.min(initialMs * 2 ** attempt, maxMs);
297
- }
298
- return total;
299
- }
300
- function terminalSessionFailureSummary(error) {
301
- if (error.code === 'node_not_found')
302
- return 'Control-plane node lookup found no matching record';
303
- if (error.code === 'node_unreachable') {
304
- return /no terminal transport/i.test(error.message)
305
- ? 'The node record was found, but its terminal transport was unavailable'
306
- : 'The control plane classified the node as unreachable';
307
- }
308
- if (error.code === 'terminal_session_unavailable') {
309
- return 'The control plane could not allocate a terminal session';
310
- }
311
- if (error.code === 'control_plane_timeout')
312
- return 'Control-plane terminal-session lookup timed out';
313
- if (error.code === 'control_plane_unavailable')
314
- return 'Control-plane terminal-session lookup failed';
315
- return 'The terminal-session request was rejected';
316
- }
317
- function isRetryableTerminalSessionFailure(code) {
318
- // These structured responses are emitted before a session is returned, so
319
- // retrying cannot duplicate a successful allocation. A fetch timeout,
320
- // network failure, or unclassified 5xx is different: this POST may already
321
- // have completed server-side, and retrying it could create a second session.
322
- return code === 'node_unreachable' || code === 'terminal_session_unavailable';
323
- }
324
- /** Start a broker-compatible loopback proxy for one remote terminal session. */
325
- export async function startFleetNodeAttachProxy(options) {
326
- const env = options.env ?? process.env;
327
- const fetchFn = options.fetch ?? globalThis.fetch;
328
- const { workspaceKey, baseUrl: requestedBaseUrl } = resolveWorkspaceTransport({
329
- workspaceKey: options.workspaceKey,
330
- baseUrl: options.baseUrl,
331
- env,
332
- });
333
- const baseUrl = validateFleetAttachBaseUrl(requestedBaseUrl ?? CANONICAL_RELAYCAST_ORIGIN);
334
- const nodePath = safeNodePath(options.node);
335
- const sessionEndpoint = `${baseUrl}/v1/nodes/${nodePath}/terminal/sessions`;
336
- const sessionRequestTimeoutMs = options.sessionRequest?.timeoutMs ?? SESSION_REQUEST_TIMEOUT_MS;
337
- const sessionRequestTotalTimeoutMs = options.sessionRequest?.totalTimeoutMs ?? SESSION_REQUEST_TOTAL_TIMEOUT_MS;
338
- const sessionRequestDeadline = Date.now() + sessionRequestTotalTimeoutMs;
339
- const sessionRequestSleep = options.sessionRequest?.sleep ??
340
- ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
341
- let sessionRequestAttempts = 0;
342
- let sessionRequestBudgetExhaustedBetweenAttempts = false;
343
- let lastSessionError;
344
- const sessionResult = await collectWithRetry('terminal session request', async () => {
345
- const remainingRequestBudgetMs = sessionRequestDeadline - Date.now();
346
- if (remainingRequestBudgetMs <= 0) {
347
- sessionRequestBudgetExhaustedBetweenAttempts = true;
348
- const exhausted = lastSessionError === undefined
349
- ? new TerminalSessionAttemptError('overall terminal-session request deadline exhausted', 'control_plane_timeout', undefined, false, false)
350
- : new TerminalSessionAttemptError(lastSessionError.message, lastSessionError.code, lastSessionError.status, false, lastSessionError.completionUnknown);
351
- lastSessionError = exhausted;
352
- throw exhausted;
353
- }
354
- sessionRequestAttempts += 1;
355
- const controller = new AbortController();
356
- let timedOut = false;
357
- const attemptTimeoutMs = Math.min(sessionRequestTimeoutMs, remainingRequestBudgetMs);
358
- const timeout = setTimeout(() => {
359
- timedOut = true;
360
- controller.abort();
361
- }, attemptTimeoutMs);
362
- let ticketResponse;
363
- let ticketPayload;
364
- try {
365
- ticketResponse = await fetchFn(sessionEndpoint, {
366
- method: 'POST',
367
- headers: { Authorization: `Bearer ${workspaceKey}`, 'Content-Type': 'application/json' },
368
- body: JSON.stringify({ agent: options.agent, mode: options.mode }),
369
- signal: controller.signal,
370
- });
371
- const parsedPayload = (await ticketResponse.json());
372
- ticketPayload =
373
- parsedPayload && typeof parsedPayload === 'object' && !Array.isArray(parsedPayload)
374
- ? parsedPayload
375
- : {};
376
- }
377
- catch (error) {
378
- const detail = error instanceof Error ? error.message : String(error);
379
- lastSessionError = new TerminalSessionAttemptError(timedOut ? 'request exceeded its deadline' : detail, timedOut ? 'control_plane_timeout' : 'control_plane_unavailable', undefined, false, true);
380
- throw lastSessionError;
381
- }
382
- finally {
383
- clearTimeout(timeout);
384
- }
385
- const terminalUrl = ticketPayload.data?.terminal_url;
386
- const sessionId = ticketPayload.data?.session_id;
387
- const resumeToken = ticketPayload.data?.resume_token;
388
- if (!ticketResponse.ok || !terminalUrl || !sessionId || !resumeToken) {
389
- const code = ticketPayload.error?.code;
390
- const message = ticketPayload.error?.message ?? `terminal session request failed (HTTP ${ticketResponse.status})`;
391
- lastSessionError = new TerminalSessionAttemptError(message, code, ticketResponse.status, isRetryableTerminalSessionFailure(code), false);
392
- throw lastSessionError;
393
- }
394
- return { terminalUrl, sessionId, resumeToken, expiresAt: ticketPayload.data?.expires_at };
395
- }, {
396
- retries: SESSION_REQUEST_RETRIES,
397
- baseDelayMs: SESSION_REQUEST_RETRY_DELAY_MS,
398
- sleep: async (delayMs) => {
399
- const remainingRequestBudgetMs = sessionRequestDeadline - Date.now();
400
- if (remainingRequestBudgetMs <= 0)
401
- return;
402
- await sessionRequestSleep(Math.min(delayMs, remainingRequestBudgetMs));
403
- },
404
- shouldRetry: (error) => error instanceof TerminalSessionAttemptError && error.retryable,
405
- });
406
- if (!sessionResult.ok) {
407
- const failure = lastSessionError;
408
- const status = failure?.status === undefined ? '' : ` HTTP ${failure.status};`;
409
- const code = failure?.code === undefined ? '' : ` code ${failure.code};`;
410
- const retryNote = sessionRequestBudgetExhaustedBetweenAttempts
411
- ? sessionRequestAttempts > 1
412
- ? `retried ${sessionRequestAttempts - 1} time${sessionRequestAttempts === 2 ? '' : 's'};` +
413
- ' overall budget exhausted before the next attempt'
414
- : 'not retried because the overall budget was exhausted before the next attempt'
415
- : sessionRequestAttempts > 1
416
- ? `retried ${sessionRequestAttempts - 1} time${sessionRequestAttempts === 2 ? '' : 's'}` +
417
- (failure?.completionUnknown
418
- ? '; final POST not retried because it may have completed server-side'
419
- : '')
420
- : failure?.completionUnknown
421
- ? 'not retried because the POST may have completed server-side'
422
- : 'not retried because the failure was terminal';
423
- const upstream = failure?.message ? ` Upstream message ${diagnosticValue(failure.message)}.` : '';
424
- throw new FleetNodeAttachError(`Error: ${failure ? terminalSessionFailureSummary(failure) : 'Terminal-session request failed'}.` +
425
- `${upstream} Node ref ${diagnosticValue(options.node.trim())}, resolved node id unavailable (session creation did not complete);` +
426
- ` endpoint ${diagnosticValue(diagnosticEndpoint(sessionEndpoint))};${status}${code}` +
427
- ` timeout ${sessionRequestTimeoutMs}ms per attempt; overall budget ${sessionRequestTotalTimeoutMs}ms;` +
428
- ` attempts ${sessionRequestAttempts} (${retryNote}).`, failure?.code);
429
- }
430
- let { terminalUrl, sessionId, resumeToken, expiresAt } = sessionResult.value;
431
- const resolvedNodeId = resolvedNodeIdFromTerminalUrl(terminalUrl);
432
- const remoteEndpoint = () => diagnosticEndpoint(terminalUrl);
433
- const reconnectInitialDelayMs = options.reconnectDelay?.initialMs ?? INITIAL_RECONNECT_DELAY_MS;
434
- const reconnectMaxDelayMs = options.reconnectDelay?.maxMs ?? MAX_RECONNECT_DELAY_MS;
435
- const terminalHandshakeTimeoutMs = options.reconnectDelay?.handshakeTimeoutMs ?? TERMINAL_CONNECT_TIMEOUT_MS;
436
- const terminalReadyTimeoutMs = options.reconnectDelay?.readyTimeoutMs ?? TERMINAL_CONNECT_TIMEOUT_MS;
437
- // A readiness-gated local request follows activeReadiness across reconnect
438
- // generations. Its own deadline therefore has to cover the same complete,
439
- // finite recovery path: every backoff plus every handshake/readiness pair.
440
- const terminalWaitTimeoutMs = retryDelayBudgetMs(MAX_RECONNECT_ATTEMPTS, reconnectInitialDelayMs, reconnectMaxDelayMs) +
441
- MAX_RECONNECT_ATTEMPTS * (terminalHandshakeTimeoutMs + terminalReadyTimeoutMs) +
442
- sessionRequestTotalTimeoutMs;
443
- let connectionGeneration = 0;
444
- const createReadiness = () => {
445
- let resolve;
446
- let reject;
447
- const promise = new Promise((resolvePromise, rejectPromise) => {
448
- resolve = resolvePromise;
449
- reject = rejectPromise;
450
- });
451
- // A failure can land before a snapshot request attaches its waiter. Keep
452
- // the rejection observable while avoiding an unhandled-rejection warning.
453
- void promise.catch(() => undefined);
454
- return { generation: ++connectionGeneration, settled: false, promise, resolve, reject };
455
- };
456
- let activeReadiness = createReadiness();
457
- const resolveReadiness = (readiness) => {
458
- if (readiness.settled)
459
- return;
460
- readiness.settled = true;
461
- readiness.resolve();
462
- };
463
- const rejectReadiness = (readiness, error) => {
464
- if (readiness.settled)
465
- return;
466
- readiness.settled = true;
467
- readiness.reject(error);
468
- };
469
- const waitForCurrentReadiness = async () => {
470
- for (;;) {
471
- const readiness = activeReadiness;
472
- await readiness.promise;
473
- if (readiness === activeReadiness)
474
- return;
475
- }
476
- };
477
- /**
478
- * Await the live readiness generation through both the WebSocket handshake
479
- * and the post-open terminal.ready allowance.
480
- * Every handler that must not run before `terminal.ready` — snapshot,
481
- * delivery-mode PUT, resize — goes through this one helper so the
482
- * timer/clearTimeout/settle logic cannot diverge between copies.
483
- *
484
- * Rejects with the underlying {@link FleetNodeAttachError} when the terminal
485
- * failed (preserving its `code`), or a plain `Error` carrying
486
- * `timeoutMessage` when the wait expired.
487
- */
488
- const waitForTerminalReady = (timeoutMessage) => new Promise((resolve, reject) => {
489
- const timer = setTimeout(() => reject(new Error(timeoutMessage)), terminalWaitTimeoutMs);
490
- void waitForCurrentReadiness().then(() => {
491
- clearTimeout(timer);
492
- resolve();
493
- }, (error) => {
494
- clearTimeout(timer);
495
- reject(error);
496
- });
497
- });
498
- /**
499
- * The two screen representations are kept as separate, differently named
500
- * fields on purpose. They are both strings and only one of them may reach a
501
- * terminal; a single `screen` field spread into both consumers is what let
502
- * the encoded form escape to stdout (relay#1829).
503
- *
504
- * `screenBase64` is the HTTP snapshot wire format (callers decode it).
505
- * `screenAnsi` is the renderable form, and the only one that may be emitted
506
- * as a `worker_stream` chunk.
507
- */
508
- const snapshot = {
509
- screenBase64: '',
510
- screenAnsi: '',
511
- rows: 24,
512
- cols: 80,
513
- offset: 0,
514
- };
515
- const eventSockets = new Set();
516
- const inputSockets = new Set();
517
- const outputHistory = [];
518
- let outputHistoryBytes = 0;
519
- let remote;
520
- let stopped = false;
521
- let terminalEnded = false;
522
- let terminalEverReady = false;
523
- let reconnecting = false;
524
- let reconnectAttempts = 0;
525
- let reconnectTimer;
526
- const terminalReadinessTimers = new Set();
527
- /** Locally-tracked delivery mode, kept in sync with each broker reply. */
528
- let loopbackDeliveryMode = options.mode === 'drive' ? 'manual_flush' : 'auto_inject';
529
- let pendingFlush = null;
530
- /** At most one in-flight delivery-mode PUT at a time. */
531
- let pendingDeliveryMode = null;
532
- const loopbackApiKey = randomBytes(32).toString('base64url');
533
- const loopbackAuthorized = (headers) => headers.authorization === `Bearer ${loopbackApiKey}` || headers['x-api-key'] === loopbackApiKey;
534
- const server = createServer(async (request, response) => {
535
- if (!loopbackAuthorized(request.headers)) {
536
- json(response, 401, {
537
- error: { code: 'unauthorized', message: 'loopback terminal token is required' },
538
- });
539
- return;
540
- }
541
- const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname;
542
- if (request.method === 'GET' && path === `/api/spawned/${encodeURIComponent(options.agent)}/snapshot`) {
543
- try {
544
- await waitForTerminalReady('terminal snapshot timed out');
545
- }
546
- catch (error) {
547
- const terminalError = error instanceof FleetNodeAttachError ? error : undefined;
548
- json(response, terminalErrorStatus(terminalError?.code), {
549
- error: {
550
- code: terminalError?.code ?? 'snapshot_unavailable',
551
- message: terminalError?.message ?? (error instanceof Error ? error.message : 'snapshot unavailable'),
552
- },
553
- });
554
- return;
555
- }
556
- // Explicit field mapping, not a spread: this endpoint's `screen` is
557
- // contractually base64 (the caller decodes it), and only the encoded
558
- // form may appear here.
559
- json(response, 200, {
560
- format: 'ansi',
561
- screen: snapshot.screenBase64,
562
- rows: snapshot.rows,
563
- cols: snapshot.cols,
564
- offset: snapshot.offset,
565
- });
566
- return;
567
- }
568
- const name = encodeURIComponent(options.agent);
569
- if (path === `/api/spawned/${name}/flush` && request.method === 'POST') {
570
- // Forward the flush to the remote broker over the terminal websocket.
571
- // Without this the `--node` form of `node agent message flush` reached
572
- // only the LOCAL broker's worker registry and returned agent_not_found
573
- // for a name that `node agent list` and `attach` both resolve.
574
- try {
575
- await waitForTerminalReady('terminal connection timed out');
576
- }
577
- catch (error) {
578
- const terminalError = error instanceof FleetNodeAttachError ? error : undefined;
579
- json(response, terminalErrorStatus(terminalError?.code), {
580
- error: {
581
- code: terminalError?.code ?? 'node_unreachable',
582
- message: terminalError?.message ?? (error instanceof Error ? error.message : 'terminal unavailable'),
583
- },
584
- });
585
- return;
586
- }
587
- if (!remote || remote.readyState !== WebSocket.OPEN) {
588
- json(response, 503, {
589
- error: { code: 'node_unreachable', message: 'terminal transport is not connected' },
590
- });
591
- return;
592
- }
593
- if (pendingFlush) {
594
- json(response, 503, {
595
- error: { code: 'flush_conflict', message: 'a flush request is already in flight' },
596
- });
597
- return;
598
- }
599
- const requestId = randomBytes(8).toString('hex');
600
- const result = await new Promise((resolve) => {
601
- const timer = setTimeout(() => {
602
- pendingFlush = null;
603
- resolve(new FleetNodeAttachError('flush request timed out', 'flush_timeout'));
604
- }, DELIVERY_MODE_TIMEOUT_MS);
605
- pendingFlush = {
606
- requestId,
607
- resolve: (r) => resolve(r),
608
- reject: (e) => resolve(e),
609
- timer,
610
- };
611
- remote.send(JSON.stringify({
612
- type: 'terminal.flush_pending',
613
- session_id: sessionId,
614
- request_id: requestId,
615
- }));
616
- });
617
- if (result instanceof Error) {
618
- const errCode = result instanceof FleetNodeAttachError ? (result.code ?? 'flush_failed') : 'flush_failed';
619
- json(response, terminalErrorStatus(errCode), {
620
- error: { code: errCode, message: result.message },
621
- });
622
- return;
623
- }
624
- json(response, 200, result);
625
- return;
626
- }
627
- if (path === `/api/spawned/${name}/delivery-mode`) {
628
- if (request.method === 'GET') {
629
- json(response, 200, { mode: loopbackDeliveryMode });
630
- return;
631
- }
632
- // PUT — forward the request to the remote broker via the terminal WS and
633
- // await the broker's real reply. This is the path that was previously a
634
- // static stub returning manual_flush, causing drive attach to fail with
635
- // "broker remained in manual_flush mode".
636
- const body = await readBody(request);
637
- const requestedMode = body.mode === 'auto_inject' ? 'auto_inject' : body.mode === 'manual_flush' ? 'manual_flush' : null;
638
- if (requestedMode === null) {
639
- json(response, 400, {
640
- error: { code: 'invalid_mode', message: `unsupported delivery mode '${String(body.mode)}'` },
641
- });
642
- return;
643
- }
644
- // Drive attach changes delivery mode before it requests the initial
645
- // snapshot. Gate the PUT on terminal.ready so a fast local caller does
646
- // not lose a race with the remote websocket handshake and receive the
647
- // misleading "terminal transport is not connected" failure.
648
- try {
649
- await waitForTerminalReady('terminal connection timed out');
650
- }
651
- catch (error) {
652
- // Preserve the canonical status mapping here too: a readiness failure
653
- // carrying `agent_not_found` has to reach the preflight as a 404 or
654
- // the operator loses the cross-node placement hint that tells them
655
- // which machine to run the attach on.
656
- const terminalError = error instanceof FleetNodeAttachError ? error : undefined;
657
- json(response, terminalErrorStatus(terminalError?.code), {
658
- error: {
659
- code: terminalError?.code ?? 'node_unreachable',
660
- message: terminalError?.message ?? (error instanceof Error ? error.message : 'terminal unavailable'),
661
- },
662
- });
663
- return;
664
- }
665
- if (!remote || remote.readyState !== WebSocket.OPEN) {
666
- json(response, 503, {
667
- error: { code: 'node_unreachable', message: 'terminal transport is not connected' },
668
- });
669
- return;
670
- }
671
- if (pendingDeliveryMode) {
672
- json(response, 503, {
673
- error: { code: 'delivery_mode_conflict', message: 'a delivery mode request is already in flight' },
674
- });
675
- return;
676
- }
677
- const requestId = randomBytes(8).toString('hex');
678
- const result = await new Promise((resolve) => {
679
- const timer = setTimeout(() => {
680
- pendingDeliveryMode = null;
681
- resolve(new FleetNodeAttachError('delivery mode request timed out', 'delivery_mode_timeout'));
682
- }, DELIVERY_MODE_TIMEOUT_MS);
683
- pendingDeliveryMode = {
684
- requestId,
685
- resolve: (r) => resolve(r),
686
- reject: (e) => resolve(e),
687
- timer,
688
- };
689
- const frame = {
690
- type: 'terminal.set_delivery_mode',
691
- session_id: sessionId,
692
- mode: requestedMode,
693
- request_id: requestId,
694
- };
695
- if (typeof body.expected_mode === 'string')
696
- frame.expected_mode = body.expected_mode;
697
- if (typeof body.expected_revision === 'string')
698
- frame.expected_revision = body.expected_revision;
699
- remote.send(JSON.stringify(frame));
700
- });
701
- if (result instanceof Error) {
702
- const errCode = result instanceof FleetNodeAttachError
703
- ? (result.code ?? 'delivery_mode_failed')
704
- : 'delivery_mode_failed';
705
- // Same canonical mapping as the readiness gate: 404 for
706
- // agent_not_found so the attach preflight can produce the no-agent or
707
- // cross-node placement error, 409 for unsupported_runtime, 503 for
708
- // everything else.
709
- json(response, terminalErrorStatus(errCode), {
710
- error: { code: errCode, message: result.message },
711
- });
712
- return;
713
- }
714
- loopbackDeliveryMode = result.mode === 'manual_flush' ? 'manual_flush' : 'auto_inject';
715
- json(response, 200, {
716
- mode: result.mode,
717
- flushed: result.flushed,
718
- ...(result.dead_lettered !== undefined ? { dead_lettered: result.dead_lettered } : {}),
719
- matched: result.matched,
720
- revision: result.revision,
721
- ...(result.blocked_reason !== undefined ? { blocked_reason: result.blocked_reason } : {}),
722
- ...gapDiagnosticsFromFrame(result),
723
- });
724
- return;
725
- }
726
- if (request.method === 'GET' && path === `/api/spawned/${name}/pending`) {
727
- json(response, 200, { pending: [] });
728
- return;
729
- }
730
- if (request.method === 'POST' && path === `/api/spawned/${name}/flush`) {
731
- json(response, 200, { flushed: 0 });
732
- return;
733
- }
734
- if (request.method === 'GET' && path === '/api/spawned') {
735
- json(response, 200, { agents: [{ name: options.agent, workerPid: 1 }] });
736
- return;
737
- }
738
- if (request.method === 'POST' && path === `/api/resize/${name}`) {
739
- const body = await readBody(request);
740
- if (body.release === true) {
741
- json(response, 200, { name: options.agent, released: true });
742
- return;
743
- }
744
- const rows = typeof body.rows === 'number' ? body.rows : 0;
745
- const cols = typeof body.cols === 'number' ? body.cols : 0;
746
- if (!Number.isInteger(rows) || !Number.isInteger(cols) || rows < 1 || cols < 1) {
747
- json(response, 400, {
748
- error: { code: 'invalid_dimensions', message: 'rows and cols must be positive integers' },
749
- });
750
- return;
751
- }
752
- try {
753
- await waitForTerminalReady('terminal resize timed out');
754
- }
755
- catch (error) {
756
- json(response, 503, {
757
- error: {
758
- code: 'session_not_ready',
759
- message: error instanceof Error ? error.message : 'terminal session is not ready',
760
- },
761
- });
762
- return;
763
- }
764
- if (!remote || remote.readyState !== WebSocket.OPEN || remote.bufferedAmount > MAX_BUFFERED_BYTES) {
765
- json(response, 503, {
766
- error: { code: 'node_unreachable', message: 'terminal transport is unavailable' },
767
- });
768
- return;
769
- }
770
- remote.send(JSON.stringify({ type: 'terminal.resize', session_id: sessionId, rows, cols }));
771
- json(response, 200, { name: options.agent, rows, cols, applied: true });
772
- return;
773
- }
774
- json(response, 404, { error: { code: 'not_found', message: 'loopback terminal endpoint not found' } });
775
- });
776
- const websocketServer = new WebSocketServer({ noServer: true });
777
- const closeSocket = (socket, code, reason) => {
778
- try {
779
- socket.close(code, boundedWebSocketCloseReason(reason));
780
- }
781
- catch {
782
- /* connection already gone */
783
- }
784
- };
785
- const broadcast = (sockets, payload) => {
786
- const encoded = JSON.stringify(payload);
787
- let accepted = false;
788
- for (const socket of sockets) {
789
- if (socket.readyState !== WebSocket.OPEN)
790
- continue;
791
- if (socket.bufferedAmount > MAX_BUFFERED_BYTES) {
792
- closeSocket(socket, 1013, 'loopback client backpressure exceeded');
793
- sockets.delete(socket);
794
- continue;
795
- }
796
- try {
797
- socket.send(encoded);
798
- accepted = true;
799
- }
800
- catch {
801
- sockets.delete(socket);
802
- }
803
- }
804
- return accepted;
805
- };
806
- const workerStreamEvent = (chunk, offset) => ({
807
- kind: 'worker_stream',
808
- name: options.agent,
809
- stream: 'stdout',
810
- chunk,
811
- ...(offset === undefined ? {} : { offset }),
812
- });
813
- const retainOutput = (chunk, offset) => {
814
- const bytes = Buffer.byteLength(chunk, 'utf8');
815
- if (outputHistoryBytes + bytes > MAX_BUFFERED_BYTES)
816
- return false;
817
- outputHistory.push({ chunk, ...(offset === undefined ? {} : { offset }) });
818
- outputHistoryBytes += bytes;
819
- return true;
820
- };
821
- /**
822
- * Report a PTY-input failure to one input socket the way the broker does:
823
- * with the `retryable` flag the SDK reads, and — for a connection-fatal
824
- * code — by closing the socket so the client's `PtyInputStream` latches
825
- * `closed` and its recovery can start buffering. See
826
- * {@link inputErrorIsConnectionFatal}.
827
- */
828
- const failInputSocket = (socket, code, message) => {
829
- const fatal = inputErrorIsConnectionFatal(code);
830
- if (socket.readyState === WebSocket.OPEN) {
831
- try {
832
- socket.send(JSON.stringify({ type: 'pty_input_error', code, message, retryable: !fatal }));
833
- }
834
- catch {
835
- // The socket is already gone; the close below is still correct.
836
- }
837
- }
838
- if (!fatal)
839
- return;
840
- inputSockets.delete(socket);
841
- closeSocket(socket, 1011, message);
842
- };
843
- /** Same, for every attached input socket (session-scoped failures). */
844
- const failAllInputSockets = (code, message) => {
845
- for (const socket of [...inputSockets])
846
- failInputSocket(socket, code, message);
847
- };
848
- websocketServer.on('connection', (socket, request) => {
849
- const path = new URL(request.url ?? '/', 'http://127.0.0.1').pathname;
850
- if (path === '/ws') {
851
- eventSockets.add(socket);
852
- socket.on('close', () => eventSockets.delete(socket));
853
- let replayed = 0;
854
- for (const event of outputHistory) {
855
- if (socket.readyState !== WebSocket.OPEN || socket.bufferedAmount > MAX_BUFFERED_BYTES)
856
- break;
857
- try {
858
- socket.send(JSON.stringify(workerStreamEvent(event.chunk, event.offset)));
859
- }
860
- catch {
861
- break;
862
- }
863
- replayed += 1;
864
- }
865
- if (replayed > 0) {
866
- const sentBytes = outputHistory
867
- .slice(0, replayed)
868
- .reduce((total, event) => total + Buffer.byteLength(event.chunk, 'utf8'), 0);
869
- outputHistory.splice(0, replayed);
870
- outputHistoryBytes -= sentBytes;
871
- }
872
- return;
873
- }
874
- if (path === `/api/input/${encodeURIComponent(options.agent)}/stream`) {
875
- inputSockets.add(socket);
876
- socket.on('close', () => inputSockets.delete(socket));
877
- socket.send(JSON.stringify({ type: 'pty_input_ready', name: options.agent }));
878
- socket.on('message', (data) => {
879
- if (!remote || remote.readyState !== WebSocket.OPEN || remote.bufferedAmount > MAX_BUFFERED_BYTES) {
880
- // Only THIS socket failed to write; a sibling input stream must not
881
- // be torn down for it. `node_unreachable` is connection-fatal, so
882
- // this also closes the socket — see failInputSocket.
883
- failInputSocket(socket, 'node_unreachable', 'terminal transport is unavailable');
884
- return;
885
- }
886
- const raw = rawDataToString(data);
887
- remote.send(JSON.stringify({
888
- type: 'terminal.input',
889
- session_id: sessionId,
890
- data_base64: Buffer.from(raw, 'utf8').toString('base64'),
891
- }));
892
- });
893
- return;
894
- }
895
- closeSocket(socket, 1008, 'unknown loopback endpoint');
896
- });
897
- server.on('upgrade', (request, socket, head) => {
898
- if (!loopbackAuthorized(request.headers)) {
899
- socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
900
- socket.destroy();
901
- return;
902
- }
903
- websocketServer.handleUpgrade(request, socket, head, (client) => websocketServer.emit('connection', client, request));
904
- });
905
- server.listen(0, '127.0.0.1');
906
- await once(server, 'listening');
907
- const address = server.address();
908
- if (!address || typeof address === 'string')
909
- throw new FleetNodeAttachError('Error: could not allocate loopback terminal listener.', 'loopback_unavailable');
910
- const resumeUrlForCurrentSession = () => {
911
- const resumeUrl = new URL(terminalUrl);
912
- resumeUrl.searchParams.delete('ticket');
913
- resumeUrl.searchParams.set('session_id', sessionId);
914
- resumeUrl.searchParams.set('resume', resumeToken);
915
- return resumeUrl.toString();
916
- };
917
- const terminalSessionExpired = () => {
918
- if (!expiresAt)
919
- return false;
920
- const expiresAtMs = Date.parse(expiresAt);
921
- return Number.isFinite(expiresAtMs) && expiresAtMs <= Date.now();
922
- };
923
- // A disconnected terminal can need one replacement session when its resume
924
- // credential has expired. Keep this scoped to the whole reconnect incident:
925
- // a replacement that itself drops still follows the normal bounded resume
926
- // budget instead of repeatedly allocating sessions.
927
- let replacementAllocatedForReconnect = false;
928
- const allocateReplacementTerminalSession = async () => {
929
- const replacementDeadline = Date.now() + sessionRequestTotalTimeoutMs;
930
- let lastReplacementError;
931
- const result = await collectWithRetry('replacement terminal session request', async () => {
932
- const remainingMs = replacementDeadline - Date.now();
933
- if (remainingMs <= 0) {
934
- throw new TerminalSessionAttemptError(lastReplacementError?.message ??
935
- 'overall replacement terminal-session request deadline exhausted', lastReplacementError?.code ?? 'control_plane_timeout', lastReplacementError?.status, false, lastReplacementError?.completionUnknown ?? false);
936
- }
937
- const controller = new AbortController();
938
- let timedOut = false;
939
- const timeout = setTimeout(() => {
940
- timedOut = true;
941
- controller.abort();
942
- }, Math.min(sessionRequestTimeoutMs, remainingMs));
943
- try {
944
- const response = await fetchFn(sessionEndpoint, {
945
- method: 'POST',
946
- headers: { Authorization: `Bearer ${workspaceKey}`, 'Content-Type': 'application/json' },
947
- // Keep the replacement bound to precisely the session this proxy was
948
- // already serving; never infer a different agent or delivery mode.
949
- body: JSON.stringify({ agent: options.agent, mode: options.mode }),
950
- signal: controller.signal,
951
- });
952
- const parsed = (await response.json());
953
- const payload = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
954
- ? parsed
955
- : {};
956
- const replacementUrl = payload.data?.terminal_url;
957
- const replacementSessionId = payload.data?.session_id;
958
- const replacementResumeToken = payload.data?.resume_token;
959
- if (!response.ok || !replacementUrl || !replacementSessionId || !replacementResumeToken) {
960
- const error = new TerminalSessionAttemptError(payload.error?.message ??
961
- 'terminal session could not be replaced after its resume credential expired', payload.error?.code, response.status, isRetryableTerminalSessionFailure(payload.error?.code), false);
962
- lastReplacementError = error;
963
- throw error;
964
- }
965
- return {
966
- terminalUrl: replacementUrl,
967
- sessionId: replacementSessionId,
968
- resumeToken: replacementResumeToken,
969
- expiresAt: payload.data?.expires_at,
970
- };
971
- }
972
- catch (error) {
973
- if (error instanceof TerminalSessionAttemptError)
974
- throw error;
975
- const replacementError = new TerminalSessionAttemptError(timedOut
976
- ? 'replacement request exceeded its deadline'
977
- : 'replacement terminal session request failed', timedOut ? 'control_plane_timeout' : 'control_plane_unavailable', undefined, false, true);
978
- lastReplacementError = replacementError;
979
- throw replacementError;
980
- }
981
- finally {
982
- clearTimeout(timeout);
983
- }
984
- }, {
985
- retries: SESSION_REQUEST_RETRIES,
986
- baseDelayMs: SESSION_REQUEST_RETRY_DELAY_MS,
987
- sleep: async (delayMs) => {
988
- const remainingMs = replacementDeadline - Date.now();
989
- if (remainingMs > 0)
990
- await sessionRequestSleep(Math.min(delayMs, remainingMs));
991
- },
992
- shouldRetry: (error) => error instanceof TerminalSessionAttemptError && error.retryable,
993
- });
994
- if (result.ok)
995
- return result.value;
996
- if (lastReplacementError)
997
- throw lastReplacementError;
998
- throw new FleetNodeAttachError('terminal session could not be replaced after its resume credential expired', 'terminal_session_unavailable');
999
- };
1000
- /** Reject and clear any in-flight delivery-mode PUT, if one is pending. */
1001
- const rejectPendingDeliveryMode = (error) => {
1002
- if (pendingFlush) {
1003
- const flush = pendingFlush;
1004
- pendingFlush = null;
1005
- clearTimeout(flush.timer);
1006
- // A flush never changes delivery mode, so it must not inherit the
1007
- // delivery-mode disconnect wording. An operator debugging a failed flush
1008
- // would otherwise be told the "delivery-mode change" was interrupted —
1009
- // pointing at an operation their command never performed.
1010
- const flushError = error.code === 'delivery_mode_disconnected'
1011
- ? new FleetNodeAttachError('terminal transport disconnected while the flush was in flight', 'flush_disconnected')
1012
- : error;
1013
- flush.reject(flushError);
1014
- }
1015
- if (!pendingDeliveryMode)
1016
- return;
1017
- const pending = pendingDeliveryMode;
1018
- pendingDeliveryMode = null;
1019
- clearTimeout(pending.timer);
1020
- pending.reject(error);
1021
- };
1022
- const endTerminal = (error, eventCloseReason = error.message) => {
1023
- if (terminalEnded)
1024
- return;
1025
- terminalEnded = true;
1026
- if (reconnectTimer) {
1027
- clearTimeout(reconnectTimer);
1028
- reconnectTimer = undefined;
1029
- }
1030
- for (const timer of terminalReadinessTimers)
1031
- clearTimeout(timer);
1032
- terminalReadinessTimers.clear();
1033
- rejectPendingDeliveryMode(error);
1034
- const activeRemote = remote;
1035
- remote = undefined;
1036
- rejectReadiness(activeReadiness, error);
1037
- failAllInputSockets(error.code ?? 'terminal_error', error.message);
1038
- for (const socket of eventSockets)
1039
- closeSocket(socket, 1011, eventCloseReason);
1040
- if (activeRemote && activeRemote.readyState !== WebSocket.CLOSED) {
1041
- try {
1042
- activeRemote.terminate();
1043
- }
1044
- catch {
1045
- // The socket may have closed between the state check and terminate.
1046
- }
1047
- }
1048
- };
1049
- const failRemote = (message, eventCloseReason) => {
1050
- endTerminal(new FleetNodeAttachError(message, 'node_unreachable'), eventCloseReason);
1051
- };
1052
- const connect = (url, readiness) => {
1053
- if (stopped || terminalEnded)
1054
- return;
1055
- const socket = new WebSocket(asWsUrl(url), { handshakeTimeout: terminalHandshakeTimeoutMs });
1056
- remote = socket;
1057
- let readinessTimer;
1058
- let readinessExpired = false;
1059
- let resumeRejectedAsExpired = false;
1060
- const clearReadinessTimer = () => {
1061
- if (!readinessTimer)
1062
- return;
1063
- clearTimeout(readinessTimer);
1064
- terminalReadinessTimers.delete(readinessTimer);
1065
- readinessTimer = undefined;
1066
- };
1067
- socket.on('open', () => {
1068
- // `handshakeTimeout` independently bounds the HTTP upgrade. Start the
1069
- // terminal.ready allowance only after that upgrade succeeds so a slow
1070
- // but valid handshake cannot consume the readiness window.
1071
- readinessTimer = setTimeout(() => {
1072
- const expiredTimer = readinessTimer;
1073
- readinessTimer = undefined;
1074
- if (expiredTimer)
1075
- terminalReadinessTimers.delete(expiredTimer);
1076
- if (remote !== socket || stopped || terminalEnded || readiness.settled)
1077
- return;
1078
- // Mark this generation stale before terminating. The ws receiver may
1079
- // still deliver data already buffered on the socket while close is
1080
- // propagating; none of it may restore readiness or reset retry state.
1081
- readinessExpired = true;
1082
- if (!terminalEverReady) {
1083
- failRemote(`terminal transport connected but did not become ready (node ref ${diagnosticValue(options.node.trim())},` +
1084
- ` resolved node id ${diagnosticValue(resolvedNodeId ?? 'unavailable')}, endpoint ${diagnosticValue(remoteEndpoint())},` +
1085
- ` readiness timeout ${terminalReadyTimeoutMs}ms, attempts 1; not retried because no terminal session became ready)`);
1086
- return;
1087
- }
1088
- // A successful WebSocket upgrade is not sufficient: Relaycast may
1089
- // accept a resume lane that never produces terminal.ready. Terminating
1090
- // it drives the same bounded close/retry path as a transport failure.
1091
- options.reconnectDelay?.beforeReadyTimeoutTerminate?.(socket);
1092
- socket.terminate();
1093
- }, terminalReadyTimeoutMs);
1094
- terminalReadinessTimers.add(readinessTimer);
1095
- });
1096
- socket.on('message', (data) => {
1097
- // A late frame from a transport superseded during reconnect must never
1098
- // overwrite the fresh snapshot or end the replacement session.
1099
- if (remote !== socket || stopped || terminalEnded || readinessExpired)
1100
- return;
1101
- const frame = parseFrame(data);
1102
- if (!frame || frame.session_id !== sessionId)
1103
- return;
1104
- if (frame.type === 'terminal.ready') {
1105
- clearReadinessTimer();
1106
- snapshot.screenBase64 = typeof frame.screen === 'string' ? frame.screen : '';
1107
- // A payload that will not decode is kept out of `screenAnsi` entirely
1108
- // so no later consumer can render it; the HTTP snapshot still serves
1109
- // the bytes verbatim and lets its own decoder report the problem.
1110
- snapshot.screenAnsi = decodeAnsiScreenPayload(snapshot.screenBase64) ?? '';
1111
- snapshot.rows = typeof frame.rows === 'number' ? frame.rows : 24;
1112
- snapshot.cols = typeof frame.cols === 'number' ? frame.cols : 80;
1113
- snapshot.offset = typeof frame.offset === 'number' ? frame.offset : 0;
1114
- // Seed loopbackDeliveryMode from the broker's actual state so that
1115
- // detach restores the correct mode even when the worker started in a
1116
- // different mode than our local inference at line 214.
1117
- if (frame.delivery_mode === 'manual_flush' || frame.delivery_mode === 'auto_inject') {
1118
- loopbackDeliveryMode = frame.delivery_mode;
1119
- }
1120
- terminalEverReady = true;
1121
- reconnectAttempts = 0;
1122
- replacementAllocatedForReconnect = false;
1123
- if (readiness === activeReadiness) {
1124
- resolveReadiness(readiness);
1125
- // A reconnect gets a fresh ANSI grid but existing local `/ws`
1126
- // consumers have already performed their initial HTTP snapshot.
1127
- // Re-emit this screen without an offset so they repaint instead of
1128
- // retaining a stale pre-reconnect terminal image. It must be the
1129
- // DECODED grid: a `worker_stream` chunk is raw PTY bytes that the
1130
- // attach client writes straight to the terminal, so the base64 form
1131
- // renders as a wall of text instead of a repaint (relay#1829).
1132
- if (readiness.generation > 1 && snapshot.screenAnsi) {
1133
- broadcast(eventSockets, workerStreamEvent(snapshot.screenAnsi));
1134
- }
1135
- }
1136
- }
1137
- else if (frame.type === 'terminal.output' && typeof frame.chunk === 'string') {
1138
- const offset = typeof frame.offset === 'number' ? frame.offset : undefined;
1139
- if (!broadcast(eventSockets, workerStreamEvent(frame.chunk, offset))) {
1140
- if (!retainOutput(frame.chunk, offset)) {
1141
- endTerminal(new FleetNodeAttachError('terminal output exceeded the bounded loopback buffer', 'output_backpressure'));
1142
- }
1143
- }
1144
- }
1145
- else if (frame.type === 'terminal.input_ack') {
1146
- broadcast(inputSockets, {
1147
- type: 'pty_input_ack',
1148
- name: options.agent,
1149
- bytes_written: typeof frame.bytes_written === 'number' ? frame.bytes_written : 0,
1150
- });
1151
- }
1152
- else if (frame.type === 'terminal.delivery_mode') {
1153
- const frameRid = typeof frame.request_id === 'string' ? frame.request_id : undefined;
1154
- if (pendingDeliveryMode && (frameRid === undefined || frameRid === pendingDeliveryMode.requestId)) {
1155
- const pending = pendingDeliveryMode;
1156
- pendingDeliveryMode = null;
1157
- clearTimeout(pending.timer);
1158
- pending.resolve({
1159
- mode: typeof frame.mode === 'string' ? frame.mode : 'auto_inject',
1160
- flushed: typeof frame.flushed === 'number' ? frame.flushed : 0,
1161
- ...(typeof frame.dead_lettered === 'number' ? { dead_lettered: frame.dead_lettered } : {}),
1162
- matched: typeof frame.matched === 'boolean' ? frame.matched : true,
1163
- revision: typeof frame.revision === 'string' ? frame.revision : '1',
1164
- ...(typeof frame.blocked_reason === 'string' ? { blocked_reason: frame.blocked_reason } : {}),
1165
- ...gapDiagnosticsFromFrame(frame),
1166
- });
1167
- }
1168
- }
1169
- else if (frame.type === 'terminal.flush_pending') {
1170
- const frameRid = typeof frame.request_id === 'string' ? frame.request_id : undefined;
1171
- // Exact match only. The proxy always sends a request_id, and unlike
1172
- // delivery-mode there is no older-broker reply shape to stay
1173
- // compatible with, so a reply without one is not ours — accepting it
1174
- // would resolve the caller's flush with an unrelated result.
1175
- if (pendingFlush && frameRid === pendingFlush.requestId) {
1176
- const pending = pendingFlush;
1177
- pendingFlush = null;
1178
- clearTimeout(pending.timer);
1179
- pending.resolve({
1180
- flushed: typeof frame.flushed === 'number' ? frame.flushed : 0,
1181
- dead_lettered: typeof frame.dead_lettered === 'number' ? frame.dead_lettered : 0,
1182
- held: typeof frame.held === 'number' ? frame.held : 0,
1183
- blocked_reason: typeof frame.blocked_reason === 'string' ? frame.blocked_reason : null,
1184
- ...gapDiagnosticsFromFrame(frame),
1185
- });
1186
- }
1187
- }
1188
- else if (frame.type === 'terminal.error') {
1189
- const message = typeof frame.message === 'string' ? frame.message : 'remote terminal failed';
1190
- const code = typeof frame.code === 'string' ? frame.code : 'terminal_error';
1191
- const frameRid = typeof frame.request_id === 'string' ? frame.request_id : undefined;
1192
- // Route the error to the pending delivery-mode request only when the
1193
- // request_id matches (or the broker sent no request_id at all — older
1194
- // broker compat). An unrelated session-level error must not cancel a
1195
- // live delivery-mode PUT and vice-versa.
1196
- if (pendingFlush && frameRid !== undefined && frameRid === pendingFlush.requestId) {
1197
- const pending = pendingFlush;
1198
- pendingFlush = null;
1199
- clearTimeout(pending.timer);
1200
- pending.reject(new FleetNodeAttachError(message, code));
1201
- }
1202
- else if (pendingDeliveryMode &&
1203
- (frameRid === undefined || frameRid === pendingDeliveryMode.requestId)) {
1204
- const pending = pendingDeliveryMode;
1205
- pendingDeliveryMode = null;
1206
- clearTimeout(pending.timer);
1207
- pending.reject(new FleetNodeAttachError(message, code));
1208
- }
1209
- else if (!frameRid && readiness === activeReadiness && !readiness.settled) {
1210
- endTerminal(new FleetNodeAttachError(message, code));
1211
- }
1212
- else if (!frameRid) {
1213
- failAllInputSockets(code, message);
1214
- }
1215
- }
1216
- else if (frame.type === 'terminal.closed') {
1217
- endTerminal(new FleetNodeAttachError('remote terminal session closed', 'terminal_closed'));
1218
- }
1219
- });
1220
- socket.on('error', (error) => {
1221
- readinessExpired = true;
1222
- clearReadinessTimer();
1223
- // `ws` exposes a refused HTTP upgrade as this error before `close`.
1224
- // Only an expired resume credential may mint a replacement terminal;
1225
- // notably a transient or 5xx failure stays on the resume path.
1226
- if (terminalEverReady &&
1227
- error instanceof Error &&
1228
- /Unexpected server response: (401|410)\b/.test(error.message)) {
1229
- resumeRejectedAsExpired = true;
1230
- }
1231
- // Initial connection failure has no terminal state worth preserving.
1232
- // Fail promptly with the canonical unavailable-node error instead of
1233
- // letting the HTTP snapshot timeout mask it. Once Ready has been seen,
1234
- // the close handler retains the bounded resume/backoff behaviour.
1235
- if (remote === socket && readiness === activeReadiness && !readiness.settled && !terminalEverReady) {
1236
- failRemote(`terminal transport could not connect to the fleet node (node ref ${diagnosticValue(options.node.trim())},` +
1237
- ` resolved node id ${diagnosticValue(resolvedNodeId ?? 'unavailable')}, endpoint ${diagnosticValue(remoteEndpoint())},` +
1238
- ` handshake budget ${terminalHandshakeTimeoutMs}ms, attempts 1; not retried because no terminal session became ready)`);
1239
- }
1240
- });
1241
- socket.on('close', () => {
1242
- readinessExpired = true;
1243
- clearReadinessTimer();
1244
- if (remote !== socket || stopped || terminalEnded || reconnecting)
1245
- return;
1246
- // Relaycast drops the old lane's terminal session state on disconnect,
1247
- // so a set_delivery_mode frame already sent on this dying socket is
1248
- // lost and will never get a reply on the replacement socket — even
1249
- // once reconnect succeeds. Fail the pending PUT fast with a retryable
1250
- // error instead of leaving it to hang out the full timeout.
1251
- rejectPendingDeliveryMode(new FleetNodeAttachError('terminal transport disconnected while the delivery-mode change was in flight', 'delivery_mode_disconnected'));
1252
- // Any waiter that observed the prior connection must retry against the
1253
- // fresh generation instead of receiving its stale resolved snapshot.
1254
- resolveReadiness(readiness);
1255
- const nextReadiness = createReadiness();
1256
- activeReadiness = nextReadiness;
1257
- if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
1258
- const backoffBudgetMs = retryDelayBudgetMs(MAX_RECONNECT_ATTEMPTS, reconnectInitialDelayMs, reconnectMaxDelayMs);
1259
- const message = `terminal transport could not reconnect to the fleet node (node ref ${diagnosticValue(options.node.trim())},` +
1260
- ` resolved node id ${diagnosticValue(resolvedNodeId ?? 'unavailable')}, endpoint ${diagnosticValue(remoteEndpoint())},` +
1261
- ` handshake timeout ${terminalHandshakeTimeoutMs}ms, readiness timeout ${terminalReadyTimeoutMs}ms,` +
1262
- ` attempts ${reconnectAttempts},` +
1263
- ` backoff budget ${backoffBudgetMs}ms)`;
1264
- failRemote(message, `terminal reconnect failed; attempts=${reconnectAttempts}; budget=${backoffBudgetMs}ms;` +
1265
- ` endpoint=${diagnosticValue(diagnosticEndpointOrigin(terminalUrl))};` +
1266
- ` node=${diagnosticValue(resolvedNodeId ?? options.node.trim())}`);
1267
- return;
1268
- }
1269
- reconnecting = true;
1270
- const delay = Math.min(reconnectInitialDelayMs * 2 ** reconnectAttempts, reconnectMaxDelayMs);
1271
- reconnectAttempts += 1;
1272
- reconnectTimer = setTimeout(() => {
1273
- reconnectTimer = undefined;
1274
- reconnecting = false;
1275
- const needsReplacement = !replacementAllocatedForReconnect && (resumeRejectedAsExpired || terminalSessionExpired());
1276
- if (!needsReplacement) {
1277
- connect(resumeUrlForCurrentSession(), nextReadiness);
1278
- return;
1279
- }
1280
- replacementAllocatedForReconnect = true;
1281
- void allocateReplacementTerminalSession().then((replacement) => {
1282
- if (stopped || terminalEnded || activeReadiness !== nextReadiness)
1283
- return;
1284
- // This has no await between assignments, so every loopback
1285
- // handler observes one coherent replacement session.
1286
- terminalUrl = replacement.terminalUrl;
1287
- sessionId = replacement.sessionId;
1288
- resumeToken = replacement.resumeToken;
1289
- expiresAt = replacement.expiresAt;
1290
- connect(terminalUrl, nextReadiness);
1291
- }, (error) => {
1292
- if (stopped || terminalEnded || activeReadiness !== nextReadiness)
1293
- return;
1294
- const replacementError = error instanceof FleetNodeAttachError
1295
- ? error
1296
- : new FleetNodeAttachError('terminal session could not be replaced after its resume credential expired', 'terminal_session_unavailable');
1297
- endTerminal(new FleetNodeAttachError(`terminal transport could not replace an expired terminal session (node ref ${diagnosticValue(options.node.trim())},` +
1298
- ` resolved node id ${diagnosticValue(resolvedNodeId ?? 'unavailable')}, endpoint ${diagnosticValue(remoteEndpoint())})`, replacementError.code));
1299
- });
1300
- }, delay);
1301
- });
1302
- };
1303
- connect(terminalUrl, activeReadiness);
1304
- return {
1305
- brokerUrl: `http://127.0.0.1:${address.port}`,
1306
- apiKey: loopbackApiKey,
1307
- requestTimeoutMs: terminalWaitTimeoutMs + DELIVERY_MODE_TIMEOUT_MS + LOOPBACK_REQUEST_TIMEOUT_MARGIN_MS,
1308
- async close() {
1309
- if (stopped)
1310
- return;
1311
- stopped = true;
1312
- terminalEnded = true;
1313
- if (reconnectTimer) {
1314
- clearTimeout(reconnectTimer);
1315
- reconnectTimer = undefined;
1316
- }
1317
- for (const timer of terminalReadinessTimers)
1318
- clearTimeout(timer);
1319
- terminalReadinessTimers.clear();
1320
- rejectReadiness(activeReadiness, new FleetNodeAttachError('terminal attach closed', 'closed'));
1321
- rejectPendingDeliveryMode(new FleetNodeAttachError('terminal attach closed', 'closed'));
1322
- const activeRemote = remote;
1323
- remote = undefined;
1324
- if (activeRemote && activeRemote.readyState === WebSocket.OPEN) {
1325
- try {
1326
- activeRemote.send(JSON.stringify({ type: 'terminal.close', session_id: sessionId }));
1327
- }
1328
- catch {
1329
- // Best effort; terminate below still prevents a late reconnect.
1330
- }
1331
- }
1332
- if (activeRemote && activeRemote.readyState !== WebSocket.CLOSED) {
1333
- try {
1334
- activeRemote.terminate();
1335
- }
1336
- catch {
1337
- // Socket is already gone.
1338
- }
1339
- }
1340
- for (const socket of [...eventSockets, ...inputSockets])
1341
- closeSocket(socket, 1000, 'terminal attach closed');
1342
- websocketServer.close();
1343
- await new Promise((resolve) => server.close(() => resolve()));
1344
- },
1345
- };
1346
- }
1347
- //# sourceMappingURL=attach-fleet-node.js.map