@blue-soda/dsh-remote 0.5.5 → 0.5.7

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 (232) hide show
  1. package/README.md +2 -2
  2. package/cordis.patch.yml +30 -30
  3. package/dist/client.github.js +1 -1
  4. package/dist/client.js +1 -1
  5. package/dist/index.js +371 -80
  6. package/dist/index.js.map +4 -4
  7. package/dsh-plugin.json +41 -41
  8. package/package.json +165 -165
  9. package/dist/acp.d.ts +0 -75
  10. package/dist/acp.d.ts.map +0 -1
  11. package/dist/acp.js +0 -61
  12. package/dist/acp.js.map +0 -1
  13. package/dist/api-proxy-switch.d.ts +0 -33
  14. package/dist/api-proxy-switch.d.ts.map +0 -1
  15. package/dist/api-proxy-switch.js +0 -109
  16. package/dist/api-proxy-switch.js.map +0 -1
  17. package/dist/atomic-file.d.ts +0 -16
  18. package/dist/atomic-file.d.ts.map +0 -1
  19. package/dist/atomic-file.js +0 -81
  20. package/dist/atomic-file.js.map +0 -1
  21. package/dist/bin/doctor.d.ts +0 -3
  22. package/dist/bin/doctor.d.ts.map +0 -1
  23. package/dist/bin/doctor.js +0 -13
  24. package/dist/bin/doctor.js.map +0 -1
  25. package/dist/cli.d.ts +0 -32
  26. package/dist/cli.d.ts.map +0 -1
  27. package/dist/cli.js +0 -289
  28. package/dist/cli.js.map +0 -1
  29. package/dist/client-runtime.d.ts +0 -375
  30. package/dist/client-runtime.d.ts.map +0 -1
  31. package/dist/client-runtime.js +0 -1768
  32. package/dist/client-runtime.js.map +0 -1
  33. package/dist/client-secure-transport.d.ts +0 -23
  34. package/dist/client-secure-transport.d.ts.map +0 -1
  35. package/dist/client-secure-transport.js +0 -144
  36. package/dist/client-secure-transport.js.map +0 -1
  37. package/dist/client-target-store.d.ts +0 -40
  38. package/dist/client-target-store.d.ts.map +0 -1
  39. package/dist/client-target-store.js +0 -79
  40. package/dist/client-target-store.js.map +0 -1
  41. package/dist/client.d.ts +0 -13
  42. package/dist/client.d.ts.map +0 -1
  43. package/dist/codex/app-server.d.ts +0 -71
  44. package/dist/codex/app-server.d.ts.map +0 -1
  45. package/dist/codex/app-server.js +0 -268
  46. package/dist/codex/app-server.js.map +0 -1
  47. package/dist/codex/codex-image-codec.d.ts +0 -7
  48. package/dist/codex/codex-image-codec.d.ts.map +0 -1
  49. package/dist/codex/codex-image-codec.js +0 -288
  50. package/dist/codex/codex-image-codec.js.map +0 -1
  51. package/dist/codex/domain.d.ts +0 -102
  52. package/dist/codex/domain.d.ts.map +0 -1
  53. package/dist/codex/domain.js +0 -1323
  54. package/dist/codex/domain.js.map +0 -1
  55. package/dist/codex/method-policy.d.ts +0 -338
  56. package/dist/codex/method-policy.d.ts.map +0 -1
  57. package/dist/codex/method-policy.js +0 -141
  58. package/dist/codex/method-policy.js.map +0 -1
  59. package/dist/codex/peer-bridge.d.ts +0 -57
  60. package/dist/codex/peer-bridge.d.ts.map +0 -1
  61. package/dist/codex/peer-bridge.js +0 -299
  62. package/dist/codex/peer-bridge.js.map +0 -1
  63. package/dist/codex/permissions.d.ts +0 -4
  64. package/dist/codex/permissions.d.ts.map +0 -1
  65. package/dist/codex/permissions.js +0 -21
  66. package/dist/codex/permissions.js.map +0 -1
  67. package/dist/codex/session-id.d.ts +0 -10
  68. package/dist/codex/session-id.d.ts.map +0 -1
  69. package/dist/codex/session-id.js +0 -15
  70. package/dist/codex/session-id.js.map +0 -1
  71. package/dist/codex/virtual-harness.d.ts +0 -209
  72. package/dist/codex/virtual-harness.d.ts.map +0 -1
  73. package/dist/codex/virtual-harness.js +0 -2650
  74. package/dist/codex/virtual-harness.js.map +0 -1
  75. package/dist/codex-workspace-bridge.d.ts +0 -108
  76. package/dist/codex-workspace-bridge.d.ts.map +0 -1
  77. package/dist/codex-workspace-bridge.js +0 -502
  78. package/dist/codex-workspace-bridge.js.map +0 -1
  79. package/dist/config.d.ts +0 -99
  80. package/dist/config.d.ts.map +0 -1
  81. package/dist/config.js +0 -127
  82. package/dist/config.js.map +0 -1
  83. package/dist/connection-controller.d.ts +0 -44
  84. package/dist/connection-controller.d.ts.map +0 -1
  85. package/dist/connection-controller.js +0 -185
  86. package/dist/connection-controller.js.map +0 -1
  87. package/dist/control-route.d.ts +0 -34
  88. package/dist/control-route.d.ts.map +0 -1
  89. package/dist/control-route.js +0 -136
  90. package/dist/control-route.js.map +0 -1
  91. package/dist/control-runtime.d.ts +0 -138
  92. package/dist/control-runtime.d.ts.map +0 -1
  93. package/dist/control-runtime.js +0 -543
  94. package/dist/control-runtime.js.map +0 -1
  95. package/dist/control-stream.d.ts +0 -67
  96. package/dist/control-stream.d.ts.map +0 -1
  97. package/dist/control-stream.js +0 -179
  98. package/dist/control-stream.js.map +0 -1
  99. package/dist/defaults.d.ts +0 -9
  100. package/dist/defaults.d.ts.map +0 -1
  101. package/dist/defaults.js +0 -9
  102. package/dist/defaults.js.map +0 -1
  103. package/dist/file-viewer-bridge.d.ts +0 -30
  104. package/dist/file-viewer-bridge.d.ts.map +0 -1
  105. package/dist/file-viewer-bridge.js +0 -128
  106. package/dist/file-viewer-bridge.js.map +0 -1
  107. package/dist/file-viewer-contract.d.ts +0 -5
  108. package/dist/file-viewer-contract.d.ts.map +0 -1
  109. package/dist/file-viewer-contract.js +0 -4
  110. package/dist/file-viewer-contract.js.map +0 -1
  111. package/dist/harness-api-bridge.d.ts +0 -81
  112. package/dist/harness-api-bridge.d.ts.map +0 -1
  113. package/dist/harness-api-bridge.js +0 -862
  114. package/dist/harness-api-bridge.js.map +0 -1
  115. package/dist/harness-api-history.d.ts +0 -3
  116. package/dist/harness-api-history.d.ts.map +0 -1
  117. package/dist/harness-api-history.js +0 -59
  118. package/dist/harness-api-history.js.map +0 -1
  119. package/dist/harness-remote-bridge.d.ts +0 -60
  120. package/dist/harness-remote-bridge.d.ts.map +0 -1
  121. package/dist/harness-remote-bridge.js +0 -540
  122. package/dist/harness-remote-bridge.js.map +0 -1
  123. package/dist/harness-version.d.ts +0 -23
  124. package/dist/harness-version.d.ts.map +0 -1
  125. package/dist/harness-version.js +0 -95
  126. package/dist/harness-version.js.map +0 -1
  127. package/dist/identity-store.d.ts +0 -45
  128. package/dist/identity-store.d.ts.map +0 -1
  129. package/dist/identity-store.js +0 -186
  130. package/dist/identity-store.js.map +0 -1
  131. package/dist/ids.d.ts +0 -2
  132. package/dist/ids.d.ts.map +0 -1
  133. package/dist/ids.js +0 -17
  134. package/dist/ids.js.map +0 -1
  135. package/dist/index.d.ts +0 -78
  136. package/dist/index.d.ts.map +0 -1
  137. package/dist/logging.d.ts +0 -18
  138. package/dist/logging.d.ts.map +0 -1
  139. package/dist/logging.js +0 -30
  140. package/dist/logging.js.map +0 -1
  141. package/dist/loopback-host.d.ts +0 -20
  142. package/dist/loopback-host.d.ts.map +0 -1
  143. package/dist/loopback-host.js +0 -245
  144. package/dist/loopback-host.js.map +0 -1
  145. package/dist/loopback-preview.d.ts +0 -19
  146. package/dist/loopback-preview.d.ts.map +0 -1
  147. package/dist/loopback-preview.js +0 -232
  148. package/dist/loopback-preview.js.map +0 -1
  149. package/dist/native-rtc-helper.d.ts +0 -14
  150. package/dist/native-rtc-helper.d.ts.map +0 -1
  151. package/dist/native-rtc-helper.js +0 -575
  152. package/dist/native-rtc-helper.js.map +0 -1
  153. package/dist/remote-api-proxy.d.ts +0 -17
  154. package/dist/remote-api-proxy.d.ts.map +0 -1
  155. package/dist/remote-api-proxy.js +0 -451
  156. package/dist/remote-api-proxy.js.map +0 -1
  157. package/dist/remote-directory-browser.d.ts +0 -16
  158. package/dist/remote-directory-browser.d.ts.map +0 -1
  159. package/dist/remote-directory-browser.js +0 -48
  160. package/dist/remote-directory-browser.js.map +0 -1
  161. package/dist/remote-file-content-provider.d.ts +0 -48
  162. package/dist/remote-file-content-provider.d.ts.map +0 -1
  163. package/dist/remote-file-content-provider.js +0 -93
  164. package/dist/remote-file-content-provider.js.map +0 -1
  165. package/dist/remote-typert-gateway.d.ts +0 -20
  166. package/dist/remote-typert-gateway.d.ts.map +0 -1
  167. package/dist/remote-typert-gateway.js +0 -334
  168. package/dist/remote-typert-gateway.js.map +0 -1
  169. package/dist/rpc-binary-attachments.d.ts +0 -33
  170. package/dist/rpc-binary-attachments.d.ts.map +0 -1
  171. package/dist/rpc-binary-attachments.js +0 -142
  172. package/dist/rpc-binary-attachments.js.map +0 -1
  173. package/dist/rpc-router.d.ts +0 -31
  174. package/dist/rpc-router.d.ts.map +0 -1
  175. package/dist/rpc-router.js +0 -201
  176. package/dist/rpc-router.js.map +0 -1
  177. package/dist/safe-error.d.ts +0 -8
  178. package/dist/safe-error.d.ts.map +0 -1
  179. package/dist/safe-error.js +0 -20
  180. package/dist/safe-error.js.map +0 -1
  181. package/dist/server-api.d.ts +0 -109
  182. package/dist/server-api.d.ts.map +0 -1
  183. package/dist/server-api.js +0 -520
  184. package/dist/server-api.js.map +0 -1
  185. package/dist/server-connection.d.ts +0 -79
  186. package/dist/server-connection.d.ts.map +0 -1
  187. package/dist/server-connection.js +0 -1023
  188. package/dist/server-connection.js.map +0 -1
  189. package/dist/server-credentials.d.ts +0 -55
  190. package/dist/server-credentials.d.ts.map +0 -1
  191. package/dist/server-credentials.js +0 -108
  192. package/dist/server-credentials.js.map +0 -1
  193. package/dist/service.d.ts +0 -151
  194. package/dist/service.d.ts.map +0 -1
  195. package/dist/service.js +0 -448
  196. package/dist/service.js.map +0 -1
  197. package/dist/session-format-compat.d.ts +0 -3
  198. package/dist/session-format-compat.d.ts.map +0 -1
  199. package/dist/session-format-compat.js +0 -183
  200. package/dist/session-format-compat.js.map +0 -1
  201. package/dist/status-stream.d.ts +0 -48
  202. package/dist/status-stream.d.ts.map +0 -1
  203. package/dist/status-stream.js +0 -133
  204. package/dist/status-stream.js.map +0 -1
  205. package/dist/terminal-policy.d.ts +0 -21
  206. package/dist/terminal-policy.d.ts.map +0 -1
  207. package/dist/terminal-policy.js +0 -68
  208. package/dist/terminal-policy.js.map +0 -1
  209. package/dist/tui-command.d.ts +0 -13
  210. package/dist/tui-command.d.ts.map +0 -1
  211. package/dist/tui-command.js +0 -392
  212. package/dist/tui-command.js.map +0 -1
  213. package/dist/typert-gateway-contract.d.ts +0 -59
  214. package/dist/typert-gateway-contract.d.ts.map +0 -1
  215. package/dist/typert-gateway-contract.js +0 -2
  216. package/dist/typert-gateway-contract.js.map +0 -1
  217. package/dist/typert-gateway-switch.d.ts +0 -85
  218. package/dist/typert-gateway-switch.d.ts.map +0 -1
  219. package/dist/typert-gateway-switch.js +0 -448
  220. package/dist/typert-gateway-switch.js.map +0 -1
  221. package/dist/types.d.ts +0 -20
  222. package/dist/types.d.ts.map +0 -1
  223. package/dist/types.js +0 -2
  224. package/dist/types.js.map +0 -1
  225. package/dist/version.d.ts +0 -12
  226. package/dist/version.d.ts.map +0 -1
  227. package/dist/version.js +0 -12
  228. package/dist/version.js.map +0 -1
  229. package/dist/werift-rtc.d.ts +0 -121
  230. package/dist/werift-rtc.d.ts.map +0 -1
  231. package/dist/werift-rtc.js +0 -490
  232. package/dist/werift-rtc.js.map +0 -1
