@andorra-labs/code 0.1.15 → 0.1.17

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 (242) hide show
  1. package/dist/src/acp-agent.d.ts +6 -0
  2. package/dist/src/acp-agent.js +15 -4
  3. package/dist/src/agent-definitions.js +29 -6
  4. package/dist/src/agent-execution.js +15 -10
  5. package/dist/src/agent-mcp-catalog.js +1 -0
  6. package/dist/src/agent-mcp.d.ts +4 -1
  7. package/dist/src/agent-mcp.js +46 -10
  8. package/dist/src/andorra/entry.d.ts +10 -0
  9. package/dist/src/andorra/entry.js +18 -4
  10. package/dist/src/andorra/hosted.d.ts +2 -1
  11. package/dist/src/andorra/hosted.js +2 -1
  12. package/dist/src/andorra/notices.d.ts +5 -0
  13. package/dist/src/andorra/notices.js +7 -0
  14. package/dist/src/andorra/state.d.ts +3 -2
  15. package/dist/src/andorra/state.js +4 -4
  16. package/dist/src/andorra/terminal.js +7 -2
  17. package/dist/src/anthropic-credentials.js +2 -0
  18. package/dist/src/app-server/error.d.ts +5 -0
  19. package/dist/src/app-server/error.js +7 -0
  20. package/dist/src/app-server/protocol.d.ts +22 -44
  21. package/dist/src/app-server/protocol.js +5 -1
  22. package/dist/src/app-server/workspace.d.ts +89 -0
  23. package/dist/src/app-server/workspace.js +457 -11
  24. package/dist/src/app-server.d.ts +465 -32
  25. package/dist/src/app-server.js +3308 -517
  26. package/dist/src/auth/deployment.js +2 -2
  27. package/dist/src/bridge/cloud.d.ts +27 -0
  28. package/dist/src/bridge/cloud.js +187 -0
  29. package/dist/src/bridge/command.d.ts +30 -0
  30. package/dist/src/bridge/command.js +347 -0
  31. package/dist/src/bridge/control.d.ts +68 -0
  32. package/dist/src/bridge/control.js +233 -0
  33. package/dist/src/bridge/engines.d.ts +90 -0
  34. package/dist/src/bridge/engines.js +601 -0
  35. package/dist/src/bridge/host-ops.d.ts +9 -0
  36. package/dist/src/bridge/host-ops.js +129 -0
  37. package/dist/src/bridge/host.d.ts +47 -0
  38. package/dist/src/bridge/host.js +540 -0
  39. package/dist/src/bridge/link.d.ts +38 -0
  40. package/dist/src/bridge/link.js +508 -0
  41. package/dist/src/bridge/login-link.d.ts +29 -0
  42. package/dist/src/bridge/login-link.js +54 -0
  43. package/dist/src/bridge/protocol.d.ts +136 -0
  44. package/dist/src/bridge/protocol.js +11 -0
  45. package/dist/src/bridge/store.d.ts +12 -0
  46. package/dist/src/bridge/store.js +61 -0
  47. package/dist/src/bridge/wording.d.ts +6 -0
  48. package/dist/src/bridge/wording.js +10 -0
  49. package/dist/src/browser-runner.js +1 -0
  50. package/dist/src/browser-server.js +7 -1
  51. package/dist/src/browser-ui/style.css +3 -3
  52. package/dist/src/browser-ui/tokens.css +28 -17
  53. package/dist/src/change-authors.d.ts +41 -0
  54. package/dist/src/change-authors.js +146 -0
  55. package/dist/src/claude-provider.js +3 -1
  56. package/dist/src/cli.js +202 -38
  57. package/dist/src/codex-errors.js +4 -1
  58. package/dist/src/coding-tools.js +15 -15
  59. package/dist/src/command-screens.d.ts +6 -0
  60. package/dist/src/command-screens.js +19 -14
  61. package/dist/src/commands.d.ts +14 -1
  62. package/dist/src/compaction-phrases.d.ts +4 -0
  63. package/dist/src/compaction-phrases.js +20 -0
  64. package/dist/src/completion.js +82 -5
  65. package/dist/src/config.d.ts +71 -3
  66. package/dist/src/config.js +202 -77
  67. package/dist/src/context-compaction.js +2 -1
  68. package/dist/src/deadline.js +13 -1
  69. package/dist/src/decision/DecisionManager.js +3 -2
  70. package/dist/src/decision/checks.js +1 -1
  71. package/dist/src/decision/requestPhrases.d.ts +4 -0
  72. package/dist/src/decision/requestPhrases.js +22 -0
  73. package/dist/src/default-graph.js +1 -1
  74. package/dist/src/file-diff.d.ts +4 -0
  75. package/dist/src/file-diff.js +2 -1
  76. package/dist/src/github-app/agent-writes.d.ts +102 -0
  77. package/dist/src/github-app/agent-writes.js +320 -0
  78. package/dist/src/github-app/client.d.ts +349 -0
  79. package/dist/src/github-app/client.js +810 -0
  80. package/dist/src/github-app/event-source.d.ts +208 -0
  81. package/dist/src/github-app/event-source.js +684 -0
  82. package/dist/src/github-app/metrics.d.ts +32 -0
  83. package/dist/src/github-app/metrics.js +49 -0
  84. package/dist/src/github-app/review-loop.d.ts +274 -0
  85. package/dist/src/github-app/review-loop.js +1177 -0
  86. package/dist/src/github-app/review-node.d.ts +81 -0
  87. package/dist/src/github-app/review-node.js +205 -0
  88. package/dist/src/github-app/review-post.d.ts +73 -0
  89. package/dist/src/github-app/review-post.js +139 -0
  90. package/dist/src/github-app/review-text.d.ts +107 -0
  91. package/dist/src/github-app/review-text.js +1133 -0
  92. package/dist/src/github-app/review-threads.d.ts +47 -0
  93. package/dist/src/github-app/review-threads.js +107 -0
  94. package/dist/src/github-app/reviewer.d.ts +121 -0
  95. package/dist/src/github-app/reviewer.js +598 -0
  96. package/dist/src/github-app/store.d.ts +59 -0
  97. package/dist/src/github-app/store.js +148 -0
  98. package/dist/src/github-app/triggers.d.ts +141 -0
  99. package/dist/src/github-app/triggers.js +441 -0
  100. package/dist/src/github-inbox.d.ts +55 -0
  101. package/dist/src/github-inbox.js +153 -0
  102. package/dist/src/github-names.d.ts +8 -0
  103. package/dist/src/github-names.js +8 -0
  104. package/dist/src/glob-search.d.ts +61 -0
  105. package/dist/src/glob-search.js +180 -0
  106. package/dist/src/graph-health.js +13 -4
  107. package/dist/src/graph-manager-chat.js +1 -1
  108. package/dist/src/graph-preview.d.ts +46 -0
  109. package/dist/src/graph-preview.js +55 -0
  110. package/dist/src/graph-provider-portability.js +34 -11
  111. package/dist/src/graph-quota.d.ts +29 -2
  112. package/dist/src/graph-quota.js +68 -10
  113. package/dist/src/graph-runner.js +88 -10
  114. package/dist/src/graph-server.d.ts +1 -1
  115. package/dist/src/graph-server.js +11 -9
  116. package/dist/src/graph-sync.js +3 -3
  117. package/dist/src/graph-ui/app.js +201 -40
  118. package/dist/src/graph-ui/controls.css +1 -0
  119. package/dist/src/graph-ui/embed.js +2 -2
  120. package/dist/src/graph-ui/icons.js +3 -1
  121. package/dist/src/graph-ui/index.html +1 -1
  122. package/dist/src/graph-ui/manager.css +1 -1
  123. package/dist/src/graph-ui/manager.js +2 -2
  124. package/dist/src/graph-ui/sidebar.js +30 -0
  125. package/dist/src/graph-ui/studio-canvas.js +26 -13
  126. package/dist/src/graph-ui/studio.css +15 -7
  127. package/dist/src/graph-ui/studio.js +26 -5
  128. package/dist/src/graph-ui/style.css +77 -45
  129. package/dist/src/graph-ui/theme.js +3 -36
  130. package/dist/src/graph-ui/tokens.css +28 -20
  131. package/dist/src/graphs.d.ts +34 -1
  132. package/dist/src/graphs.js +162 -17
  133. package/dist/src/image-input.d.ts +16 -0
  134. package/dist/src/image-input.js +41 -0
  135. package/dist/src/membership.d.ts +30 -1
  136. package/dist/src/membership.js +48 -8
  137. package/dist/src/model-health-cache.js +1 -1
  138. package/dist/src/model-metadata.d.ts +7 -1
  139. package/dist/src/model-metadata.js +39 -17
  140. package/dist/src/model-relay/local.d.ts +116 -0
  141. package/dist/src/model-relay/local.js +468 -0
  142. package/dist/src/model-relay/remote.d.ts +129 -0
  143. package/dist/src/model-relay/remote.js +252 -0
  144. package/dist/src/model-relay/runs.d.ts +34 -0
  145. package/dist/src/model-relay/runs.js +146 -0
  146. package/dist/src/model-relay/wire.d.ts +5 -0
  147. package/dist/src/model-relay/wire.js +5 -0
  148. package/dist/src/plan-pass.d.ts +59 -0
  149. package/dist/src/plan-pass.js +165 -0
  150. package/dist/src/project-registry.d.ts +21 -0
  151. package/dist/src/project-registry.js +74 -0
  152. package/dist/src/provider-engine.js +3 -0
  153. package/dist/src/provider-import.d.ts +0 -12
  154. package/dist/src/provider-import.js +7 -195
  155. package/dist/src/providers.d.ts +40 -2
  156. package/dist/src/providers.js +93 -23
  157. package/dist/src/pull-request-checks.d.ts +26 -0
  158. package/dist/src/pull-request-checks.js +56 -0
  159. package/dist/src/pull-request-conversation.d.ts +134 -0
  160. package/dist/src/pull-request-conversation.js +221 -0
  161. package/dist/src/pull-request-create.d.ts +175 -0
  162. package/dist/src/pull-request-create.js +392 -0
  163. package/dist/src/pull-request-details.d.ts +242 -0
  164. package/dist/src/pull-request-details.js +614 -0
  165. package/dist/src/pull-request-edit.d.ts +23 -0
  166. package/dist/src/pull-request-edit.js +91 -0
  167. package/dist/src/pull-request-logs.d.ts +87 -0
  168. package/dist/src/pull-request-logs.js +183 -0
  169. package/dist/src/pull-request-merge.d.ts +112 -0
  170. package/dist/src/pull-request-merge.js +258 -0
  171. package/dist/src/pull-request-review.d.ts +137 -0
  172. package/dist/src/pull-request-review.js +401 -0
  173. package/dist/src/pull-requests.d.ts +369 -8
  174. package/dist/src/pull-requests.js +524 -55
  175. package/dist/src/react-runtime.js +38 -5
  176. package/dist/src/remote/engine-pool.d.ts +88 -4
  177. package/dist/src/remote/engine-pool.js +379 -90
  178. package/dist/src/remote/roots.d.ts +19 -0
  179. package/dist/src/remote/roots.js +45 -7
  180. package/dist/src/remote/types.d.ts +0 -44
  181. package/dist/src/run-control.d.ts +17 -0
  182. package/dist/src/run-control.js +47 -0
  183. package/dist/src/run-progress.d.ts +10 -0
  184. package/dist/src/run-progress.js +122 -0
  185. package/dist/src/run-records.d.ts +7 -2
  186. package/dist/src/run-records.js +71 -6
  187. package/dist/src/runtime.d.ts +9 -1
  188. package/dist/src/runtime.js +24 -4
  189. package/dist/src/session-changes.d.ts +35 -0
  190. package/dist/src/session-changes.js +194 -6
  191. package/dist/src/session-monitor.js +2 -1
  192. package/dist/src/session-reaper.d.ts +1 -1
  193. package/dist/src/session-reaper.js +6 -1
  194. package/dist/src/session-summary.d.ts +2 -1
  195. package/dist/src/session-summary.js +2 -1
  196. package/dist/src/sessions.d.ts +11 -1
  197. package/dist/src/sessions.js +17 -4
  198. package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
  199. package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
  200. package/dist/src/skills/bundled/provenance.json +2 -2
  201. package/dist/src/skills/runtime-skills.js +1 -1
  202. package/dist/src/subagent-run.js +1 -0
  203. package/dist/src/telemetry/capture-core.d.ts +17 -0
  204. package/dist/src/telemetry/capture-core.js +59 -1
  205. package/dist/src/telemetry/classify.d.ts +3 -1
  206. package/dist/src/telemetry/classify.js +37 -0
  207. package/dist/src/telemetry/emitter.d.ts +17 -0
  208. package/dist/src/telemetry/emitter.js +76 -5
  209. package/dist/src/telemetry/schema.d.ts +47 -2
  210. package/dist/src/telemetry/schema.js +120 -5
  211. package/dist/src/telemetry/surface.d.ts +3 -1
  212. package/dist/src/telemetry/surface.js +4 -1
  213. package/dist/src/telemetry/uploader.d.ts +6 -1
  214. package/dist/src/telemetry/uploader.js +22 -3
  215. package/dist/src/terminal-ui.d.ts +1 -0
  216. package/dist/src/terminal-ui.js +10 -3
  217. package/dist/src/test-edit-guard.d.ts +7 -0
  218. package/dist/src/test-edit-guard.js +49 -1
  219. package/dist/src/timers.d.ts +2 -0
  220. package/dist/src/tools.js +59 -9
  221. package/dist/src/transcript.js +8 -2
  222. package/dist/src/types.d.ts +7 -0
  223. package/dist/src/usage-analytics.js +18 -10
  224. package/package.json +6 -1
  225. package/dist/src/remote/cert.d.ts +0 -11
  226. package/dist/src/remote/cert.js +0 -87
  227. package/dist/src/remote/client.d.ts +0 -119
  228. package/dist/src/remote/client.js +0 -544
  229. package/dist/src/remote/command.d.ts +0 -4
  230. package/dist/src/remote/command.js +0 -194
  231. package/dist/src/remote/errors.d.ts +0 -11
  232. package/dist/src/remote/errors.js +0 -14
  233. package/dist/src/remote/network.d.ts +0 -22
  234. package/dist/src/remote/network.js +0 -102
  235. package/dist/src/remote/pairing.d.ts +0 -63
  236. package/dist/src/remote/pairing.js +0 -299
  237. package/dist/src/remote/pem.d.ts +0 -2
  238. package/dist/src/remote/pem.js +0 -7
  239. package/dist/src/remote/serve.d.ts +0 -68
  240. package/dist/src/remote/serve.js +0 -244
  241. package/dist/src/remote/server.d.ts +0 -21
  242. package/dist/src/remote/server.js +0 -406
@@ -0,0 +1,540 @@
1
+ import { hostname } from 'node:os';
2
+ import { RemoteEngineRelay } from '../remote/engine-pool.js';
3
+ import { MODEL_RELAY_CONNECTION_PREFIX } from '../model-relay/wire.js';
4
+ import { HEARTBEAT_MS } from './cloud.js';
5
+ import { ControlError } from './control.js';
6
+ import { compareVersions } from './engines.js';
7
+ import { hostOperation, HostOperationError } from './host-ops.js';
8
+ import { CLIENT_DEAD_MS, CLIENT_PING_MS, CLOSE, MAX_FRAME_BYTES, PROTOCOL_VERSION } from './protocol.js';
9
+ export const DEFAULT_RELAY_URL = 'wss://relay.andorracode.com/v1/link';
10
+ const REFRESH_LEAD_MS = 300_000;
11
+ const MIN_REFRESH_GAP_MS = 30_000;
12
+ const REFRESH_RETRY_MS = 15_000;
13
+ const READY_TIMEOUT_MS = 30_000;
14
+ const SOCKET_OPEN = 1;
15
+ const ENGINE_VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,4}$/;
16
+ /** How often a host started by the launcher checks that the launcher is still there. */
17
+ export const LAUNCHER_CHECK_MS = 30_000;
18
+ /** How often a host that a newer desktop has seen checks whether it can hand over to that version. */
19
+ export const RESTART_CHECK_MS = 10_000;
20
+ /** How long a host that was started for another version than it runs waits before asking for that version again. */
21
+ export const HOST_REQUEST_HOLD_MS = 10 * 60_000;
22
+ export const MAX_NEWER_VERSIONS = 4;
23
+ export const RESTARTING_MESSAGE = 'This machine is restarting to update Andorra Code. Try again in a moment.';
24
+ const TASK_START_METHODS = new Set(['run.start', 'run.resume']);
25
+ const HOST_OPERATIONS = new Set(['whoami', 'projects', 'roots', 'browse', 'owner.roots', 'owner.browse', 'owner.projects.add']);
26
+ export const hostDependencies = {
27
+ createRelay: (directory, engines) => new RemoteEngineRelay(directory, {}, engines ? { engines } : {}),
28
+ };
29
+ export function relayUrlFromEnvironment(environment = process.env) {
30
+ return environment.ANDORRA_RELAY_URL?.trim() || DEFAULT_RELAY_URL;
31
+ }
32
+ export function reconnectDelayMs(attempt, random = Math.random) {
33
+ const base = Math.min(30_000, 1000 * 2 ** attempt);
34
+ return Math.round(base + base * 0.2 * random());
35
+ }
36
+ export function refreshDelayMs(expiresAt, now = Date.now()) {
37
+ const expires = Date.parse(expiresAt);
38
+ if (Number.isNaN(expires))
39
+ return 10 * 60_000;
40
+ return Math.max(0, expires - REFRESH_LEAD_MS - now);
41
+ }
42
+ function isRecord(value) {
43
+ return !!value && typeof value === 'object' && !Array.isArray(value);
44
+ }
45
+ function sleep(ms, signal) {
46
+ return new Promise(resolve => {
47
+ if (signal.aborted) {
48
+ resolve();
49
+ return;
50
+ }
51
+ const done = () => { clearTimeout(timer); signal.removeEventListener('abort', done); resolve(); };
52
+ const timer = setTimeout(done, ms);
53
+ signal.addEventListener('abort', done, { once: true });
54
+ });
55
+ }
56
+ /** Whether a token can open a new session: it has more than the refresh lead left. */
57
+ function stillGood(credential, now = Date.now()) {
58
+ if (!credential)
59
+ return false;
60
+ const expires = Date.parse(credential.expiresAt);
61
+ return !Number.isNaN(expires) && expires - now > REFRESH_LEAD_MS;
62
+ }
63
+ /** Connections a person could be looking at: open on the relay, and not the engine's own model relay link. */
64
+ class OpenConnections {
65
+ open = new Map();
66
+ add(viewer, connectionId) {
67
+ const ids = this.open.get(viewer) ?? new Set();
68
+ ids.add(connectionId);
69
+ this.open.set(viewer, ids);
70
+ }
71
+ delete(viewer, connectionId) {
72
+ const ids = this.open.get(viewer);
73
+ if (!ids)
74
+ return;
75
+ ids.delete(connectionId);
76
+ if (ids.size === 0)
77
+ this.open.delete(viewer);
78
+ }
79
+ attached() {
80
+ let count = 0;
81
+ for (const ids of this.open.values())
82
+ for (const connectionId of ids)
83
+ if (!connectionId.startsWith(MODEL_RELAY_CONNECTION_PREFIX))
84
+ count += 1;
85
+ return count;
86
+ }
87
+ }
88
+ export async function runBridgeHost(hostOptions) {
89
+ // The heartbeat can end the host (the service no longer knows this machine) without the caller's signal firing.
90
+ const stopped = new AbortController();
91
+ const forwardAbort = () => stopped.abort();
92
+ if (hostOptions.signal.aborted)
93
+ stopped.abort();
94
+ else
95
+ hostOptions.signal.addEventListener('abort', forwardAbort, { once: true });
96
+ const options = { ...hostOptions, signal: stopped.signal };
97
+ const { signal, log } = options;
98
+ const host = { hostname: hostname(), platform: process.platform, version: options.version };
99
+ // One relay for the life of the host: its engines and runs outlive any single socket.
100
+ const relay = hostDependencies.createRelay(options.directory, options.engines);
101
+ const backoff = options.backoffMs ?? reconnectDelayMs;
102
+ let attempt = 0;
103
+ // The last token, reused for a new session while it has time left, so a reconnect does not ask the account API.
104
+ let cached;
105
+ const connections = new OpenConnections();
106
+ let unlinkedByHeartbeat = false;
107
+ let heartbeatTimer;
108
+ if (options.heartbeat) {
109
+ const report = options.heartbeat;
110
+ let sending = false;
111
+ let lastFailure;
112
+ const beat = async () => {
113
+ if (sending || signal.aborted)
114
+ return;
115
+ sending = true;
116
+ try {
117
+ await report({ running: relay.activity().running, attached: connections.attached() });
118
+ lastFailure = undefined;
119
+ }
120
+ catch (error) {
121
+ if (error instanceof ControlError && error.code === 'unlinked') {
122
+ unlinkedByHeartbeat = true;
123
+ log('This machine is no longer linked to an Andorra account.');
124
+ stopped.abort();
125
+ return;
126
+ }
127
+ const failure = error instanceof Error ? error.message : String(error);
128
+ if (failure !== lastFailure)
129
+ log(`Could not report activity to Andorra: ${failure}`);
130
+ lastFailure = failure;
131
+ }
132
+ finally {
133
+ sending = false;
134
+ }
135
+ };
136
+ void beat();
137
+ heartbeatTimer = setInterval(() => { void beat(); }, HEARTBEAT_MS);
138
+ heartbeatTimer.unref?.();
139
+ }
140
+ let launcherTimer;
141
+ if (options.launcherAlive) {
142
+ const alive = options.launcherAlive;
143
+ launcherTimer = setInterval(() => {
144
+ if (signal.aborted || alive())
145
+ return;
146
+ log('The bridge launcher that started this bridge is gone, so it is stopping.');
147
+ stopped.abort();
148
+ }, options.launcherCheckMs ?? LAUNCHER_CHECK_MS);
149
+ launcherTimer.unref?.();
150
+ }
151
+ // Newer desktop versions seen on this host: once one is installed and no task runs, the launcher restarts the host as it.
152
+ // A version is not forgotten when its desktop leaves: that desktop will come back, and should find the newer host.
153
+ // Only the highest MAX_NEWER_VERSIONS are kept, so a desktop naming made-up versions cannot grow the set.
154
+ const newer = new Set();
155
+ const now = options.now ?? Date.now;
156
+ // A host started for a restart it asked for, but running another version (the launcher could not start that one),
157
+ // does not ask for the same version again at once: the launcher would fall back again and again.
158
+ let held;
159
+ if (options.engines) {
160
+ const last = await options.engines.lastHostRequest().catch(() => undefined);
161
+ if (last && last.version !== options.version && ENGINE_VERSION.test(options.version) && compareVersions(last.version, options.version) > 0) {
162
+ held = { version: last.version, until: last.at + HOST_REQUEST_HOLD_MS };
163
+ }
164
+ }
165
+ let restarting = false;
166
+ // Requests and host operations not yet answered: a restart would cut a compaction or a save short, or tear a config write.
167
+ let answering = 0;
168
+ // Asking the engines what they hold can outlast the interval between checks.
169
+ let checking = false;
170
+ const restartIfIdle = async () => {
171
+ if (checking)
172
+ return;
173
+ checking = true;
174
+ try {
175
+ await checkRestart();
176
+ }
177
+ finally {
178
+ checking = false;
179
+ }
180
+ };
181
+ const checkRestart = async () => {
182
+ const engines = options.engines;
183
+ if (!engines || restarting || signal.aborted || newer.size === 0)
184
+ return;
185
+ if (answering > 0 || relay.runningTasks() > 0 || engines.installing() > 0)
186
+ return;
187
+ const installed = [];
188
+ for (const version of newer)
189
+ if (await engines.installed(version))
190
+ installed.push(version);
191
+ if (installed.length === 0)
192
+ return;
193
+ const next = installed.sort(compareVersions).at(-1);
194
+ if (held !== undefined && next === held.version && now() < held.until)
195
+ return;
196
+ // Work no run.start announced would be lost with the engines: a wake, a run an engine started itself, a background process, a terminal.
197
+ if (await relay.holdsWork())
198
+ return;
199
+ if (restarting || signal.aborted || answering > 0 || relay.runningTasks() > 0)
200
+ return;
201
+ // From here on task starts are refused, so none can begin while the restart is written.
202
+ restarting = true;
203
+ try {
204
+ await engines.requestHostVersion(next, now());
205
+ }
206
+ catch (error) {
207
+ restarting = false;
208
+ log(`Could not hand this bridge over to Andorra Code ${next}: ${error instanceof Error ? error.message : String(error)}`);
209
+ return;
210
+ }
211
+ if (answering > 0 || relay.runningTasks() > 0 || await relay.holdsWork()) {
212
+ await engines.withdrawHostVersion().catch(error => log(`Could not withdraw the restart: ${error instanceof Error ? error.message : String(error)}`));
213
+ restarting = false;
214
+ return;
215
+ }
216
+ log(`Restarting this bridge as Andorra Code ${next}.`);
217
+ stopped.abort();
218
+ };
219
+ const noteVersion = (version) => {
220
+ if (!options.engines || compareVersions(version, options.version) <= 0 || !ENGINE_VERSION.test(options.version))
221
+ return;
222
+ newer.add(version);
223
+ if (newer.size > MAX_NEWER_VERSIONS)
224
+ newer.delete([...newer].sort(compareVersions)[0]);
225
+ if (held !== undefined && compareVersions(version, held.version) > 0)
226
+ held = undefined;
227
+ };
228
+ let restartTimer;
229
+ if (options.engines) {
230
+ restartTimer = setInterval(() => { void restartIfIdle(); }, options.restartCheckMs ?? RESTART_CHECK_MS);
231
+ restartTimer.unref?.();
232
+ }
233
+ const answer = async (work) => {
234
+ answering += 1;
235
+ try {
236
+ return await work();
237
+ }
238
+ finally {
239
+ answering -= 1;
240
+ }
241
+ };
242
+ const watch = { noteVersion, settled: () => { void restartIfIdle(); }, restarting: () => restarting, answer };
243
+ try {
244
+ while (!signal.aborted) {
245
+ let credential;
246
+ try {
247
+ credential = stillGood(cached) ? cached : await options.token();
248
+ cached = credential;
249
+ }
250
+ catch (error) {
251
+ if (signal.aborted)
252
+ break;
253
+ if (error instanceof ControlError && error.code === 'unlinked') {
254
+ log('This machine is no longer linked to an Andorra account.');
255
+ return 'unlinked';
256
+ }
257
+ log(`Could not fetch a bridge token: ${error instanceof Error ? error.message : String(error)}`);
258
+ await sleep(backoff(attempt++), signal);
259
+ continue;
260
+ }
261
+ if (signal.aborted)
262
+ break;
263
+ const outcome = await runSession(options, relay, host, credential, connections, next => { cached = next; }, watch);
264
+ if (outcome.unlinked) {
265
+ log('This machine is no longer linked to an Andorra account.');
266
+ return 'unlinked';
267
+ }
268
+ if (unlinkedByHeartbeat)
269
+ return 'unlinked';
270
+ if (restarting)
271
+ return 'restart';
272
+ if (outcome.ready)
273
+ attempt = 0;
274
+ if (signal.aborted)
275
+ break;
276
+ if (outcome.code === CLOSE.replaced) {
277
+ log('Another bridge took over this environment, so this one is stopping.');
278
+ return 'stopped';
279
+ }
280
+ // A refused or lapsed token is never offered again.
281
+ if (outcome.code === CLOSE.unauthorized || outcome.code === CLOSE.expired)
282
+ cached = undefined;
283
+ if (outcome.code === CLOSE.unauthorized)
284
+ log('The relay rejected the bridge token; fetching a new one.');
285
+ else
286
+ log(`The relay connection ended${outcome.code === undefined ? '' : ` (code ${outcome.code})`}; reconnecting.`);
287
+ await sleep(backoff(attempt++), signal);
288
+ }
289
+ return unlinkedByHeartbeat ? 'unlinked' : restarting ? 'restart' : 'stopped';
290
+ }
291
+ finally {
292
+ clearInterval(heartbeatTimer);
293
+ clearInterval(launcherTimer);
294
+ clearInterval(restartTimer);
295
+ hostOptions.signal.removeEventListener('abort', forwardAbort);
296
+ stopped.abort();
297
+ await relay.close().catch(() => undefined);
298
+ }
299
+ }
300
+ function runSession(options, relay, host, credential, connections, onToken, versions) {
301
+ const { signal, log } = options;
302
+ return new Promise(resolve => {
303
+ let socket;
304
+ try {
305
+ socket = (options.socket ?? (url => new WebSocket(url)))(options.relayUrl);
306
+ }
307
+ catch (error) {
308
+ log(`Could not open the relay socket: ${error instanceof Error ? error.message : String(error)}`);
309
+ resolve({ ready: false });
310
+ return;
311
+ }
312
+ let ready = false;
313
+ let finished = false;
314
+ let refreshTimer;
315
+ let readyTimer;
316
+ let pingTimer;
317
+ let deadTimer;
318
+ let lastFrameAt = Date.now();
319
+ // viewer -> connectionId -> stop for the event sink registered on the relay
320
+ const sinks = new Map();
321
+ const sendText = (text) => {
322
+ if (socket.readyState !== SOCKET_OPEN)
323
+ return false;
324
+ try {
325
+ socket.send(text);
326
+ return true;
327
+ }
328
+ catch {
329
+ return false;
330
+ }
331
+ };
332
+ const send = (frame) => {
333
+ const text = JSON.stringify(frame);
334
+ return Buffer.byteLength(text) <= MAX_FRAME_BYTES && sendText(text);
335
+ };
336
+ /** An engine event for one link; one too large for the relay is replaced by a small notice the desktop can show. */
337
+ const sendEvent = (viewer, connectionId, engineFrame) => {
338
+ const text = JSON.stringify({ t: 'event', viewer, connectionId, frame: engineFrame });
339
+ if (Buffer.byteLength(text) <= MAX_FRAME_BYTES) {
340
+ sendText(text);
341
+ return;
342
+ }
343
+ log(`Dropped a ${engineFrame.event} event for a desktop: it was larger than the relay link allows.`);
344
+ send({ t: 'event', viewer, connectionId, frame: { engine: engineFrame.engine, event: 'remote.engine.dropped', data: { event: engineFrame.event, reason: 'too-large' } } });
345
+ };
346
+ const release = (viewer, connectionId) => {
347
+ const stops = sinks.get(viewer);
348
+ stops?.get(connectionId)?.();
349
+ stops?.delete(connectionId);
350
+ connections.delete(viewer, connectionId);
351
+ if (stops && stops.size === 0)
352
+ sinks.delete(viewer);
353
+ };
354
+ const finish = (outcome) => {
355
+ if (finished)
356
+ return;
357
+ finished = true;
358
+ clearTimeout(refreshTimer);
359
+ clearTimeout(readyTimer);
360
+ clearInterval(pingTimer);
361
+ clearTimeout(deadTimer);
362
+ signal.removeEventListener('abort', onAbort);
363
+ // The socket is gone, so its sinks have nowhere to deliver. The relay keeps its connections and runs for the next socket.
364
+ for (const [viewer, stops] of [...sinks])
365
+ for (const connectionId of [...stops.keys()])
366
+ release(viewer, connectionId);
367
+ try {
368
+ socket.close(1000);
369
+ }
370
+ catch { }
371
+ resolve({ ready, ...outcome });
372
+ };
373
+ const onAbort = () => finish({});
374
+ signal.addEventListener('abort', onAbort, { once: true });
375
+ const scheduleRefresh = (expiresAt) => {
376
+ clearTimeout(refreshTimer);
377
+ refreshTimer = setTimeout(() => void refresh(), refreshDelayMs(expiresAt));
378
+ refreshTimer.unref?.();
379
+ };
380
+ const refresh = async () => {
381
+ try {
382
+ const next = await options.token();
383
+ if (finished)
384
+ return;
385
+ onToken(next);
386
+ send({ t: 'auth', token: next.token });
387
+ const delay = refreshDelayMs(next.expiresAt);
388
+ clearTimeout(refreshTimer);
389
+ refreshTimer = setTimeout(() => void refresh(), Math.max(delay, MIN_REFRESH_GAP_MS));
390
+ refreshTimer.unref?.();
391
+ }
392
+ catch (error) {
393
+ if (finished)
394
+ return;
395
+ if (error instanceof ControlError && error.code === 'unlinked') {
396
+ finish({ unlinked: true });
397
+ return;
398
+ }
399
+ log(`Could not refresh the bridge token: ${error instanceof Error ? error.message : String(error)}`);
400
+ clearTimeout(refreshTimer);
401
+ refreshTimer = setTimeout(() => void refresh(), REFRESH_RETRY_MS);
402
+ refreshTimer.unref?.();
403
+ }
404
+ };
405
+ const answerWith = (viewer, id, answer) => {
406
+ if (send({ t: 'answer', viewer, id, answer }))
407
+ return;
408
+ send({ t: 'answer', viewer, id, answer: { error: { code: 'remote', message: 'The answer was larger than the relay link allows.' } } });
409
+ };
410
+ const handle = async (frame) => {
411
+ const { t, viewer, id, connectionId } = frame;
412
+ if (t === 'ready') {
413
+ if (ready)
414
+ return;
415
+ ready = true;
416
+ clearTimeout(readyTimer);
417
+ // Nothing but the hello goes out before ready, the refresh included.
418
+ scheduleRefresh(credential.expiresAt);
419
+ pingTimer = setInterval(() => send({ t: 'ping' }), CLIENT_PING_MS);
420
+ pingTimer.unref?.();
421
+ watchForSilence();
422
+ return;
423
+ }
424
+ if (t === 'pong')
425
+ return;
426
+ if (typeof viewer !== 'string')
427
+ return;
428
+ if (t === 'viewer-gone') {
429
+ // The desktop's socket went away, perhaps only for a moment: stop sending it events, but keep its connections
430
+ // (and their terminals) so it can pick them up again. The relay's sweep reclaims a connection left without a sink.
431
+ for (const connection of [...(sinks.get(viewer)?.keys() ?? [])])
432
+ release(viewer, connection);
433
+ return;
434
+ }
435
+ if (t === 'open') {
436
+ if (typeof connectionId !== 'string' || (frame.viewerWorkspaceId !== undefined && typeof frame.viewerWorkspaceId !== 'string'))
437
+ return;
438
+ // The relay is not trusted to have checked it: an open that names anything but a plain major.minor.patch is refused,
439
+ // while one that names no version is an older desktop and gets the host's own engine.
440
+ if (frame.version !== undefined && (typeof frame.version !== 'string' || !ENGINE_VERSION.test(frame.version))) {
441
+ log('Refused a desktop connection that named a malformed engine version.');
442
+ return;
443
+ }
444
+ const version = frame.version;
445
+ if (version !== undefined)
446
+ versions.noteVersion(version);
447
+ release(viewer, connectionId);
448
+ send({ t: 'opened', viewer, connectionId, host });
449
+ const sink = (engineFrame) => { sendEvent(viewer, connectionId, engineFrame); };
450
+ const stop = relay.events(viewer, connectionId, frame.viewerWorkspaceId, sink, () => release(viewer, connectionId), version);
451
+ let stops = sinks.get(viewer);
452
+ if (!stops) {
453
+ stops = new Map();
454
+ sinks.set(viewer, stops);
455
+ }
456
+ stops.set(connectionId, stop);
457
+ connections.add(viewer, connectionId);
458
+ return;
459
+ }
460
+ if (t === 'close') {
461
+ if (typeof connectionId !== 'string')
462
+ return;
463
+ release(viewer, connectionId);
464
+ relay.disconnect(viewer, connectionId);
465
+ return;
466
+ }
467
+ if (t === 'request') {
468
+ if (typeof id !== 'string')
469
+ return;
470
+ if (!isRecord(frame.body)) {
471
+ answerWith(viewer, id, { error: { code: 'invalid-params', message: 'A request body is required.' } });
472
+ return;
473
+ }
474
+ if (versions.restarting() && TASK_START_METHODS.has(frame.body.method)) {
475
+ answerWith(viewer, id, { error: { code: 'busy', message: RESTARTING_MESSAGE } });
476
+ return;
477
+ }
478
+ const body = frame.body;
479
+ await versions.answer(async () => { answerWith(viewer, id, await relay.request(viewer, body)); });
480
+ versions.settled();
481
+ return;
482
+ }
483
+ if (t === 'host') {
484
+ const { op } = frame;
485
+ if (typeof id !== 'string' || typeof op !== 'string')
486
+ return;
487
+ if (!HOST_OPERATIONS.has(op)) {
488
+ answerWith(viewer, id, { error: { code: 'invalid-params', message: 'Unknown host operation' } });
489
+ return;
490
+ }
491
+ const params = isRecord(frame.params) ? frame.params : {};
492
+ await versions.answer(async () => {
493
+ try {
494
+ answerWith(viewer, id, { result: await hostOperation(options.directory, op, params, host) });
495
+ }
496
+ catch (error) {
497
+ const code = error instanceof HostOperationError ? error.code : 'remote';
498
+ answerWith(viewer, id, { error: { code, message: error instanceof Error ? error.message : String(error) } });
499
+ }
500
+ });
501
+ }
502
+ };
503
+ // A socket that has carried no frame of any kind for CLIENT_DEAD_MS is dead, even if the OS has not noticed.
504
+ const watchForSilence = () => {
505
+ const quiet = Date.now() - lastFrameAt;
506
+ if (quiet >= CLIENT_DEAD_MS) {
507
+ log('The relay connection stopped answering; reconnecting.');
508
+ finish({});
509
+ return;
510
+ }
511
+ deadTimer = setTimeout(watchForSilence, CLIENT_DEAD_MS - quiet);
512
+ deadTimer.unref?.();
513
+ };
514
+ socket.addEventListener('open', () => {
515
+ send({ t: 'hello', v: PROTOCOL_VERSION, role: 'bridge', token: credential.token, host });
516
+ readyTimer = setTimeout(() => { log('The relay did not answer the bridge hello in time.'); finish({}); }, READY_TIMEOUT_MS);
517
+ readyTimer.unref?.();
518
+ });
519
+ socket.addEventListener('message', event => {
520
+ const data = event.data;
521
+ lastFrameAt = Date.now();
522
+ if (typeof data !== 'string' || Buffer.byteLength(data) > MAX_FRAME_BYTES)
523
+ return;
524
+ let frame;
525
+ try {
526
+ frame = JSON.parse(data);
527
+ }
528
+ catch {
529
+ return;
530
+ }
531
+ if (!isRecord(frame))
532
+ return;
533
+ handle(frame).catch(error => log(`A relay frame failed: ${error instanceof Error ? error.message : String(error)}`));
534
+ });
535
+ socket.addEventListener('close', event => finish({ code: event.code }));
536
+ socket.addEventListener('error', () => finish({}));
537
+ if (signal.aborted)
538
+ finish({});
539
+ });
540
+ }
@@ -0,0 +1,38 @@
1
+ import { AppServerError } from '../app-server/error.js';
2
+ import type { RelayAnswer, RelayRequestBody } from '../remote/engine-pool.js';
3
+ import { type EngineFrame, type Host } from './protocol.js';
4
+ /** Why a link ended: a reason the relay sent, or `relay` when the socket to the relay itself was lost. */
5
+ export type RelayClosedReason = 'offline' | 'not-found' | 'slow' | 'unlinked' | 'limit' | 'relay';
6
+ /** A relay socket that has not opened by then is abandoned and the dial fails as a network error. */
7
+ export declare const CONNECT_TIMEOUT_MS = 10000;
8
+ /** A link, request or host call the relay ended for `reason`. */
9
+ export declare class RelayClosedError extends AppServerError {
10
+ readonly reason: RelayClosedReason;
11
+ constructor(reason: RelayClosedReason);
12
+ }
13
+ export interface RelayLinkOptions {
14
+ relayUrl: string;
15
+ /** The desktop's Andorra access token. An AppServerError it throws (login-required) is passed to the caller unchanged. */
16
+ token: () => Promise<string>;
17
+ socket?: (url: string) => WebSocket;
18
+ /** The engine's own version; the hello carries it only when it is a plain major.minor.patch. */
19
+ version?: () => Promise<string | undefined>;
20
+ backoffMs?: (attempt: number) => number;
21
+ }
22
+ /**
23
+ * The desktop engine's one socket to Andorra's relay, shared by every machine it reaches. It is dialled on first use
24
+ * and again on the first call after it drops.
25
+ */
26
+ export declare class RelayLink {
27
+ #private;
28
+ constructor(options: RelayLinkOptions);
29
+ open(env: string, connectionId: string, viewerWorkspaceId: string | undefined, onEvent: (frame: EngineFrame) => void, onClosed: (reason: RelayClosedReason) => void): Promise<{
30
+ host: Host;
31
+ }>;
32
+ request(env: string, body: RelayRequestBody, deadlineAt: number): Promise<RelayAnswer>;
33
+ host(env: string, op: string, params: Record<string, unknown>, deadlineAt: number): Promise<unknown>;
34
+ close(env: string, connectionId: string): void;
35
+ presence(): Promise<string[]>;
36
+ /** Ends the link for good. Pending calls reject with `error`: by default, that the engine is shutting down. */
37
+ dispose(error?: Error): void;
38
+ }