@@ -1,1768 +0,0 @@
1
- import { LoopbackPreview } from './loopback-preview.js';
2
- import { CodexRemoteClient, RemoteClientCore } from '@dsh-remote/client-core';
3
- import { AdaptiveTransport, stunOnlyIceServers, } from '@dsh-remote/webrtc';
4
- import { ApiProxySwitch } from './api-proxy-switch.js';
5
- import { ClientSecureTransport } from './client-secure-transport.js';
6
- import { registerControlRoute } from './control-route.js';
7
- import { uuidV7 } from './ids.js';
8
- import { harnessSessionGeneration } from './harness-version.js';
9
- import { RemoteHarnessApiProxy } from './remote-api-proxy.js';
10
- import { RemoteTypertGateway } from './remote-typert-gateway.js';
11
- import { codexProjectWorkspaceId, CodexVirtualHarness, discoverCodexVirtualWorkspaces, } from './codex/virtual-harness.js';
12
- import { ServerApiError, } from './server-api.js';
13
- import { TypertGatewaySwitch } from './typert-gateway-switch.js';
14
- import { loadNodeRtcFactory } from './werift-rtc.js';
15
- import { safeErrorCode } from './safe-error.js';
16
- const REMOTE_COMMAND_LIST_MIN_VERSION = [0, 3, 16];
17
- const REMOTE_FILE_VIEWER_MIN_VERSION = [0, 3, 17];
18
- const DIRECT_WEBRTC_NEGOTIATE_TIMEOUT_MS = 12_000;
19
- const DIRECT_LAN_PROGRESS_DISPLAY_MS = 1_400;
20
- const HOST_AUTHORIZATION_ERRORS = new Set([
21
- 'ACCOUNT_AUTH_REQUIRED',
22
- 'AUTH_INVALID',
23
- 'DEVICE_OWNERSHIP_REQUIRED',
24
- 'DEVICE_REVOKED',
25
- 'TOKEN_EXPIRED',
26
- ]);
27
- /**
28
- * Failures a retry loop cannot resolve on its own.
29
- *
30
- * The Account authorization has to be redone by the user, so retrying only burns attempts and
31
- * would keep a boot restore alive forever on a device that is no longer signed in.
32
- */
33
- const CREDENTIAL_FAILURE_CODES = new Set([
34
- 'AUTH_REQUIRED',
35
- 'ACCOUNT_AUTH_REQUIRED',
36
- 'AUTH_INVALID',
37
- 'TOKEN_EXPIRED',
38
- 'DEVICE_NOT_FOUND',
39
- 'DEVICE_REVOKED',
40
- 'MEMBERSHIP_REQUIRED',
41
- ]);
42
- /**
43
- * How often an idle remote session proves its link is still there.
44
- *
45
- * A socket can end without either side being told: the peer is reaped, a NAT mapping expires, or a
46
- * network path black-holes the close. A client that never notices keeps rendering a remote session
47
- * that silently answers nothing, so it asks for one cheap answer on a fixed cadence.
48
- */
49
- const LIVENESS_INTERVAL_MS = 30_000;
50
- /** Cadence while the link is being rebuilt, so the next verdict arrives in seconds. */
51
- const FAST_RECONNECT_INTERVAL_MS = 5_000;
52
- /**
53
- * How long one proof may take before it counts as no answer at all.
54
- *
55
- * The check is a cheap read-only call over a link that is already established, so a healthy peer
56
- * answers in well under a second; a longer budget only postpones the verdict.
57
- */
58
- const LIVENESS_TIMEOUT_MS = 4_000;
59
- /** Unanswered proofs before giving up: the first rebuilds the link, the second falls back. */
60
- const LIVENESS_TOLERATED_FAILURES = 2;
61
- /** Codes the client core raises locally when an RPC never reached an answer. */
62
- const NO_ANSWER_CODES = new Set(['RPC_TIMEOUT', 'CLIENT_CLOSED', 'TRANSPORT_CLOSED', 'RPC_ABORTED']);
63
- /**
64
- * Whether a proof of life failed to reach the peer.
65
- *
66
- * The check asks for an answer, not for success, so the two outcomes are told apart by where the
67
- * error came from. An answer arrives as an error carrying the peer's own code (METHOD_NOT_FOUND,
68
- * FEATURE_NOT_SUPPORTED, ...). A local failure is either one of the core's own codes above or a raw
69
- * transport error with no code at all - a send that failed on a socket this process has not noticed
70
- * is closed. Counting that second kind as liveness would make the whole check useless exactly when
71
- * it matters.
72
- * @param error - the error the check rejected with.
73
- * @returns true when no answer arrived, so the transport must be treated as lost.
74
- */
75
- export function livenessProbeLost(error) {
76
- const code = typeof error === 'object' && error !== null && 'code' in error
77
- ? error.code
78
- : undefined;
79
- if (typeof code !== 'string')
80
- return true;
81
- return NO_ANSWER_CODES.has(code);
82
- }
83
- export class ClientModeRuntime {
84
- config;
85
- identities;
86
- server;
87
- logger;
88
- host;
89
- rtcFactoryProvider;
90
- targetStore;
91
- preview;
92
- identity;
93
- connected;
94
- /**
95
- * Set when a remote session dropped and the runtime fell back to local.
96
- *
97
- * The mode then reads 'local', which is what every "return to local" control is
98
- * gated on, so without this the user is left in a stale remote view with no way
99
- * back except signing out.
100
- */
101
- fellBackToLocal = false;
102
- /**
103
- * Identifies the live reconnect loop.
104
- *
105
- * A dropped transport starts one; anything else that settles the connection —
106
- * the user returning to local, a logout, a fresh connect — bumps it so the loop
107
- * stops instead of fighting the newer decision.
108
- */
109
- remoteReconnectRun = 0;
110
- pendingWorkspaceSelection;
111
- /**
112
- * Transport a running fast reconnect is replacing.
113
- *
114
- * The rebuild opens its own control connection and the Server closes the older one for the same
115
- * device, so that close belongs to our own replacement. Reading it as a lost peer is what made the
116
- * fast level escalate itself into the fallback before it could ever succeed.
117
- */
118
- supersededClient;
119
- /**
120
- * True while a fast reconnect is rebuilding the link.
121
- *
122
- * The probe must not judge the link in the middle of its own replacement: the Server closes the
123
- * older connection for the device, so a check that ran then would read our replacement's side effect
124
- * as a second miss and escalate the level that is busy recovering. The rebuild's own outcome decides
125
- * first; only once it has settled does the cadence resume judging.
126
- */
127
- fastRebuildInFlight = false;
128
- /**
129
- * The last workspace the user opened for a Host.
130
- *
131
- * Kept so a reconnect can republish it: re-selecting the workspace is what makes the native UI
132
- * re-read its session list, and without it a list poisoned by the outage stays wrong even after
133
- * the link is back.
134
- */
135
- lastWorkspaceSelection;
136
- codexVirtual;
137
- proxySwitch;
138
- gatewaySwitch;
139
- codexStreams = new Map();
140
- connectionProgress;
141
- connectionProgressRun = 0;
142
- /**
143
- * Host a boot is trying to restore, reported to the UI while the retry loop runs.
144
- *
145
- * Nothing is connected yet, so without this the window would show the local shell while the
146
- * user is still looking at the remote workspace they left.
147
- */
148
- /**
149
- * Recovery in progress, and which kind.
150
- *
151
- * `restore` is a start that is reconnecting to the recorded target, `fast` keeps the session on
152
- * screen while its link is rebuilt, and `fallback` is the last resort that returns the user to
153
- * the local shell. The UI shows all three, so a reconnect is never invisible, and the retry loop
154
- * stops as soon as the user asks for local.
155
- */
156
- reconnecting;
157
- /** Periodic proof of life for the live remote session; absent while nothing is connected. */
158
- livenessTimer;
159
- livenessInFlight = false;
160
- livenessFailures = 0;
161
- closed = false;
162
- constructor(config, identities, server, apiProxy, typertGateway, logger, host, rtcFactoryProvider = loadNodeRtcFactory, targetStore) {
163
- this.config = config;
164
- this.identities = identities;
165
- this.server = server;
166
- this.logger = logger;
167
- this.host = host;
168
- this.rtcFactoryProvider = rtcFactoryProvider;
169
- this.targetStore = targetStore;
170
- this.proxySwitch = apiProxy === undefined ? undefined : new ApiProxySwitch(apiProxy);
171
- this.gatewaySwitch = new TypertGatewaySwitch(typertGateway);
172
- // Serve the local shell while no peer session is live. Otherwise a remote-mode
173
- // boot routes its own local services at a peer that may not be there, and the
174
- // shell never finishes activating.
175
- this.gatewaySwitch.setRemoteAvailability(() => this.connected !== undefined);
176
- }
177
- async start() {
178
- if (this.closed)
179
- throw new Error('client remote-mode runtime is closed');
180
- this.identity = await this.identities.loadOrCreate(this.config.deviceName);
181
- this.server.bindIdentity(this.identity);
182
- this.proxySwitch?.install();
183
- this.gatewaySwitch.install();
184
- this.logger.info('client remote-mode identity ready', {
185
- deviceId: shortId(this.identity.deviceId),
186
- fingerprint: this.identity.fingerprint,
187
- });
188
- // A previously authorized Client should make the local Host controllable
189
- // on startup as well. Do not register an anonymous Client just to probe:
190
- // only persisted Client credentials opt into this default.
191
- if (this.config.hostControl?.enabled !== false
192
- && this.host !== undefined
193
- && this.server.hasStoredAuthorization !== undefined) {
194
- try {
195
- if (await this.server.hasStoredAuthorization()
196
- && (this.host.hasStoredAuthorization === undefined || !await this.host.hasStoredAuthorization())) {
197
- await this.authorizeHostByDefault();
198
- }
199
- }
200
- catch (error) {
201
- this.logger.warn('automatic Host authorization failed', { code: safeErrorCode(error) });
202
- }
203
- }
204
- }
205
- /**
206
- * Whether this installation already holds stored Server credentials for its
207
- * Client identity.
208
- *
209
- * This is the local answer to "is this installation signed in", available
210
- * without contacting the Server, so the UI can choose its panel immediately
211
- * instead of inferring the answer from a failed network round trip.
212
- */
213
- async hasStoredAuthorization() {
214
- return this.server.hasStoredAuthorization === undefined
215
- ? false
216
- : await this.server.hasStoredAuthorization();
217
- }
218
- async authorizeHostByDefault() {
219
- try {
220
- if (this.host === undefined)
221
- return;
222
- if (this.config.hostControl?.enabled === false)
223
- return;
224
- const status = this.host.hostStatus();
225
- if (status.authorized)
226
- return;
227
- // Stored credentials the Server has already rejected must not block
228
- // re-authorization. A credential left over from another account — for
229
- // example after a Server state migration — would otherwise keep the Host
230
- // unregistered while the UI keeps telling the user to authorize again.
231
- const rejected = status.error !== undefined && HOST_AUTHORIZATION_ERRORS.has(status.error);
232
- if (!rejected && this.host.hasStoredAuthorization !== undefined && await this.host.hasStoredAuthorization())
233
- return;
234
- const credentials = await this.server.authenticate(this.requireIdentity());
235
- await this.host.authorizeHostAsOwned(credentials.accessToken, credentials.account);
236
- }
237
- catch (error) {
238
- this.logger.warn('automatic Host authorization failed', { code: safeErrorCode(error) });
239
- }
240
- }
241
- registerControl(connection, webServer) {
242
- return registerControlRoute(connection, (endpoint, payload, signal) => this.handleControl(endpoint, payload, signal), webServer);
243
- }
244
- status() {
245
- const targetStatus = this.gatewaySwitch.supportsCarrier()
246
- ? this.gatewaySwitch.status()
247
- : this.proxySwitch?.status() ?? this.gatewaySwitch.status();
248
- return {
249
- available: this.config.serverUrl !== undefined,
250
- identityReady: this.identity !== undefined,
251
- deviceId: this.identity?.deviceId,
252
- deviceName: this.identity?.name,
253
- serverUrl: this.config.serverUrl,
254
- ...targetStatus,
255
- connected: this.connected !== undefined,
256
- fellBackToLocal: this.fellBackToLocal,
257
- ...(this.reconnecting === undefined ? {} : { reconnecting: { ...this.reconnecting } }),
258
- transport: this.connected?.client.getStats().mode ?? 'Disconnected',
259
- connectedTargetDeviceId: this.connected?.target.deviceId,
260
- preferredTransports: this.config.forceRelay ? ['relay'] : ['lan', 'p2p', 'turn', 'relay'],
261
- ...(this.connectionProgress === undefined ? {} : {
262
- connectionProgress: {
263
- targetDeviceId: this.connectionProgress.targetDeviceId,
264
- phase: this.connectionProgress.phase,
265
- ...(this.connectionProgress.activeTransports === undefined
266
- ? {}
267
- : { activeTransports: [...this.connectionProgress.activeTransports] }),
268
- },
269
- }),
270
- remoteFeatures: this.connected?.features ?? remoteHostFeatures(),
271
- ...(this.pendingWorkspaceSelection === undefined
272
- ? {}
273
- : { workspaceSelection: { ...this.pendingWorkspaceSelection } }),
274
- backend: this.codexVirtual === undefined ? 'harness' : 'codex',
275
- hostAuthorizationAvailable: this.host !== undefined,
276
- ...(this.host === undefined ? {} : { host: this.host.hostStatus() }),
277
- };
278
- }
279
- async closePreview() {
280
- const preview = this.preview;
281
- this.preview = undefined;
282
- await preview?.close();
283
- }
284
- async detailedStatus() {
285
- const connected = this.connected;
286
- if (connected === undefined || this.identity === undefined)
287
- return this.status();
288
- const details = await connected.transport.connectionDetails();
289
- if (this.connected !== connected)
290
- return this.status();
291
- return {
292
- ...this.status(),
293
- network: {
294
- ...details,
295
- local: {
296
- deviceId: this.identity.deviceId,
297
- name: this.identity.name,
298
- platform: process.platform,
299
- },
300
- remote: {
301
- deviceId: connected.target.deviceId,
302
- name: connected.target.name,
303
- platform: connected.target.platform,
304
- },
305
- },
306
- };
307
- }
308
- async devices() {
309
- this.assertHostAuthorizationForDeviceDiscovery();
310
- this.requireIdentity();
311
- const serverDevices = await this.server.listDevices();
312
- const remoteDevices = serverDevices.filter(device => device.deviceId !== this.host?.hostStatus().deviceId);
313
- return Promise.all(remoteDevices.map(async (device) => {
314
- await this.authorizeHostPeer(device);
315
- const presence = await this.server.presenceFor(device.deviceId).catch(() => ({ online: false }));
316
- return { ...device, ...presence };
317
- }));
318
- }
319
- /**
320
- * Device discovery is exposed through the local app control route. When this
321
- * installation also runs a Host, keep that route closed after the Host's
322
- * Server credential has become terminally invalid. The Client credential can
323
- * remain usable for a short time after a revoke, so checking only
324
- * `ClientServerApi.listDevices()` would otherwise leak the device directory
325
- * from a Host that the user has already been told to re-authorize.
326
- */
327
- assertHostAuthorizationForDeviceDiscovery() {
328
- const status = this.host?.hostStatus();
329
- if (status === undefined || status.error === undefined || !HOST_AUTHORIZATION_ERRORS.has(status.error))
330
- return;
331
- const message = status.error === 'DEVICE_REVOKED'
332
- ? 'The local Host was revoked on the Server. Sign out and authorize this Host again.'
333
- : 'The local Host authorization is no longer valid. Sign out and authorize this Host again.';
334
- throw new ClientModeError(status.error, message);
335
- }
336
- async authorizeClientWithAccount(email, password) {
337
- let authorization;
338
- try {
339
- authorization = await this.server.authorizeWithAccount(this.requireIdentity(), email, password);
340
- }
341
- catch (error) {
342
- if (!(error instanceof ServerApiError) || error.code !== 'DEVICE_REVOKED')
343
- throw error;
344
- this.identity = await this.identities.reset(this.config.deviceName);
345
- this.server.bindIdentity(this.identity);
346
- authorization = await this.server.authorizeWithAccount(this.identity, email, password);
347
- }
348
- await this.authorizeHostByDefault();
349
- this.logger.info('Client account authorized');
350
- return authorization;
351
- }
352
- async startClientOAuthQrLogin(provider) {
353
- return this.server.startOAuthQrLogin(provider);
354
- }
355
- async pollClientOAuthQrLogin(qrId) {
356
- const result = await this.server.pollOAuthQrLogin(this.requireIdentity(), qrId, async () => {
357
- this.identity = await this.identities.reset(this.config.deviceName);
358
- this.server.bindIdentity(this.identity);
359
- this.logger.info('Rotated revoked Client identity before QR authorization retry');
360
- return this.identity;
361
- });
362
- if (result.status === 'complete')
363
- this.logger.info('Client account authorized with QR login');
364
- if (result.status === 'complete')
365
- await this.authorizeHostByDefault();
366
- return result;
367
- }
368
- /**
369
- * Stop this Client from being authorized, keeping its device identity.
370
- *
371
- * The device is deliberately *not* revoked and the identity is deliberately
372
- * *not* rotated. Signing out used to revoke the device, which forced a new
373
- * identity on the next sign-in and registered a second device for the same
374
- * installation; an account holds at most 256 devices, so signing out often
375
- * enough could exhaust it. Keeping the row also means the next sign-in reuses
376
- * it, and the server invalidates the previous tokens at that point.
377
- *
378
- * The cost, by choice: while signed out the device stays in the account and
379
- * its old tokens stay valid until the next sign-in or their expiry, so signing
380
- * out is no longer a way to cut a leaked token off immediately. Removing the
381
- * device for good is an operator action on the server's state file.
382
- */
383
- async clearClientAuthorization() {
384
- const previous = this.connected;
385
- this.connected = undefined;
386
- this.connectionProgress = undefined;
387
- this.pendingWorkspaceSelection = undefined;
388
- await this.closeCodexVirtual();
389
- this.proxySwitch?.selectLocal();
390
- await this.closePreview();
391
- this.gatewaySwitch.selectLocal();
392
- await this.closeCodexStreams(previous?.client);
393
- await previous?.client.close().catch(() => undefined);
394
- // A sign-out ends the session for good, so no reconnect loop may keep trying.
395
- this.remoteReconnectRun += 1;
396
- // Clear the in-memory authorization as well as the stored credential. The
397
- // caller clears the credential file, but this API also caches the
398
- // authorization in memory, and a stale copy keeps reporting the Client as
399
- // authorized — which stops the Host from re-authorizing and leaves the
400
- // connection retrying tokens the Server no longer accepts.
401
- await this.server.clearAuthorization();
402
- }
403
- async setHostAuthorization(enabled) {
404
- if (this.host === undefined)
405
- throw new ClientModeError('METHOD_NOT_ALLOWED', 'This plugin is not running as a Host.');
406
- if (!enabled) {
407
- await this.host.clearHostAuthorization();
408
- return this.status();
409
- }
410
- const credentials = await this.server.authenticate(this.requireIdentity());
411
- await this.host.authorizeHostAsOwned(credentials.accessToken, credentials.account);
412
- return this.status();
413
- }
414
- async setMode(mode, targetDeviceId, signal) {
415
- if (mode === 'local') {
416
- await this.closeCodexVirtual();
417
- this.proxySwitch?.selectLocal();
418
- await this.closePreview();
419
- this.gatewaySwitch.selectLocal();
420
- const previous = this.connected;
421
- this.connected = undefined;
422
- this.connectionProgress = undefined;
423
- this.pendingWorkspaceSelection = undefined;
424
- // The user asked for local, so the next remote session starts from a fresh workspace choice.
425
- this.lastWorkspaceSelection = undefined;
426
- await this.closeCodexStreams(previous?.client);
427
- await previous?.client.close().catch(() => undefined);
428
- // Returning to local is the answer to a dropped session, so the record of
429
- // that drop must not outlive it: otherwise the exit affordances stay on
430
- // screen after the user has already acted on them. Stop any pending
431
- // reconnect too — the user asked for local, not for a retry.
432
- this.fellBackToLocal = false;
433
- this.reconnecting = undefined;
434
- this.stopLivenessWatch();
435
- this.remoteReconnectRun += 1;
436
- await this.rememberTarget({ mode: 'local' });
437
- this.logger.info('Harness target switched', { mode: 'local' });
438
- return this.status();
439
- }
440
- if (targetDeviceId === undefined || targetDeviceId.length === 0) {
441
- throw new ClientModeError('INVALID_MESSAGE', 'A targetDeviceId is required for remote mode.');
442
- }
443
- const next = await this.connect(targetDeviceId, signal);
444
- try {
445
- this.assertRemoteCompatible(next);
446
- }
447
- catch (error) {
448
- this.clearConnectionProgress(next.progressRunId);
449
- await next.client.close().catch(() => undefined);
450
- throw error;
451
- }
452
- const previous = this.connected;
453
- await this.closePreview();
454
- this.connected = next;
455
- this.clearConnectionProgress(next.progressRunId);
456
- this.pendingWorkspaceSelection = undefined;
457
- await this.closeCodexVirtual();
458
- this.selectRemoteTarget(next);
459
- // A fresh remote session clears the record of an earlier dropped one.
460
- this.fellBackToLocal = false;
461
- this.reconnecting = undefined;
462
- await this.rememberTarget({ mode: 'remote', hostDeviceId: next.target.deviceId, hostName: next.target.name });
463
- await this.closeCodexStreams(previous?.client);
464
- await previous?.client.close().catch(() => undefined);
465
- this.logger.info('Harness target switched', { mode: 'remote', targetDeviceId: shortId(next.target.deviceId) });
466
- return this.status();
467
- }
468
- /**
469
- * Prove the live remote link still answers, and act on the result.
470
- *
471
- * Only a missing answer counts as loss: the peer's own error (a refusal, an unknown method) came
472
- * back over the same link and therefore proves it is there.
473
- *
474
- * The two recovery levels differ in what the user keeps. The first miss rebuilds the link in
475
- * place, so the session, its workspace selection and the remote carriers all stay; the second
476
- * gives up and returns to the local shell.
477
- */
478
- async verifyRemoteLiveness() {
479
- const connected = this.connected;
480
- if (connected === undefined || this.livenessInFlight || this.fastRebuildInFlight)
481
- return;
482
- this.livenessInFlight = true;
483
- try {
484
- await connected.client.rpc('harness.transport.describe', {}, undefined, { timeoutMs: LIVENESS_TIMEOUT_MS });
485
- this.livenessFailures = 0;
486
- if (this.reconnecting?.phase === 'fast')
487
- this.finishReconnect('the link answered again');
488
- }
489
- catch (error) {
490
- if (!livenessProbeLost(error)) {
491
- // Any answer proves the peer is alive, including a refusal.
492
- this.livenessFailures = 0;
493
- return;
494
- }
495
- this.livenessFailures += 1;
496
- this.logger.warn('remote Harness liveness check found no answer', {
497
- targetDeviceId: shortId(connected.target.deviceId),
498
- attempt: this.livenessFailures,
499
- });
500
- if (this.livenessFailures === 1) {
501
- await this.enterFastReconnect(connected.target.deviceId, connected.target.name);
502
- return;
503
- }
504
- if (this.livenessFailures >= LIVENESS_TOLERATED_FAILURES) {
505
- this.handleRemoteTransportLost(connected.client, connected.target.deviceId, 'unanswered-twice');
506
- }
507
- }
508
- finally {
509
- this.livenessInFlight = false;
510
- }
511
- }
512
- /**
513
- * Rebuild the link while the session stays on screen.
514
- *
515
- * This is what separates the two recovery levels: nothing is handed back to the local shell, so a
516
- * link that recovers does not cost the user the view they were working in.
517
- * @param targetDeviceId - the Host to rebuild the link to.
518
- */
519
- async enterFastReconnect(targetDeviceId, targetName) {
520
- if (this.reconnecting !== undefined)
521
- return;
522
- this.reconnecting = { targetDeviceId, ...(targetName === undefined ? {} : { targetName }), phase: 'fast' };
523
- this.logger.warn('remote Harness link stopped answering; reconnecting in place', {
524
- targetDeviceId: shortId(targetDeviceId),
525
- });
526
- // Faster probes while recovering: the next miss is what decides recovery against the fallback.
527
- this.armLivenessWatch(FAST_RECONNECT_INTERVAL_MS);
528
- await this.reestablish(targetDeviceId);
529
- }
530
- /**
531
- * Build a new transport for the session already on screen.
532
- *
533
- * The carriers hold the previous client, so they are rebound to the new one before the old client
534
- * is closed; leaving it open would keep pointing remote calls at a dead transport.
535
- * @param targetDeviceId - the Host to reconnect to.
536
- * @returns true when a new session is in place.
537
- */
538
- async reestablish(targetDeviceId) {
539
- const previous = this.connected;
540
- // From here until the new session is in place, a close of the old transport is our own doing and
541
- // the liveness cadence stops judging the link.
542
- this.supersededClient = previous?.client;
543
- this.fastRebuildInFlight = true;
544
- try {
545
- const next = await this.connect(targetDeviceId);
546
- if (previous === undefined) {
547
- // The user asked for local while this attempt was running.
548
- this.supersededClient = undefined;
549
- await next.client.close().catch(() => undefined);
550
- return false;
551
- }
552
- await this.closePreview();
553
- this.connected = next;
554
- this.clearConnectionProgress(next.progressRunId);
555
- this.selectRemoteTarget(next);
556
- await this.closeCodexStreams(previous.client);
557
- await previous.client.close().catch(() => undefined);
558
- this.supersededClient = undefined;
559
- this.finishReconnect('link re-established');
560
- return true;
561
- }
562
- catch (error) {
563
- this.supersededClient = undefined;
564
- this.logger.warn('fast reconnect attempt failed', {
565
- targetDeviceId: shortId(targetDeviceId),
566
- code: safeErrorCode(error),
567
- });
568
- return false;
569
- }
570
- finally {
571
- this.fastRebuildInFlight = false;
572
- }
573
- }
574
- rememberWorkspaceSelection(selection) {
575
- this.pendingWorkspaceSelection = selection;
576
- this.lastWorkspaceSelection = { ...selection };
577
- }
578
- /**
579
- * Republish the workspace selection so the native UI re-reads its remote session list.
580
- *
581
- * The client half consumes status.workspaceSelection and reconnects that workspace; that refresh is
582
- * what replaces a list the outage had filled with local answers.
583
- * @param targetDeviceId - the Host the reconnect finished against.
584
- */
585
- restoreWorkspaceSelection(targetDeviceId) {
586
- const selection = this.lastWorkspaceSelection;
587
- if (selection === undefined || selection.targetDeviceId !== targetDeviceId)
588
- return;
589
- this.pendingWorkspaceSelection = { ...selection };
590
- this.logger.info('republishing the workspace selection to re-read the remote session list', {
591
- targetDeviceId: shortId(targetDeviceId),
592
- workspaceId: selection.workspaceId,
593
- });
594
- }
595
- finishReconnect(reason) {
596
- const target = this.reconnecting?.targetDeviceId;
597
- if (target === undefined)
598
- return;
599
- this.reconnecting = undefined;
600
- this.livenessFailures = 0;
601
- this.armLivenessWatch(LIVENESS_INTERVAL_MS);
602
- this.restoreWorkspaceSelection(target);
603
- this.logger.info('remote Harness reconnect finished', { targetDeviceId: shortId(target), reason });
604
- }
605
- /**
606
- * Check the live session now, outside the cadence.
607
- *
608
- * Used when the page becomes visible again, which is when a suspended client is most likely to be
609
- * holding a link that already ended.
610
- * @returns the status after the check.
611
- */
612
- async verifyRemoteConnection() {
613
- await this.verifyRemoteLiveness();
614
- return this.status();
615
- }
616
- armLivenessWatch(intervalMs) {
617
- if (this.livenessTimer !== undefined)
618
- clearInterval(this.livenessTimer);
619
- // The tick reads the live session, so a reconnected client is checked without re-arming.
620
- const timer = setInterval(() => { void this.verifyRemoteLiveness(); }, intervalMs);
621
- // A background check must never hold the process - or a test run - open.
622
- timer.unref?.();
623
- this.livenessTimer = timer;
624
- }
625
- stopLivenessWatch() {
626
- if (this.livenessTimer !== undefined)
627
- clearInterval(this.livenessTimer);
628
- this.livenessTimer = undefined;
629
- this.livenessFailures = 0;
630
- this.livenessInFlight = false;
631
- }
632
- /**
633
- * Shared cleanup for a session whose transport is gone.
634
- *
635
- * A close event and an exhausted liveness check must leave exactly the same state behind, so both
636
- * paths run this. The session is gone for good here, which is why the phase becomes 'fallback' and
637
- * the retry loop keeps the UI saying that it is reconnecting.
638
- * @param client - the client that was connected.
639
- * @param targetDeviceId - the Host it was bound to.
640
- */
641
- handleRemoteTransportLost(client, targetDeviceId, reason) {
642
- if (this.connected?.client !== client)
643
- return;
644
- this.supersededClient = undefined;
645
- const targetName = this.connected.target.name;
646
- // A closed transport is the disaster fallback: the session is gone and the retry loop takes over.
647
- // Only an unanswered liveness check rebuilds in place first, so a peer that merely went quiet
648
- // keeps the user's view while its link is re-established.
649
- this.stopLivenessWatch();
650
- void this.closePreview();
651
- this.connected = undefined;
652
- this.connectionProgress = undefined;
653
- this.pendingWorkspaceSelection = undefined;
654
- void this.closeCodexVirtual();
655
- this.proxySwitch?.selectLocal();
656
- this.gatewaySwitch.selectLocal();
657
- this.fellBackToLocal = true;
658
- this.reconnecting = { targetDeviceId, ...(targetName === undefined ? {} : { targetName }), phase: 'fallback' };
659
- void client.close().catch(() => undefined);
660
- this.logger.warn('remote Harness transport lost; reconnecting', {
661
- targetDeviceId: shortId(targetDeviceId),
662
- reason,
663
- });
664
- void this.reconnectRemoteSession(targetDeviceId);
665
- }
666
- /**
667
- * Re-establish a remote session whose transport closed.
668
- *
669
- * The UI keeps rendering the remote session after the transport is gone, so
670
- * without this the user faces a session that silently ignores everything and has
671
- * to exit and pick the Host again — which is what a suspended and resumed client
672
- * used to require every time. Retry the same Host with backoff; a loop that is
673
- * superseded, or one whose session came back another way, stops quietly.
674
- * @param targetDeviceId - the Host the dropped session was bound to.
675
- */
676
- async reconnectRemoteSession(targetDeviceId) {
677
- const run = ++this.remoteReconnectRun;
678
- // Fast attempts first, then a steady low rate. Timers do not run while a
679
- // client is suspended, so a pending wait simply lands when it comes back —
680
- // which is what makes a backgrounded phone reconnect on its own. Keeping the
681
- // loop alive matters for the other order too: attempts spent while the network
682
- // was down must not leave the session dead until the user acts.
683
- const fastDelays = [1_000, 2_000, 4_000, 8_000, 15_000];
684
- let attempt = 0;
685
- for (;;) {
686
- const wait = fastDelays[attempt] ?? 30_000;
687
- await new Promise(resolve => { setTimeout(resolve, wait); });
688
- if (run !== this.remoteReconnectRun)
689
- return;
690
- if (this.connected !== undefined)
691
- return;
692
- try {
693
- await this.setMode('remote', targetDeviceId);
694
- this.restoreWorkspaceSelection(targetDeviceId);
695
- this.logger.info('remote Harness session reconnected', { targetDeviceId: shortId(targetDeviceId) });
696
- return;
697
- }
698
- catch (error) {
699
- const code = safeErrorCode(error);
700
- // Credentials that are missing or refused cannot be fixed by waiting, and a boot restore
701
- // would otherwise retry an unauthorized connection forever. Stop and let the user sign in.
702
- if (code !== undefined && CREDENTIAL_FAILURE_CODES.has(code)) {
703
- this.logger.warn('remote Harness reconnect stopped: authorization is required', {
704
- targetDeviceId: shortId(targetDeviceId),
705
- code,
706
- });
707
- this.reconnecting = undefined;
708
- return;
709
- }
710
- // Report the early attempts, then only occasionally: a Host that stays
711
- // away would otherwise fill the log every half minute.
712
- if (attempt < 3 || attempt % 10 === 0) {
713
- this.logger.warn('remote Harness reconnect attempt failed', {
714
- targetDeviceId: shortId(targetDeviceId),
715
- attempt,
716
- code,
717
- });
718
- }
719
- }
720
- attempt += 1;
721
- }
722
- }
723
- /**
724
- * Persist the target a later boot may have to restore.
725
- *
726
- * A failure here must not fail a connect: the only cost is that a killed process comes back to
727
- * the local shell, which is where it would have been without this record.
728
- * @param target - the target to record.
729
- */
730
- async rememberTarget(target) {
731
- if (this.targetStore === undefined)
732
- return;
733
- try {
734
- await this.targetStore.save({
735
- ...target,
736
- ...(this.config.serverUrl === undefined ? {} : { serverUrl: this.config.serverUrl }),
737
- });
738
- }
739
- catch (error) {
740
- this.logger.warn('could not record the remote target', { code: safeErrorCode(error) });
741
- }
742
- }
743
- /**
744
- * Reconnect to the target this device was last using, with the usual backoff.
745
- *
746
- * A resumed app can miss the transport close entirely - Android may reclaim the process - so
747
- * nothing would start the retry loop and the user would face a local shell behind a remote
748
- * workspace view. Restoring the recorded target gives that case the same loop a dropped
749
- * transport gets. A target recorded for another Server is left alone: it is not reachable
750
- * through the configured one.
751
- * @returns true when a retry loop was started.
752
- */
753
- async restoreLastTarget() {
754
- if (this.closed || this.connected !== undefined)
755
- return false;
756
- const record = await this.targetStore?.load();
757
- if (record === undefined || record.mode !== 'remote' || record.hostDeviceId === undefined)
758
- return false;
759
- if (record.serverUrl !== undefined && record.serverUrl !== this.config.serverUrl) {
760
- this.logger.info('recorded remote target belongs to another Server; not restoring', {
761
- targetDeviceId: shortId(record.hostDeviceId),
762
- });
763
- return false;
764
- }
765
- this.reconnecting = {
766
- targetDeviceId: record.hostDeviceId,
767
- ...(record.hostName === undefined ? {} : { targetName: record.hostName }),
768
- phase: 'restore',
769
- };
770
- this.logger.info('restoring the remote target of the previous run', {
771
- targetDeviceId: shortId(record.hostDeviceId),
772
- });
773
- void this.reconnectRemoteSession(record.hostDeviceId);
774
- return true;
775
- }
776
- async listRemoteDirectory(targetDeviceId, path, signal) {
777
- const remote = await this.ensureConnected(targetDeviceId, signal);
778
- if (remote.features.remoteGateway) {
779
- const value = await new RemoteTypertGateway(remote.client).invoke({
780
- namespace: 'directoryPicker',
781
- method: 'list',
782
- args: path === undefined ? {} : { path },
783
- ...(signal === undefined ? {} : { signal }),
784
- });
785
- return value;
786
- }
787
- const api = new RemoteHarnessApiProxy(remote.client).api;
788
- const response = await api.host.listDirectory({
789
- rpcId: `remote-directory-${Date.now()}`,
790
- payload: path === undefined ? {} : { path },
791
- }, signal ?? new AbortController().signal);
792
- return unwrapNativeResult(response);
793
- }
794
- async listRemoteWorkspaces(targetDeviceId, signal) {
795
- const remote = await this.ensureConnected(targetDeviceId, signal);
796
- if (remote.features.remoteGateway) {
797
- return readRemoteWorkspaceBaseline(new RemoteTypertGateway(remote.client), signal);
798
- }
799
- const api = new RemoteHarnessApiProxy(remote.client).api;
800
- const response = await api.workspace.list({
801
- rpcId: `remote-workspaces-${Date.now()}`,
802
- payload: {},
803
- });
804
- const value = unwrapNativeResult(response);
805
- return value.items;
806
- }
807
- async openRemoteWorkspace(targetDeviceId, path, signal) {
808
- if (path.trim() === '')
809
- throw new ClientModeError('INVALID_MESSAGE', 'A remote working directory is required.');
810
- const remote = await this.ensureConnected(targetDeviceId, signal);
811
- const transport = this.selectHarnessRemoteTransport(remote);
812
- let workspace;
813
- if (transport === 'remoteGateway') {
814
- workspace = await new RemoteTypertGateway(remote.client).invoke({
815
- namespace: 'workspace',
816
- method: 'create',
817
- args: { request: { path } },
818
- ...(signal === undefined ? {} : { signal }),
819
- });
820
- }
821
- else {
822
- const api = new RemoteHarnessApiProxy(remote.client).api;
823
- const response = await api.workspace.create({
824
- rpcId: `remote-workspace-${Date.now()}`,
825
- payload: { path },
826
- });
827
- workspace = unwrapNativeResult(response);
828
- }
829
- await this.closeCodexVirtual();
830
- this.selectRemoteTarget(remote, transport);
831
- const workspaceId = workspaceRecordId(workspace.workspace);
832
- this.rememberWorkspaceSelection({ targetDeviceId: remote.target.deviceId, workspaceId });
833
- this.logger.info('Remote workspace opened', { targetDeviceId: shortId(remote.target.deviceId) });
834
- return { ...this.status(), workspace };
835
- }
836
- async listCodexWorkspaces(targetDeviceId, signal) {
837
- const remote = await this.ensureConnected(targetDeviceId, signal);
838
- remote.features = await probeRemoteHostFeatures(remote.client, remote.clientVersion);
839
- if (!remote.features.codex) {
840
- throw new ClientModeError('FEATURE_NOT_SUPPORTED', 'The selected Host does not provide CodeX workspaces.');
841
- }
842
- return discoverCodexVirtualWorkspaces(new CodexRemoteClient(remote.client), signal);
843
- }
844
- async openCodexWorkspace(targetDeviceId, workspaceId, signal) {
845
- const remote = await this.ensureConnected(targetDeviceId, signal);
846
- remote.features = await probeRemoteHostFeatures(remote.client, remote.clientVersion);
847
- if (!remote.features.codex) {
848
- throw new ClientModeError('FEATURE_NOT_SUPPORTED', 'The selected Host does not provide CodeX workspaces.');
849
- }
850
- this.assertLocalHarnessCarrierAvailable();
851
- const virtual = CodexVirtualHarness.remote(remote.client, {
852
- deviceId: remote.target.deviceId,
853
- name: remote.target.name,
854
- }, harnessSessionGeneration(this.host?.localHarnessVersion?.()), new RemoteTypertGateway(remote.client));
855
- let workspace;
856
- try {
857
- workspace = await virtual.selectWorkspace(workspaceId, signal);
858
- }
859
- catch {
860
- await virtual.close();
861
- throw new ClientModeError('WORKSPACE_NOT_FOUND', 'The selected CodeX workspace is no longer available.');
862
- }
863
- await this.closeCodexVirtual();
864
- this.codexVirtual = virtual;
865
- this.selectCodexTarget(virtual, remote);
866
- const preferredSessionId = await virtual.preferredSessionId(signal);
867
- this.rememberWorkspaceSelection({
868
- targetDeviceId: remote.target.deviceId,
869
- workspaceId,
870
- backend: 'codex',
871
- ...(preferredSessionId === undefined ? {} : { sessionId: preferredSessionId }),
872
- });
873
- this.logger.info('CodeX virtual workspace opened', { targetDeviceId: shortId(remote.target.deviceId) });
874
- return { ...this.status(), workspace };
875
- }
876
- async createCodexWorkspace(targetDeviceId, path, signal) {
877
- const trimmedPath = path.trim();
878
- if (trimmedPath === '')
879
- throw new ClientModeError('INVALID_MESSAGE', 'A CodeX project directory is required.');
880
- const remote = await this.ensureConnected(targetDeviceId, signal);
881
- remote.features = await probeRemoteHostFeatures(remote.client, remote.clientVersion);
882
- if (!remote.features.codex) {
883
- throw new ClientModeError('FEATURE_NOT_SUPPORTED', 'The selected Host does not provide CodeX workspaces.');
884
- }
885
- this.assertLocalHarnessCarrierAvailable();
886
- const result = record(await new CodexRemoteClient(remote.client).request('project/create', {
887
- name: remoteWorkspaceTitle(trimmedPath),
888
- roots: [{ path: trimmedPath }],
889
- idempotencyKey: uuidV7(),
890
- }, signal));
891
- const project = record(result.project);
892
- if (typeof project.id !== 'string' || project.id.length === 0) {
893
- throw new ClientModeError('INVALID_MESSAGE', 'The Host returned an invalid CodeX project.');
894
- }
895
- return this.openCodexWorkspace(targetDeviceId, codexProjectWorkspaceId(project.id), signal);
896
- }
897
- consumeWorkspaceSelection(selection) {
898
- // The client half opened this selection, so it is the workspace a later reconnect has to republish.
899
- // It can arrive from the browser's own stored selection rather than from workspaces.open, which is
900
- // why remembering it here - and not only where we publish it - is what makes the re-baseline work.
901
- this.lastWorkspaceSelection = { ...selection };
902
- const pending = this.pendingWorkspaceSelection;
903
- if (pending?.targetDeviceId === selection.targetDeviceId
904
- && pending.workspaceId === selection.workspaceId
905
- && (pending.backend ?? 'harness') === (selection.backend ?? 'harness')) {
906
- this.pendingWorkspaceSelection = undefined;
907
- }
908
- return this.status();
909
- }
910
- async close() {
911
- await this.closePreview();
912
- if (this.closed)
913
- return;
914
- this.closed = true;
915
- this.stopLivenessWatch();
916
- this.proxySwitch?.selectLocal();
917
- await this.closePreview();
918
- this.gatewaySwitch.selectLocal();
919
- this.pendingWorkspaceSelection = undefined;
920
- await this.closeCodexVirtual();
921
- await this.closeCodexStreams(this.connected?.client);
922
- await this.connected?.client.close().catch(() => undefined);
923
- this.connected = undefined;
924
- this.connectionProgress = undefined;
925
- this.proxySwitch?.restore();
926
- this.gatewaySwitch.restore();
927
- }
928
- async callRemoteFileViewer(endpoint, payload, signal) {
929
- const remote = this.connected;
930
- if (remote === undefined || this.status().mode !== 'remote') {
931
- throw new ClientModeError('REMOTE_NOT_CONNECTED', 'No Remote Host is selected.', true);
932
- }
933
- if (!remote.features.fileViewer) {
934
- throw new ClientModeError('FEATURE_NOT_SUPPORTED', 'The selected Remote Host does not support remote file viewing.');
935
- }
936
- return remote.client.rpc('fileviewer.call', { endpoint, payload }, signal);
937
- }
938
- activeRemote() {
939
- return this.connected;
940
- }
941
- activeCodexRemote() {
942
- const remote = this.activeRemote();
943
- if (remote === undefined)
944
- return undefined;
945
- if (!remote.features.codex) {
946
- return undefined;
947
- }
948
- return remote;
949
- }
950
- async openCodexStream(payload, signal) {
951
- const remote = this.activeCodexRemote();
952
- const value = record(payload);
953
- if (typeof value.streamId !== 'string' || value.streamId.length === 0 || value.streamId.length > 128
954
- || typeof value.threadId !== 'string' || value.threadId.length === 0) {
955
- throw new ClientModeError('INVALID_MESSAGE', 'A Codex stream and thread are required.');
956
- }
957
- if (this.codexStreams.has(value.streamId))
958
- throw new ClientModeError('REQUEST_CONFLICT', 'The Codex stream is already open.');
959
- let wake = () => undefined;
960
- const stream = {
961
- target: remote === undefined ? { kind: 'local' } : { kind: 'remote', client: remote.client },
962
- frames: [],
963
- unsubscribe: () => undefined,
964
- close: async () => {
965
- if (remote === undefined) {
966
- await this.host?.codexCloseStream?.({ streamId: value.streamId }).catch(() => undefined);
967
- return;
968
- }
969
- await remote.client.rpc('codex.app.stream.close', { streamId: value.streamId }).catch(() => undefined);
970
- },
971
- wake: () => wake(),
972
- };
973
- if (remote === undefined) {
974
- const host = this.requireLocalCodex();
975
- this.codexStreams.set(value.streamId, stream);
976
- try {
977
- const result = await host.codexOpenStream({ streamId: value.streamId, threadId: value.threadId }, this.publishLocalCodexFrame, signal);
978
- return result;
979
- }
980
- catch (error) {
981
- this.codexStreams.delete(value.streamId);
982
- stream.wake();
983
- throw error;
984
- }
985
- }
986
- stream.unsubscribe = remote.client.onEvent(event => {
987
- if (event.event === 'codex.app.frame' && isRecord(event.data) && event.data.streamId === value.streamId) {
988
- this.appendCodexFrame(stream, event.data);
989
- }
990
- if (event.event === 'codex.app.stream.closed' && isRecord(event.data) && event.data.streamId === value.streamId) {
991
- stream.closed = typeof event.data.reason === 'string' ? event.data.reason : 'closed';
992
- stream.wake();
993
- }
994
- });
995
- try {
996
- // Subscribe before opening the Host stream so the first App Server
997
- // notification cannot race past the loopback listener.
998
- await remote.client.rpc('codex.app.stream.open', { streamId: value.streamId, threadId: value.threadId }, signal);
999
- }
1000
- catch (error) {
1001
- stream.unsubscribe();
1002
- throw error;
1003
- }
1004
- this.codexStreams.set(value.streamId, stream);
1005
- return { opened: true, streamId: value.streamId, threadId: value.threadId };
1006
- }
1007
- publishLocalCodexFrame = async (event, data) => {
1008
- const streamId = data.streamId;
1009
- const stream = this.codexStreams.get(streamId);
1010
- if (stream === undefined || stream.target.kind !== 'local')
1011
- return;
1012
- if (event === 'codex.app.frame') {
1013
- this.appendCodexFrame(stream, data);
1014
- return;
1015
- }
1016
- const closed = data;
1017
- stream.closed = typeof closed.reason === 'string' ? closed.reason : 'closed';
1018
- stream.wake();
1019
- };
1020
- appendCodexFrame(stream, data) {
1021
- if (!isRecord(data) || !isRecord(data.frame) || typeof data.frame.method !== 'string')
1022
- return;
1023
- if (stream.frames.length >= 256) {
1024
- stream.closed = 'overflow';
1025
- }
1026
- else {
1027
- stream.frames.push({ method: data.frame.method, params: data.frame.params });
1028
- }
1029
- stream.wake();
1030
- }
1031
- localCodexAvailable() {
1032
- return this.host?.codexStatus?.().available === true;
1033
- }
1034
- requireLocalCodex() {
1035
- if (!this.localCodexAvailable()
1036
- || this.host?.codexCall === undefined
1037
- || this.host.codexRespond === undefined
1038
- || this.host.codexOpenStream === undefined
1039
- || this.host.codexCloseStream === undefined) {
1040
- throw new ClientModeError('FEATURE_NOT_SUPPORTED', 'Local CodeX is disabled or unavailable on this Host.');
1041
- }
1042
- return {
1043
- codexCall: this.host.codexCall.bind(this.host),
1044
- codexRespond: this.host.codexRespond.bind(this.host),
1045
- codexOpenStream: this.host.codexOpenStream.bind(this.host),
1046
- codexCloseStream: this.host.codexCloseStream.bind(this.host),
1047
- };
1048
- }
1049
- async nextCodexFrames(payload, signal) {
1050
- const value = record(payload);
1051
- if (typeof value.streamId !== 'string')
1052
- throw new ClientModeError('INVALID_MESSAGE', 'A Codex stream is required.');
1053
- const stream = this.codexStreams.get(value.streamId);
1054
- if (stream === undefined)
1055
- throw new ClientModeError('STREAM_NOT_FOUND', 'The Codex stream is not open.');
1056
- if (stream.frames.length === 0 && stream.closed === undefined)
1057
- await waitForCodexFrames(stream, signal);
1058
- const frames = stream.frames.splice(0, 100);
1059
- return {
1060
- streamId: value.streamId,
1061
- frames,
1062
- closed: stream.closed !== undefined,
1063
- ...(stream.closed === undefined ? {} : { reason: stream.closed }),
1064
- };
1065
- }
1066
- async closeCodexStream(payload) {
1067
- const value = record(payload);
1068
- if (typeof value.streamId !== 'string')
1069
- throw new ClientModeError('INVALID_MESSAGE', 'A Codex stream is required.');
1070
- const stream = this.codexStreams.get(value.streamId);
1071
- if (stream === undefined)
1072
- return { closed: false, streamId: value.streamId };
1073
- this.codexStreams.delete(value.streamId);
1074
- stream.unsubscribe();
1075
- stream.wake();
1076
- await stream.close();
1077
- return { closed: true, streamId: value.streamId };
1078
- }
1079
- async closeCodexStreams(client) {
1080
- const targets = [...this.codexStreams.entries()].filter(([, stream]) => (client === undefined || (stream.target.kind === 'remote' && stream.target.client === client)));
1081
- await Promise.all(targets.map(async ([streamId, stream]) => {
1082
- this.codexStreams.delete(streamId);
1083
- stream.unsubscribe();
1084
- stream.closed = 'peer-disconnected';
1085
- stream.wake();
1086
- await stream.close();
1087
- }));
1088
- }
1089
- selectRemoteTarget(remote, transport = this.selectHarnessRemoteTransport(remote)) {
1090
- const target = { deviceId: remote.target.deviceId, name: remote.target.name };
1091
- if (transport === 'remoteGateway') {
1092
- this.gatewaySwitch.selectRemote(this.remoteTypertGateway(remote), undefined, target);
1093
- return;
1094
- }
1095
- this.proxySwitch?.selectRemote(new RemoteHarnessApiProxy(remote.client, remote.harnessVersion).api, target);
1096
- this.gatewaySwitch.selectRemote(request => invokeRemoteCommand(remote.client, request), {
1097
- execute: true,
1098
- list: remote.features.commandList,
1099
- }, target);
1100
- }
1101
- remoteTypertGateway(remote) {
1102
- const localSessionGeneration = harnessSessionGeneration(this.host?.localHarnessVersion?.());
1103
- return new RemoteTypertGateway(remote.client, localSessionGeneration === 'v3' && remote.features.sessionFormat !== 3 ? 'legacy-to-v3' : undefined, remote.harnessVersion);
1104
- }
1105
- selectCodexTarget(virtual, remote) {
1106
- const target = { deviceId: remote.target.deviceId, name: remote.target.name };
1107
- // The Harness answers every `/api` endpoint once it is the Codex target, so give it
1108
- // the local carriers: everything outside the CodeX domain (the shell's settings
1109
- // bootstrap, plugin registry and account reads) has to describe this installation.
1110
- virtual.setLocalCarrier(this.gatewaySwitch.localCarrier());
1111
- if (this.gatewaySwitch.supportsCarrier()) {
1112
- this.gatewaySwitch.selectRemote(virtual, undefined, target);
1113
- return;
1114
- }
1115
- this.proxySwitch.selectRemote(virtual.api, target);
1116
- this.gatewaySwitch.selectRemote(request => virtual.invoke(request), { execute: true, list: true }, target);
1117
- }
1118
- async closeCodexVirtual() {
1119
- const virtual = this.codexVirtual;
1120
- this.codexVirtual = undefined;
1121
- await virtual?.close();
1122
- }
1123
- assertRemoteCompatible(remote) {
1124
- this.selectHarnessRemoteTransport(remote);
1125
- }
1126
- selectHarnessRemoteTransport(remote) {
1127
- const localRemoteGateway = this.gatewaySwitch.supportsCarrier();
1128
- const localSessionGeneration = harnessSessionGeneration(this.host?.localHarnessVersion?.());
1129
- if (localRemoteGateway && remote.features.remoteGateway) {
1130
- if (localSessionGeneration === 'v3' || remote.features.sessionFormat !== 3)
1131
- return 'remoteGateway';
1132
- throw new ClientModeError('HARNESS_VERSION_INCOMPATIBLE', 'The selected Host uses Harness Session V3, but this Client uses the legacy Typert Remote session format.');
1133
- }
1134
- if (this.proxySwitch !== undefined && remote.features.apiProxy)
1135
- return 'apiProxy';
1136
- throw new ClientModeError('HARNESS_VERSION_INCOMPATIBLE', localRemoteGateway
1137
- ? 'The selected Host does not provide a compatible Harness Typert Remote Gateway transport.'
1138
- : 'The selected Host does not provide the legacy Harness ApiProxy transport.');
1139
- }
1140
- assertLocalHarnessCarrierAvailable() {
1141
- if (this.gatewaySwitch.supportsCarrier() || this.proxySwitch !== undefined)
1142
- return;
1143
- throw new ClientModeError('HARNESS_VERSION_INCOMPATIBLE', 'This Client does not provide a compatible Harness carrier for the selected remote workspace.');
1144
- }
1145
- async connect(targetDeviceId, signal) {
1146
- signal?.throwIfAborted();
1147
- const progressRunId = this.connectionProgressRun + 1;
1148
- this.connectionProgressRun = progressRunId;
1149
- this.connectionProgress = { runId: progressRunId, targetDeviceId, phase: 'checking-host' };
1150
- const identity = this.requireIdentity();
1151
- let client;
1152
- try {
1153
- const serverDevice = (await this.server.listDevices()).find(device => device.deviceId === targetDeviceId);
1154
- if (serverDevice === undefined) {
1155
- throw new ClientModeError('MEMBERSHIP_REQUIRED', 'The selected Host is not authorized for this account.');
1156
- }
1157
- this.updateConnectionProgress(progressRunId, 'authorizing-peer');
1158
- const target = await this.authorizeHostPeer(serverDevice);
1159
- const presence = await this.server.presenceFor(targetDeviceId);
1160
- if (!presence.online)
1161
- throw new ClientModeError('HOST_OFFLINE', 'The selected Host is offline.', true);
1162
- const credentials = await this.server.authenticate(identity);
1163
- const rtcFactory = this.config.forceRelay
1164
- ? undefined
1165
- : await this.rtcFactoryProvider({ routeTargets: [this.server.baseUrl] }).catch(() => undefined);
1166
- if (!this.config.forceRelay && rtcFactory === undefined) {
1167
- this.logger.warn('remote Harness WebRTC backend unavailable; using relay', {
1168
- targetDeviceId: shortId(target.deviceId),
1169
- });
1170
- }
1171
- let webRtcFallback = false;
1172
- const createTransport = (attempt) => new AdaptiveTransport(websocketUrl(this.server.baseUrl), {
1173
- role: 'client',
1174
- deviceId: identity.deviceId,
1175
- accessToken: credentials.accessToken,
1176
- targetDeviceId,
1177
- forceRelay: this.config.forceRelay || attempt === 'relay',
1178
- preferredTransports: preferredTransportsForAttempt(attempt),
1179
- negotiateTimeoutMs: attempt === 'direct' ? DIRECT_WEBRTC_NEGOTIATE_TIMEOUT_MS : undefined,
1180
- ...(rtcFactory === undefined || attempt === 'relay' ? {} : { rtcFactory }),
1181
- fetchIceServers: async (connectionId) => iceServersForAttempt(attempt, await this.server.turnCredentials(connectionId)),
1182
- onWebRtcFallback: (error, diagnostics) => {
1183
- webRtcFallback = true;
1184
- this.logger.warn(attempt === 'direct'
1185
- ? 'remote Harness direct WebRTC failed; trying TURN'
1186
- : 'remote Harness TURN WebRTC failed; using relay', {
1187
- targetDeviceId: shortId(target.deviceId),
1188
- attempt,
1189
- reason: diagnosticReason(error),
1190
- });
1191
- if (diagnostics !== undefined) {
1192
- this.logger.debug('remote Harness WebRTC fallback diagnostics', {
1193
- targetDeviceId: shortId(target.deviceId),
1194
- attempt,
1195
- ...webrtcDiagnosticsLogFields(diagnostics),
1196
- });
1197
- }
1198
- },
1199
- });
1200
- const attempts = this.config.forceRelay || rtcFactory === undefined
1201
- ? ['relay']
1202
- : ['direct', 'turn', 'relay'];
1203
- let transport;
1204
- for (const attempt of attempts) {
1205
- webRtcFallback = false;
1206
- const stopProgressTimer = this.beginAttemptProgress(progressRunId, attempt);
1207
- try {
1208
- transport = createTransport(attempt);
1209
- client = new RemoteClientCore(new ClientSecureTransport(transport, identity, target), 60_000);
1210
- await client.connect();
1211
- signal?.throwIfAborted();
1212
- }
1213
- finally {
1214
- stopProgressTimer();
1215
- }
1216
- if (attempt === 'relay' || !webRtcFallback)
1217
- break;
1218
- await client.close();
1219
- client = undefined;
1220
- transport = undefined;
1221
- if (attempt === 'turn') {
1222
- this.logger.info('remote Harness relay fallback re-established', {
1223
- targetDeviceId: shortId(target.deviceId),
1224
- });
1225
- }
1226
- }
1227
- if (client === undefined || transport === undefined) {
1228
- throw new ClientModeError('CONNECTION_FAILED', 'Unable to establish a remote transport.', true);
1229
- }
1230
- const connectedClient = client;
1231
- const connectedTransport = transport;
1232
- const connectedPreference = transportPreferenceForMode(connectedClient.getStats().mode);
1233
- this.updateConnectionProgress(progressRunId, 'connected', connectedPreference === undefined ? undefined : [connectedPreference]);
1234
- connectedClient.onClose(() => {
1235
- if (this.supersededClient === connectedClient) {
1236
- this.logger.info('ignoring the close of the transport a reconnect is replacing', {
1237
- targetDeviceId: shortId(target.deviceId),
1238
- });
1239
- return;
1240
- }
1241
- // The UI keeps whatever the remote session rendered and offers no exit route once the mode
1242
- // reads 'local' again, so remember that the session dropped: the card uses this to keep a
1243
- // way back to the local shell.
1244
- this.handleRemoteTransportLost(connectedClient, target.deviceId, 'transport-closed');
1245
- });
1246
- // A live session proves itself on a cadence: a close event is not guaranteed to arrive.
1247
- this.armLivenessWatch(LIVENESS_INTERVAL_MS);
1248
- const connectionDetails = await connectedTransport.connectionDetails().catch(() => undefined);
1249
- this.logger.info('remote Harness transport ready', {
1250
- targetDeviceId: shortId(target.deviceId),
1251
- transport: connectedClient.getStats().mode,
1252
- ...(connectionDetails === undefined ? {} : {
1253
- preferredTransports: connectionDetails.preferredTransports,
1254
- negotiatedCapabilities: connectionDetails.negotiatedCapabilities,
1255
- webRtcEnabled: connectionDetails.webRtcEnabled,
1256
- }),
1257
- });
1258
- if (connectionDetails?.webRtc?.diagnostics !== undefined) {
1259
- this.logger.debug('remote Harness transport diagnostics', {
1260
- targetDeviceId: shortId(target.deviceId),
1261
- ...webrtcDiagnosticsLogFields(connectionDetails.webRtc.diagnostics),
1262
- });
1263
- }
1264
- const features = await probeRemoteHostFeatures(connectedClient, serverDevice.clientVersion);
1265
- return {
1266
- client: connectedClient,
1267
- target,
1268
- transport: connectedTransport,
1269
- features,
1270
- progressRunId,
1271
- ...(serverDevice.clientVersion === undefined ? {} : { clientVersion: serverDevice.clientVersion }),
1272
- ...(serverDevice.harnessVersion === undefined ? {} : { harnessVersion: serverDevice.harnessVersion }),
1273
- };
1274
- }
1275
- catch (error) {
1276
- this.clearConnectionProgress(progressRunId);
1277
- await client?.close().catch(() => undefined);
1278
- throw error;
1279
- }
1280
- }
1281
- async ensureConnected(targetDeviceId, signal) {
1282
- if (this.connected?.target.deviceId === targetDeviceId)
1283
- return this.connected;
1284
- const next = await this.connect(targetDeviceId, signal);
1285
- const previous = this.connected;
1286
- await this.closePreview();
1287
- this.connected = next;
1288
- this.clearConnectionProgress(next.progressRunId);
1289
- await previous?.client.close().catch(() => undefined);
1290
- return next;
1291
- }
1292
- beginAttemptProgress(runId, attempt) {
1293
- if (attempt !== 'direct') {
1294
- this.updateConnectionProgress(runId, 'probing', [attempt]);
1295
- return () => undefined;
1296
- }
1297
- this.updateConnectionProgress(runId, 'probing', ['lan']);
1298
- // LAN and public P2P candidates are gathered inside one ICE attempt. The
1299
- // linear Remote UI still needs a single active route, so advance the
1300
- // visible cue if direct negotiation takes longer than a local probe.
1301
- const timer = setTimeout(() => {
1302
- if (this.connectionProgress?.runId === runId && this.connectionProgress.phase === 'probing') {
1303
- this.updateConnectionProgress(runId, 'probing', ['p2p']);
1304
- }
1305
- }, DIRECT_LAN_PROGRESS_DISPLAY_MS);
1306
- return () => clearTimeout(timer);
1307
- }
1308
- updateConnectionProgress(runId, phase, activeTransports) {
1309
- if (this.connectionProgress?.runId !== runId)
1310
- return;
1311
- this.connectionProgress = {
1312
- runId,
1313
- targetDeviceId: this.connectionProgress.targetDeviceId,
1314
- phase,
1315
- ...(activeTransports === undefined ? {} : { activeTransports }),
1316
- };
1317
- }
1318
- clearConnectionProgress(runId) {
1319
- if (this.connectionProgress?.runId === runId)
1320
- this.connectionProgress = undefined;
1321
- }
1322
- async handleControl(endpoint, payload, signal) {
1323
- try {
1324
- if (endpoint === 'status')
1325
- return ok(await this.detailedStatus());
1326
- // A client that just came back to the foreground asks for an immediate check instead of
1327
- // waiting for the next interval: while it was suspended it answered nothing and may have
1328
- // missed the transport close entirely.
1329
- if (endpoint === 'client.connection.verify')
1330
- return ok(await this.verifyRemoteConnection());
1331
- if (endpoint === 'devices')
1332
- return ok(await this.devices());
1333
- if (endpoint === 'client.account.login') {
1334
- const value = record(payload);
1335
- if (typeof value.email !== 'string' || typeof value.password !== 'string') {
1336
- throw new ClientModeError('INVALID_MESSAGE', 'Email and password are required.');
1337
- }
1338
- return ok(await this.authorizeClientWithAccount(value.email, value.password));
1339
- }
1340
- if (endpoint === 'client.account.qr.start') {
1341
- const value = record(payload);
1342
- const provider = value.provider ?? 'zhihu';
1343
- if (provider !== 'zhihu' && provider !== 'github') {
1344
- throw new ClientModeError('INVALID_MESSAGE', 'A supported OAuth provider is required.');
1345
- }
1346
- return ok(await this.startClientOAuthQrLogin(provider));
1347
- }
1348
- if (endpoint === 'client.account.qr.poll') {
1349
- const value = record(payload);
1350
- if (typeof value.qrId !== 'string' || value.qrId.length < 20) {
1351
- throw new ClientModeError('INVALID_MESSAGE', 'A QR login session is required.');
1352
- }
1353
- return ok(await this.pollClientOAuthQrLogin(value.qrId));
1354
- }
1355
- if (endpoint === 'preview.open') {
1356
- const remote = this.activeRemote();
1357
- if (remote === undefined)
1358
- throw new ClientModeError('TRANSPORT_CLOSED', 'Connect to a Remote Host first.');
1359
- this.preview ??= new LoopbackPreview(remote.client);
1360
- return ok(await this.preview.open(record(payload).port));
1361
- }
1362
- if (endpoint === 'directory.list') {
1363
- const value = record(payload);
1364
- if (typeof value.targetDeviceId !== 'string')
1365
- throw new ClientModeError('INVALID_MESSAGE', 'A Host is required.');
1366
- return ok(await this.listRemoteDirectory(value.targetDeviceId, typeof value.path === 'string' ? value.path : undefined, signal));
1367
- }
1368
- if (endpoint === 'workspaces.list') {
1369
- const value = record(payload);
1370
- if (typeof value.targetDeviceId !== 'string')
1371
- throw new ClientModeError('INVALID_MESSAGE', 'A Host is required.');
1372
- return ok(await this.listRemoteWorkspaces(value.targetDeviceId, signal));
1373
- }
1374
- if (endpoint === 'codex.workspaces.list') {
1375
- const value = record(payload);
1376
- if (typeof value.targetDeviceId !== 'string')
1377
- throw new ClientModeError('INVALID_MESSAGE', 'A Host is required.');
1378
- return ok(await this.listCodexWorkspaces(value.targetDeviceId, signal));
1379
- }
1380
- if (endpoint === 'workspace.open') {
1381
- const value = record(payload);
1382
- if (typeof value.targetDeviceId !== 'string' || typeof value.path !== 'string') {
1383
- throw new ClientModeError('INVALID_MESSAGE', 'A Host and working directory are required.');
1384
- }
1385
- return ok(await this.openRemoteWorkspace(value.targetDeviceId, value.path, signal));
1386
- }
1387
- if (endpoint === 'codex.workspace.open') {
1388
- const value = record(payload);
1389
- if (typeof value.targetDeviceId !== 'string' || typeof value.workspaceId !== 'string') {
1390
- throw new ClientModeError('INVALID_MESSAGE', 'A Host and CodeX Workspace are required.');
1391
- }
1392
- return ok(await this.openCodexWorkspace(value.targetDeviceId, value.workspaceId, signal));
1393
- }
1394
- if (endpoint === 'codex.workspace.create') {
1395
- const value = record(payload);
1396
- if (typeof value.targetDeviceId !== 'string' || typeof value.path !== 'string') {
1397
- throw new ClientModeError('INVALID_MESSAGE', 'A Host and CodeX project directory are required.');
1398
- }
1399
- return ok(await this.createCodexWorkspace(value.targetDeviceId, value.path, signal));
1400
- }
1401
- if (endpoint === 'workspace.selection.consume') {
1402
- const value = record(payload);
1403
- if (typeof value.targetDeviceId !== 'string' || typeof value.workspaceId !== 'string') {
1404
- throw new ClientModeError('INVALID_MESSAGE', 'A Host and Workspace are required.');
1405
- }
1406
- return ok(this.consumeWorkspaceSelection({
1407
- targetDeviceId: value.targetDeviceId,
1408
- workspaceId: value.workspaceId,
1409
- ...(value.backend === 'codex' ? { backend: 'codex' } : {}),
1410
- ...(typeof value.sessionId === 'string' ? { sessionId: value.sessionId } : {}),
1411
- }));
1412
- }
1413
- if (endpoint === 'fileviewer.stat' || endpoint === 'fileviewer.readRange' || endpoint === 'fileviewer.list') {
1414
- const method = endpoint === 'fileviewer.stat'
1415
- ? 'stat'
1416
- : endpoint === 'fileviewer.readRange' ? 'readRange' : 'list';
1417
- return ok(await this.callRemoteFileViewer(method, payload, signal));
1418
- }
1419
- if (endpoint === 'codex.call') {
1420
- const value = record(payload);
1421
- if (typeof value.method !== 'string' || !('params' in value)) {
1422
- throw new ClientModeError('INVALID_MESSAGE', 'A Codex method and params are required.');
1423
- }
1424
- const remote = this.activeCodexRemote();
1425
- if (remote !== undefined)
1426
- return ok(await new CodexRemoteClient(remote.client).request(value.method, value.params, signal));
1427
- const host = this.requireLocalCodex();
1428
- return ok(await host.codexCall(value, signal));
1429
- }
1430
- if (endpoint === 'codex.probe') {
1431
- const local = this.localCodexAvailable();
1432
- let remoteSupported = false;
1433
- const remote = this.activeRemote();
1434
- if (remote !== undefined) {
1435
- try {
1436
- remote.features = await probeRemoteHostFeatures(remote.client, remote.clientVersion);
1437
- remoteSupported = remote.features.codex;
1438
- }
1439
- catch (error) {
1440
- if (!local)
1441
- throw error;
1442
- }
1443
- }
1444
- return ok({ supported: local || remoteSupported, local, remote: remoteSupported });
1445
- }
1446
- if (endpoint === 'codex.respond') {
1447
- const value = record(payload);
1448
- const remote = this.activeCodexRemote();
1449
- if (remote !== undefined)
1450
- return ok(await remote.client.rpc('codex.app.respond', value, signal));
1451
- const host = this.requireLocalCodex();
1452
- return ok(await host.codexRespond(value, signal));
1453
- }
1454
- if (endpoint === 'codex.stream.open')
1455
- return ok(await this.openCodexStream(payload, signal));
1456
- if (endpoint === 'codex.stream.next')
1457
- return ok(await this.nextCodexFrames(payload, signal));
1458
- if (endpoint === 'codex.stream.close')
1459
- return ok(await this.closeCodexStream(payload));
1460
- if (endpoint === 'host.account.login') {
1461
- if (this.host === undefined)
1462
- throw new ClientModeError('METHOD_NOT_ALLOWED', 'This plugin is not running as a Host.');
1463
- const value = record(payload);
1464
- if (typeof value.email !== 'string' || typeof value.password !== 'string') {
1465
- throw new ClientModeError('INVALID_MESSAGE', 'Email and password are required.');
1466
- }
1467
- return ok(await this.host.authorizeHostWithAccount(value.email, value.password));
1468
- }
1469
- if (endpoint === 'host.authorization.set') {
1470
- const value = record(payload);
1471
- if (typeof value.enabled !== 'boolean') {
1472
- throw new ClientModeError('INVALID_MESSAGE', 'Host authorization state is required.');
1473
- }
1474
- return ok(await this.setHostAuthorization(value.enabled));
1475
- }
1476
- if (endpoint === 'host.registration-code.submit') {
1477
- if (this.host === undefined)
1478
- throw new ClientModeError('METHOD_NOT_ALLOWED', 'This plugin is not running as a Host.');
1479
- const value = record(payload);
1480
- if (typeof value.code !== 'string' || value.code.trim() === '') {
1481
- throw new ClientModeError('INVALID_MESSAGE', 'A Host registration code is required.');
1482
- }
1483
- return ok(await this.host.authorizeHostWithCode(value.code));
1484
- }
1485
- if (endpoint === 'mode.set') {
1486
- const value = record(payload);
1487
- if (value.mode !== 'local' && value.mode !== 'remote')
1488
- throw new ClientModeError('INVALID_MESSAGE', 'Mode must be local or remote.');
1489
- return ok(await this.setMode(value.mode, typeof value.targetDeviceId === 'string' ? value.targetDeviceId : undefined, signal));
1490
- }
1491
- throw new ClientModeError('METHOD_NOT_FOUND', 'The remote-mode control method does not exist.');
1492
- }
1493
- catch (error) {
1494
- return fail(error);
1495
- }
1496
- }
1497
- requireIdentity() {
1498
- if (this.identity === undefined)
1499
- throw new ClientModeError('IDENTITY_INVALID', 'The client identity is not ready.');
1500
- return this.identity;
1501
- }
1502
- async authorizeHostPeer(serverDevice) {
1503
- const descriptor = await this.server.deviceFor(serverDevice.deviceId);
1504
- assertAuthorizedHost(serverDevice, descriptor);
1505
- const existing = this.identities.trustedPeer(descriptor.deviceId);
1506
- if (existing !== undefined && existing.publicKey !== descriptor.identityKey) {
1507
- throw new ClientModeError('PEER_IDENTITY_MISMATCH', 'The authorized Host identity key changed unexpectedly.');
1508
- }
1509
- if (existing !== undefined
1510
- && existing.membershipId === descriptor.membershipId
1511
- && existing.name === descriptor.name
1512
- && existing.platform === descriptor.platform) {
1513
- return existing;
1514
- }
1515
- return this.identities.trustPeer({
1516
- deviceId: descriptor.deviceId,
1517
- name: descriptor.name,
1518
- platform: descriptor.platform,
1519
- publicKey: descriptor.identityKey,
1520
- membershipId: descriptor.membershipId,
1521
- });
1522
- }
1523
- }
1524
- export class ClientModeError extends Error {
1525
- code;
1526
- retryable;
1527
- constructor(code, message, retryable = false) {
1528
- super(message);
1529
- this.code = code;
1530
- this.retryable = retryable;
1531
- }
1532
- }
1533
- function assertAuthorizedHost(listed, descriptor) {
1534
- if (descriptor.role !== 'host' || descriptor.deviceId !== listed.deviceId
1535
- || descriptor.membershipId !== listed.membershipId) {
1536
- throw new ClientModeError('PEER_IDENTITY_MISMATCH', 'Server Host details do not match the authorized device list.');
1537
- }
1538
- }
1539
- function websocketUrl(baseUrl) {
1540
- const url = new URL(baseUrl);
1541
- url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
1542
- url.pathname = `${url.pathname.replace(/\/$/, '')}/ws/v1/connect`;
1543
- return url.toString();
1544
- }
1545
- function webrtcDiagnosticsLogFields(diagnostics) {
1546
- if (diagnostics === undefined)
1547
- return {};
1548
- return {
1549
- rtcConnectionState: diagnostics.connectionState,
1550
- rtcIceConnectionState: diagnostics.iceConnectionState,
1551
- rtcIceGatheringState: diagnostics.iceGatheringState,
1552
- rtcLocalCandidates: diagnostics.localCandidates,
1553
- rtcRemoteCandidates: diagnostics.remoteCandidates,
1554
- rtcCandidatePairs: diagnostics.candidatePairs,
1555
- rtcFilteredLocalCandidates: diagnostics.filteredLocalCandidates,
1556
- rtcFilteredCandidatePairs: diagnostics.filteredCandidatePairs,
1557
- ...(diagnostics.selectedPath === undefined ? {} : { rtcSelectedPath: diagnostics.selectedPath }),
1558
- };
1559
- }
1560
- function record(value) {
1561
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
1562
- throw new ClientModeError('INVALID_MESSAGE', 'The control request payload is invalid.');
1563
- }
1564
- return value;
1565
- }
1566
- function isRecord(value) {
1567
- return typeof value === 'object' && value !== null && !Array.isArray(value);
1568
- }
1569
- function ok(value) { return { ok: true, value }; }
1570
- async function invokeRemoteCommand(client, request) {
1571
- const rpcId = uuidV7();
1572
- const response = await client.rpc('harness.api.call', {
1573
- method: `${request.namespace}.${request.method}`,
1574
- rpcId,
1575
- payload: request.args,
1576
- }, request.signal);
1577
- if (response.rpcId !== rpcId) {
1578
- throw new ClientModeError('INVALID_MESSAGE', 'The remote Host returned an invalid command response.');
1579
- }
1580
- return unwrapNativeResult(response);
1581
- }
1582
- async function readRemoteWorkspaceBaseline(gateway, signal) {
1583
- const lifetime = new AbortController();
1584
- const activeSignal = signal === undefined
1585
- ? lifetime.signal
1586
- : AbortSignal.any([signal, lifetime.signal]);
1587
- const source = await gateway.open('workspace/follow', { args: {} }, activeSignal);
1588
- const iterator = source[Symbol.asyncIterator]();
1589
- try {
1590
- const first = await iterator.next();
1591
- if (first.done || !isRecord(first.value) || first.value.type !== 'baseline'
1592
- || !isRecord(first.value.value) || !Array.isArray(first.value.value.items)) {
1593
- throw new ClientModeError('INVALID_MESSAGE', 'The remote Host returned an invalid Workspace baseline.');
1594
- }
1595
- return first.value.value.items.map((item) => {
1596
- if (!isRecord(item) || typeof item.workspaceId !== 'string'
1597
- || typeof item.path !== 'string' || typeof item.title !== 'string') {
1598
- throw new ClientModeError('INVALID_MESSAGE', 'The remote Host returned an invalid Workspace row.');
1599
- }
1600
- return { workspaceId: item.workspaceId, path: item.path, title: item.title };
1601
- });
1602
- }
1603
- finally {
1604
- lifetime.abort('workspace-baseline-read');
1605
- await iterator.return?.();
1606
- }
1607
- }
1608
- function unwrapNativeResult(response) {
1609
- const result = response.result;
1610
- if (typeof result !== 'object' || result === null || !('ok' in result)) {
1611
- throw new ClientModeError('INVALID_MESSAGE', 'The remote Host returned an invalid response.');
1612
- }
1613
- if (result.ok !== true || !('value' in result)) {
1614
- const message = 'error' in result && typeof result.error === 'object' && result.error !== null
1615
- && 'message' in result.error && typeof result.error.message === 'string'
1616
- ? result.error.message
1617
- : 'The remote Host rejected the request.';
1618
- throw new ClientModeError('REMOTE_API_ERROR', message);
1619
- }
1620
- return result.value;
1621
- }
1622
- function workspaceRecordId(value) {
1623
- if (typeof value !== 'object' || value === null || !('workspaceId' in value)
1624
- || typeof value.workspaceId !== 'string' || value.workspaceId.length === 0) {
1625
- throw new ClientModeError('INVALID_MESSAGE', 'The remote Host returned an invalid Workspace.');
1626
- }
1627
- return value.workspaceId;
1628
- }
1629
- function remoteWorkspaceTitle(path) {
1630
- const normalized = path.replace(/[\\/]+$/u, '');
1631
- return normalized.split(/[\\/]+/u).filter(Boolean).at(-1) ?? path;
1632
- }
1633
- function fail(error) {
1634
- const source = error instanceof Error ? error : undefined;
1635
- const remoteCode = source !== undefined && 'code' in source && typeof source.code === 'string'
1636
- ? source.code
1637
- : source instanceof ClientModeError ? source.code : undefined;
1638
- const retryable = source !== undefined && 'retryable' in source && typeof source.retryable === 'boolean'
1639
- ? source.retryable
1640
- : source instanceof ClientModeError ? source.retryable : false;
1641
- return {
1642
- ok: false,
1643
- error: {
1644
- code: 'internal',
1645
- message: source?.message ?? 'The remote-mode operation failed.',
1646
- details: remoteCode === undefined ? {} : { remoteCode, retryable },
1647
- },
1648
- };
1649
- }
1650
- function shortId(value) { return value.length <= 12 ? value : `${value.slice(0, 8)}…${value.slice(-4)}`; }
1651
- /** Conservative feature profile for Hosts that predate fine-grained capability discovery. */
1652
- export function remoteHostFeatures(clientVersion) {
1653
- return {
1654
- commandList: isVersionAtLeast(clientVersion, REMOTE_COMMAND_LIST_MIN_VERSION),
1655
- fileViewer: isVersionAtLeast(clientVersion, REMOTE_FILE_VIEWER_MIN_VERSION),
1656
- terminal: false,
1657
- apiProxy: true,
1658
- remoteGateway: false,
1659
- codex: false,
1660
- };
1661
- }
1662
- export async function probeRemoteHostFeatures(client, clientVersion) {
1663
- const fallback = remoteHostFeatures(clientVersion);
1664
- let value;
1665
- try {
1666
- value = await client.rpc('harness.transport.describe', {});
1667
- }
1668
- catch (error) {
1669
- if (error instanceof Error && 'code' in error && error.code === 'METHOD_NOT_FOUND')
1670
- return fallback;
1671
- throw error;
1672
- }
1673
- if (!isRecord(value) || !Array.isArray(value.capabilities)
1674
- || value.capabilities.some(capability => typeof capability !== 'string')) {
1675
- throw new ClientModeError('INVALID_MESSAGE', 'The remote Host returned invalid transport capabilities.');
1676
- }
1677
- const capabilities = new Set(value.capabilities);
1678
- const apiProxy = capabilities.has('harness.api.v1');
1679
- const remoteV1 = capabilities.has('harness.remote.v1');
1680
- const remoteV3 = capabilities.has('harness.remote.v3');
1681
- const terminal = capabilities.has('harness.terminal.v1');
1682
- const codex = capabilities.has('codex.appserver.v1');
1683
- if (remoteV1 && remoteV3) {
1684
- throw new ClientModeError('INVALID_MESSAGE', 'The remote Host advertised conflicting Harness Session formats.');
1685
- }
1686
- const sessionFormat = remoteV3 ? 3 : undefined;
1687
- const remoteGateway = remoteV3 || remoteV1;
1688
- if (!apiProxy && !remoteGateway && !codex) {
1689
- throw new ClientModeError('FEATURE_NOT_SUPPORTED', 'The remote Host exposes no supported Harness transport.');
1690
- }
1691
- return {
1692
- commandList: remoteGateway || (apiProxy && fallback.commandList),
1693
- fileViewer: capabilities.has('fileviewer.read.v1'),
1694
- terminal,
1695
- apiProxy,
1696
- remoteGateway,
1697
- ...(sessionFormat === undefined ? {} : { sessionFormat }),
1698
- codex,
1699
- };
1700
- }
1701
- async function waitForCodexFrames(stream, signal) {
1702
- if (signal?.aborted)
1703
- throw new ClientModeError('RPC_ABORTED', 'The Codex event poll was cancelled.');
1704
- await new Promise((resolve, reject) => {
1705
- const previousWake = stream.wake;
1706
- const timer = setTimeout(done, 25_000);
1707
- const onAbort = () => {
1708
- cleanup();
1709
- reject(new ClientModeError('RPC_ABORTED', 'The Codex event poll was cancelled.'));
1710
- };
1711
- function cleanup() {
1712
- clearTimeout(timer);
1713
- stream.wake = previousWake;
1714
- signal?.removeEventListener('abort', onAbort);
1715
- }
1716
- function done() {
1717
- cleanup();
1718
- resolve();
1719
- }
1720
- stream.wake = () => {
1721
- previousWake();
1722
- done();
1723
- };
1724
- signal?.addEventListener('abort', onAbort, { once: true });
1725
- });
1726
- }
1727
- function isVersionAtLeast(value, minimum) {
1728
- const match = value?.match(/^v?(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);
1729
- if (match === undefined || match === null)
1730
- return false;
1731
- const version = match.slice(1, 4).map(part => Number(part));
1732
- for (let index = 0; index < minimum.length; index += 1) {
1733
- const part = version[index] ?? 0;
1734
- const expected = minimum[index] ?? 0;
1735
- if (part > expected)
1736
- return true;
1737
- if (part < expected)
1738
- return false;
1739
- }
1740
- return true;
1741
- }
1742
- function diagnosticReason(error) {
1743
- const code = 'code' in error && typeof error.code === 'string' ? error.code : undefined;
1744
- const message = error.message.replace(/[\r\n\t]+/g, ' ').slice(0, 240);
1745
- return code === undefined ? message : `${code}: ${message}`;
1746
- }
1747
- function preferredTransportsForAttempt(attempt) {
1748
- if (attempt === 'direct')
1749
- return ['lan', 'p2p', 'relay'];
1750
- if (attempt === 'turn')
1751
- return ['turn', 'relay'];
1752
- return ['relay'];
1753
- }
1754
- function transportPreferenceForMode(mode) {
1755
- if (mode === 'LAN')
1756
- return 'lan';
1757
- if (mode === 'P2P')
1758
- return 'p2p';
1759
- if (mode === 'TURN')
1760
- return 'turn';
1761
- if (mode === 'Relay')
1762
- return 'relay';
1763
- return undefined;
1764
- }
1765
- function iceServersForAttempt(attempt, iceServers) {
1766
- return attempt === 'direct' ? stunOnlyIceServers(iceServers) : iceServers;
1767
- }
1768
- //# sourceMappingURL=client-runtime.js.map