@andorra-labs/code 0.1.16 → 0.1.18

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 (236) 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-execution.js +108 -19
  4. package/dist/src/agent-mcp-catalog.js +1 -0
  5. package/dist/src/agent-mcp.d.ts +3 -0
  6. package/dist/src/agent-mcp.js +33 -1
  7. package/dist/src/andorra/entry.d.ts +10 -0
  8. package/dist/src/andorra/entry.js +18 -4
  9. package/dist/src/andorra/errors.js +3 -0
  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 +30 -44
  21. package/dist/src/app-server/protocol.js +5 -1
  22. package/dist/src/app-server/workspace.d.ts +108 -0
  23. package/dist/src/app-server/workspace.js +608 -11
  24. package/dist/src/app-server.d.ts +390 -33
  25. package/dist/src/app-server.js +3033 -565
  26. package/dist/src/attachments.d.ts +10 -0
  27. package/dist/src/attachments.js +102 -7
  28. package/dist/src/automation-tool.js +2 -1
  29. package/dist/src/bridge/cloud.d.ts +27 -0
  30. package/dist/src/bridge/cloud.js +187 -0
  31. package/dist/src/bridge/command.d.ts +30 -0
  32. package/dist/src/bridge/command.js +359 -0
  33. package/dist/src/bridge/control.d.ts +70 -0
  34. package/dist/src/bridge/control.js +238 -0
  35. package/dist/src/bridge/engines.d.ts +90 -0
  36. package/dist/src/bridge/engines.js +601 -0
  37. package/dist/src/bridge/github.d.ts +108 -0
  38. package/dist/src/bridge/github.js +378 -0
  39. package/dist/src/bridge/host-ops.d.ts +9 -0
  40. package/dist/src/bridge/host-ops.js +139 -0
  41. package/dist/src/bridge/host.d.ts +47 -0
  42. package/dist/src/bridge/host.js +543 -0
  43. package/dist/src/bridge/link.d.ts +38 -0
  44. package/dist/src/bridge/link.js +508 -0
  45. package/dist/src/bridge/login-link.d.ts +29 -0
  46. package/dist/src/bridge/login-link.js +54 -0
  47. package/dist/src/bridge/protocol.d.ts +136 -0
  48. package/dist/src/bridge/protocol.js +11 -0
  49. package/dist/src/bridge/store.d.ts +12 -0
  50. package/dist/src/bridge/store.js +61 -0
  51. package/dist/src/bridge/wording.d.ts +6 -0
  52. package/dist/src/bridge/wording.js +10 -0
  53. package/dist/src/browser-server.js +7 -1
  54. package/dist/src/browser-ui/tokens.css +1 -1
  55. package/dist/src/bug-report-attachments.d.ts +48 -0
  56. package/dist/src/bug-report-attachments.js +327 -0
  57. package/dist/src/bug-report.d.ts +23 -3
  58. package/dist/src/bug-report.js +72 -9
  59. package/dist/src/change-authors.d.ts +41 -0
  60. package/dist/src/change-authors.js +146 -0
  61. package/dist/src/cli.d.ts +1 -3
  62. package/dist/src/cli.js +191 -35
  63. package/dist/src/codex-provider.js +1 -1
  64. package/dist/src/coding-tools.js +24 -17
  65. package/dist/src/command-screens.d.ts +6 -0
  66. package/dist/src/command-screens.js +14 -11
  67. package/dist/src/commands.d.ts +15 -3
  68. package/dist/src/commands.js +2 -1
  69. package/dist/src/compaction-phrases.js +1 -1
  70. package/dist/src/completion.js +89 -8
  71. package/dist/src/config.d.ts +71 -3
  72. package/dist/src/config.js +205 -78
  73. package/dist/src/context-budget.js +15 -2
  74. package/dist/src/deadline.js +13 -1
  75. package/dist/src/decision/DecisionEngine.d.ts +2 -0
  76. package/dist/src/decision/DecisionManager.d.ts +11 -0
  77. package/dist/src/decision/DecisionManager.js +36 -0
  78. package/dist/src/decision/applyTaskKind.d.ts +8 -0
  79. package/dist/src/decision/applyTaskKind.js +53 -0
  80. package/dist/src/decision/checks.js +1 -1
  81. package/dist/src/decision/hostedPolicy.js +2 -1
  82. package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +2 -0
  83. package/dist/src/decision/providers/AndorraDecisionProvider.js +12 -0
  84. package/dist/src/decision/requestPhrases.js +0 -1
  85. package/dist/src/decision/taskKind.d.ts +52 -0
  86. package/dist/src/decision/taskKind.js +76 -0
  87. package/dist/src/decision/types.d.ts +1 -1
  88. package/dist/src/default-graph.js +1 -1
  89. package/dist/src/efficiency.d.ts +5 -0
  90. package/dist/src/efficiency.js +5 -1
  91. package/dist/src/effort-routing.d.ts +27 -0
  92. package/dist/src/effort-routing.js +34 -0
  93. package/dist/src/evidence.d.ts +110 -0
  94. package/dist/src/evidence.js +195 -0
  95. package/dist/src/file-diff.d.ts +4 -0
  96. package/dist/src/file-diff.js +2 -1
  97. package/dist/src/github-app/agent-writes.d.ts +102 -0
  98. package/dist/src/github-app/agent-writes.js +320 -0
  99. package/dist/src/github-app/client.d.ts +368 -0
  100. package/dist/src/github-app/client.js +830 -0
  101. package/dist/src/github-app/event-source.d.ts +208 -0
  102. package/dist/src/github-app/event-source.js +684 -0
  103. package/dist/src/github-app/metrics.d.ts +32 -0
  104. package/dist/src/github-app/metrics.js +49 -0
  105. package/dist/src/github-app/review-loop.d.ts +274 -0
  106. package/dist/src/github-app/review-loop.js +1177 -0
  107. package/dist/src/github-app/review-node.d.ts +81 -0
  108. package/dist/src/github-app/review-node.js +205 -0
  109. package/dist/src/github-app/review-post.d.ts +73 -0
  110. package/dist/src/github-app/review-post.js +139 -0
  111. package/dist/src/github-app/review-text.d.ts +107 -0
  112. package/dist/src/github-app/review-text.js +1133 -0
  113. package/dist/src/github-app/review-threads.d.ts +47 -0
  114. package/dist/src/github-app/review-threads.js +107 -0
  115. package/dist/src/github-app/reviewer.d.ts +121 -0
  116. package/dist/src/github-app/reviewer.js +598 -0
  117. package/dist/src/github-app/store.d.ts +59 -0
  118. package/dist/src/github-app/store.js +148 -0
  119. package/dist/src/github-app/triggers.d.ts +141 -0
  120. package/dist/src/github-app/triggers.js +441 -0
  121. package/dist/src/github-names.d.ts +15 -0
  122. package/dist/src/github-names.js +15 -0
  123. package/dist/src/glob-search.d.ts +61 -0
  124. package/dist/src/glob-search.js +180 -0
  125. package/dist/src/graph-health.js +6 -1
  126. package/dist/src/graph-manager-chat.js +1 -1
  127. package/dist/src/graph-preview.d.ts +48 -0
  128. package/dist/src/graph-preview.js +56 -0
  129. package/dist/src/graph-provider-portability.js +2 -1
  130. package/dist/src/graph-runner.js +65 -4
  131. package/dist/src/graph-server.js +7 -5
  132. package/dist/src/graph-sync.js +3 -3
  133. package/dist/src/graph-ui/app.js +121 -7
  134. package/dist/src/graph-ui/icons.js +2 -1
  135. package/dist/src/graph-ui/studio.js +15 -1
  136. package/dist/src/graph-ui/tokens.css +1 -1
  137. package/dist/src/graphs.d.ts +40 -1
  138. package/dist/src/graphs.js +164 -15
  139. package/dist/src/hardened-runtime.js +32 -21
  140. package/dist/src/image-input.d.ts +16 -0
  141. package/dist/src/image-input.js +41 -0
  142. package/dist/src/membership.d.ts +10 -0
  143. package/dist/src/membership.js +19 -4
  144. package/dist/src/model-health-cache.js +1 -1
  145. package/dist/src/model-metadata.d.ts +6 -0
  146. package/dist/src/model-metadata.js +35 -15
  147. package/dist/src/model-override.d.ts +2 -1
  148. package/dist/src/model-override.js +9 -0
  149. package/dist/src/model-relay/local.d.ts +116 -0
  150. package/dist/src/model-relay/local.js +468 -0
  151. package/dist/src/model-relay/remote.d.ts +129 -0
  152. package/dist/src/model-relay/remote.js +252 -0
  153. package/dist/src/model-relay/runs.d.ts +34 -0
  154. package/dist/src/model-relay/runs.js +146 -0
  155. package/dist/src/model-relay/wire.d.ts +5 -0
  156. package/dist/src/model-relay/wire.js +5 -0
  157. package/dist/src/model-tiers.d.ts +3 -0
  158. package/dist/src/model-tiers.js +3 -3
  159. package/dist/src/project-registry.d.ts +21 -0
  160. package/dist/src/project-registry.js +74 -0
  161. package/dist/src/provider-engine.d.ts +13 -1
  162. package/dist/src/provider-engine.js +74 -0
  163. package/dist/src/provider-import.d.ts +0 -12
  164. package/dist/src/provider-import.js +7 -195
  165. package/dist/src/providers.d.ts +28 -2
  166. package/dist/src/providers.js +59 -12
  167. package/dist/src/pull-request-logs.d.ts +12 -1
  168. package/dist/src/pull-request-logs.js +14 -3
  169. package/dist/src/pull-requests.d.ts +338 -8
  170. package/dist/src/pull-requests.js +482 -53
  171. package/dist/src/react-runtime.js +99 -16
  172. package/dist/src/remote/engine-pool.d.ts +88 -4
  173. package/dist/src/remote/engine-pool.js +367 -90
  174. package/dist/src/remote/roots.d.ts +19 -0
  175. package/dist/src/remote/roots.js +45 -7
  176. package/dist/src/remote/types.d.ts +0 -44
  177. package/dist/src/run-control.d.ts +7 -0
  178. package/dist/src/run-control.js +23 -0
  179. package/dist/src/run-records.d.ts +7 -2
  180. package/dist/src/run-records.js +71 -6
  181. package/dist/src/runtime.d.ts +34 -2
  182. package/dist/src/runtime.js +18 -2
  183. package/dist/src/session-changes.d.ts +35 -0
  184. package/dist/src/session-changes.js +194 -6
  185. package/dist/src/session-monitor.js +2 -1
  186. package/dist/src/session-reaper.d.ts +1 -1
  187. package/dist/src/session-reaper.js +6 -1
  188. package/dist/src/session-summary.d.ts +2 -1
  189. package/dist/src/session-summary.js +2 -1
  190. package/dist/src/sessions.d.ts +35 -1
  191. package/dist/src/sessions.js +70 -4
  192. package/dist/src/skills/bundled/bug-report/SKILL.md +51 -7
  193. package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
  194. package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
  195. package/dist/src/skills/bundled/provenance.json +3 -3
  196. package/dist/src/skills/runtime-skills.js +1 -1
  197. package/dist/src/task-checkout.d.ts +141 -0
  198. package/dist/src/task-checkout.js +558 -0
  199. package/dist/src/telemetry/emitter.d.ts +15 -0
  200. package/dist/src/telemetry/emitter.js +35 -1
  201. package/dist/src/telemetry/schema.d.ts +25 -2
  202. package/dist/src/telemetry/schema.js +52 -4
  203. package/dist/src/telemetry/surface.d.ts +2 -1
  204. package/dist/src/telemetry/surface.js +4 -1
  205. package/dist/src/terminal-ui.d.ts +1 -0
  206. package/dist/src/terminal-ui.js +10 -3
  207. package/dist/src/test-edit-guard.d.ts +37 -0
  208. package/dist/src/test-edit-guard.js +216 -3
  209. package/dist/src/thinking-level-detect.d.ts +11 -0
  210. package/dist/src/thinking-level-detect.js +47 -0
  211. package/dist/src/thinking-levels.d.ts +30 -0
  212. package/dist/src/thinking-levels.js +124 -0
  213. package/dist/src/timers.d.ts +3 -0
  214. package/dist/src/tool-catalog.js +1 -1
  215. package/dist/src/tools.js +59 -9
  216. package/dist/src/transcript.js +1 -1
  217. package/dist/src/types.d.ts +34 -0
  218. package/package.json +6 -1
  219. package/dist/src/remote/cert.d.ts +0 -11
  220. package/dist/src/remote/cert.js +0 -87
  221. package/dist/src/remote/client.d.ts +0 -119
  222. package/dist/src/remote/client.js +0 -544
  223. package/dist/src/remote/command.d.ts +0 -4
  224. package/dist/src/remote/command.js +0 -194
  225. package/dist/src/remote/errors.d.ts +0 -11
  226. package/dist/src/remote/errors.js +0 -14
  227. package/dist/src/remote/network.d.ts +0 -22
  228. package/dist/src/remote/network.js +0 -102
  229. package/dist/src/remote/pairing.d.ts +0 -63
  230. package/dist/src/remote/pairing.js +0 -299
  231. package/dist/src/remote/pem.d.ts +0 -2
  232. package/dist/src/remote/pem.js +0 -7
  233. package/dist/src/remote/serve.d.ts +0 -68
  234. package/dist/src/remote/serve.js +0 -244
  235. package/dist/src/remote/server.d.ts +0 -21
  236. package/dist/src/remote/server.js +0 -406
@@ -0,0 +1,359 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { hostname } from 'node:os';
3
+ import { AUTH_DEPLOYMENT } from '../auth/deployment.js';
4
+ import { changeConfigFile, configDirectory, loadConfig } from '../config.js';
5
+ import { ensureWorkFolder, MAX_BOOT_INPUT_BYTES, runCloudBoot } from './cloud.js';
6
+ import { ControlError, environmentToken, heartbeat, linkPoll, linkStart } from './control.js';
7
+ import { engineStoreFromEnvironment, HOST_RESTART_EXIT_CODE } from './engines.js';
8
+ import { installCredentialHelperFromEnvironment, runGitCredential } from './github.js';
9
+ import { relayUrlFromEnvironment, runBridgeHost } from './host.js';
10
+ import { linkAddress, openCommand, openOnThisComputer, overSshFromEnvironment } from './login-link.js';
11
+ import { clearBridgeIdentity, readBridgeIdentity, shareFolder, writeBridgeIdentity } from './store.js';
12
+ import { bridgeCommand, launchedFromEnvironment } from './wording.js';
13
+ export { bridgeCommand };
14
+ export function bridgeUsage(launched = launchedFromEnvironment()) {
15
+ const rows = [
16
+ ['link [--yes] [--no-open]', 'link this machine to your Andorra account'],
17
+ ['run', 'serve this machine until stopped (Ctrl+C)'],
18
+ ['status', 'show whether this machine is linked'],
19
+ ['unlink', 'forget the link on this machine'],
20
+ ];
21
+ const width = Math.max(...rows.map(([name]) => bridgeCommand(name, launched).length)) + 2;
22
+ const lines = rows.map(([name, description]) => `${bridgeCommand(name, launched).padEnd(width)}${description}`);
23
+ lines.push(bridgeCommand('folders list|add <path>|remove <id>', launched));
24
+ return `Usage: ${lines.join('\n ')}`;
25
+ }
26
+ export const BRIDGE_USAGE = bridgeUsage(false);
27
+ const POLL_INTERVAL_MS = 3000;
28
+ export function cloudApiBase(environment) {
29
+ const configured = environment.ANDORRA_API_BASE_URL?.trim();
30
+ return configured?.startsWith('https://') ? configured : undefined;
31
+ }
32
+ /** How often a running bridge checks that this machine is still linked locally (bridge.json unchanged). */
33
+ export const IDENTITY_CHECK_MS = 10_000;
34
+ const MAX_NAME_LENGTH = 64;
35
+ const expired = (launched) => `That code expired. Run "${bridgeCommand('link', launched)}" again.`;
36
+ const refused = (launched) => `Not linked. If that was not your account, nothing on this machine was shared. Ask the account owner to remove the machine in Settings → Environments, then run "${bridgeCommand('link', launched)}" again.`;
37
+ const noTerminal = (launched) => `Not linked: there is no terminal to confirm the account in. If that is your account, run "${bridgeCommand('link --yes', launched)}" again.`;
38
+ function message(error) { return error instanceof Error ? error.message : String(error); }
39
+ function defaultSleep(ms) {
40
+ return new Promise(resolveSleep => setTimeout(resolveSleep, ms));
41
+ }
42
+ async function askOnTerminal(question) {
43
+ const { createInterface } = await import('node:readline/promises');
44
+ const terminal = createInterface({ input: process.stdin, output: process.stdout });
45
+ try {
46
+ return await terminal.question(`${question} `);
47
+ }
48
+ finally {
49
+ terminal.close();
50
+ }
51
+ }
52
+ /** At most MAX_BOOT_INPUT_BYTES + 1 bytes of stdin: enough to tell a start code from something that is not one. */
53
+ async function readBoundedStdin() {
54
+ const chunks = [];
55
+ let size = 0;
56
+ for await (const chunk of process.stdin) {
57
+ const bytes = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
58
+ chunks.push(bytes);
59
+ size += bytes.length;
60
+ if (size > MAX_BOOT_INPUT_BYTES)
61
+ break;
62
+ }
63
+ return Buffer.concat(chunks).subarray(0, MAX_BOOT_INPUT_BYTES + 1).toString('utf8');
64
+ }
65
+ async function offerLoginLink(address, print, skipOpen, interactive, dependencies) {
66
+ const overSsh = dependencies.overSsh ?? overSshFromEnvironment(process.env);
67
+ const platform = dependencies.platform ?? process.platform;
68
+ // A script, container or service has nobody to show a window to, so only a person at a terminal gets an open attempt,
69
+ // and only where the installed desktop app handles the link (Windows and macOS; the Linux build registers no scheme).
70
+ const appHandlesLink = openCommand(platform, address) !== undefined;
71
+ if (!overSsh && !skipOpen && interactive && appHandlesLink) {
72
+ const opened = await (dependencies.open ?? openOnThisComputer)(address).catch(() => false);
73
+ if (opened) {
74
+ print('Opened Andorra Code on this computer to fill it in.');
75
+ return;
76
+ }
77
+ }
78
+ print('Or open this link on your computer to fill it in:');
79
+ print(address);
80
+ }
81
+ async function link(args, print, apiBase, dependencies) {
82
+ const launched = dependencies.launched ?? launchedFromEnvironment();
83
+ if (args.some(arg => arg !== '--yes' && arg !== '--no-open')) {
84
+ print(bridgeUsage(launched));
85
+ return 1;
86
+ }
87
+ const assumeYes = args.includes('--yes');
88
+ const skipOpen = args.includes('--no-open');
89
+ const sleep = dependencies.sleep ?? defaultSleep;
90
+ const now = dependencies.now ?? Date.now;
91
+ const directory = configDirectory();
92
+ const existing = await readBridgeIdentity(directory);
93
+ if (existing) {
94
+ print(`This machine is already linked as ${existing.name}. Run "${bridgeCommand('unlink', launched)}" first.`);
95
+ return 1;
96
+ }
97
+ const interactive = dependencies.interactive ?? process.stdin.isTTY === true;
98
+ // Without a terminal the account cannot be confirmed, so no code is issued for anyone to claim.
99
+ if (!assumeYes && !interactive) {
100
+ print(noTerminal(launched));
101
+ return 1;
102
+ }
103
+ // The secret is made here and never leaves this machine: the service gets only its hash. It stays in memory until
104
+ // the person confirms the account, and is written to bridge.json only then.
105
+ const secret = randomBytes(32).toString('base64url');
106
+ try {
107
+ const started = await linkStart(apiBase, createHash('sha256').update(secret).digest('hex'));
108
+ const address = linkAddress(started.code);
109
+ print('Enter this code in Andorra Code under Settings → Environments → Add a machine:');
110
+ print(started.code);
111
+ await offerLoginLink(address, print, skipOpen, interactive, dependencies);
112
+ const expiresAt = Date.parse(started.expiresAt);
113
+ for (;;) {
114
+ try {
115
+ const polled = await linkPoll(apiBase, started.pollToken);
116
+ if (polled.status === 'linked') {
117
+ // Whoever typed the code owns the machine from now on, so the person here confirms that account first.
118
+ print(polled.account
119
+ ? `This machine was claimed by the Andorra account ${polled.account}.`
120
+ : 'This machine was claimed by an Andorra account whose address could not be read.');
121
+ if (!assumeYes) {
122
+ if (!interactive) {
123
+ print(noTerminal(launched));
124
+ return 1;
125
+ }
126
+ const answer = (await (dependencies.ask ?? askOnTerminal)('Link it to that account? [y/N]')).trim().toLowerCase();
127
+ if (answer !== 'y' && answer !== 'yes') {
128
+ print(refused(launched));
129
+ return 1;
130
+ }
131
+ }
132
+ const linkedName = polled.name.trim().slice(0, MAX_NAME_LENGTH) || hostname().slice(0, MAX_NAME_LENGTH);
133
+ await writeBridgeIdentity(directory, { environmentId: polled.environmentId, name: linkedName, secret, linkedAt: new Date(now()).toISOString() });
134
+ print(`Linked as ${linkedName}. Run "${bridgeCommand('run', launched)}" to serve this machine.`);
135
+ return 0;
136
+ }
137
+ }
138
+ catch (error) {
139
+ if (!(error instanceof ControlError) || error.code === 'code_expired' || error.code === 'unlinked')
140
+ throw error;
141
+ // A transient network or server error: keep polling until the code itself runs out.
142
+ }
143
+ if (!Number.isNaN(expiresAt) && now() >= expiresAt)
144
+ throw new ControlError('code_expired', expired(launched));
145
+ await sleep(POLL_INTERVAL_MS);
146
+ if (!Number.isNaN(expiresAt) && now() >= expiresAt)
147
+ throw new ControlError('code_expired', expired(launched));
148
+ }
149
+ }
150
+ catch (error) {
151
+ if (error instanceof ControlError && error.code === 'code_expired')
152
+ print(expired(launched));
153
+ else if (error instanceof ControlError)
154
+ print(`Could not reach Andorra: ${error.message}`);
155
+ else
156
+ print(`Could not link this machine: ${message(error)}`);
157
+ return 1;
158
+ }
159
+ }
160
+ // SIGBREAK is Ctrl+Break on a Windows console; Node ends the process at once when nothing listens for it.
161
+ // On Windows closing the console ends every process attached to it, installs included, so SIGHUP keeps its default there.
162
+ function stopSignals(platform) {
163
+ return platform === 'win32' ? ['SIGINT', 'SIGTERM', 'SIGBREAK'] : ['SIGINT', 'SIGTERM', 'SIGBREAK', 'SIGHUP', 'SIGQUIT'];
164
+ }
165
+ // A hang-up or termination often arrives twice for one stop (a closed terminal signals the launcher's whole group, and the
166
+ // launcher passes it on as well), so those stay caught until shutdown ends; a second Ctrl+C still ends the process at once.
167
+ const REPEATED_DELIVERIES = new Set(['SIGTERM', 'SIGHUP', 'SIGQUIT']);
168
+ /** Resolves on the first stop signal or on `signal` aborting; `release` stops catching the signals still held. */
169
+ function waitForStop(signal, platform) {
170
+ const names = stopSignals(platform);
171
+ const ignore = () => undefined;
172
+ let resolveStop = () => undefined;
173
+ const stopped = new Promise(resolvePromise => { resolveStop = resolvePromise; });
174
+ let stopping = false;
175
+ const stop = () => {
176
+ if (stopping)
177
+ return;
178
+ stopping = true;
179
+ for (const name of names) {
180
+ process.removeListener(name, stop);
181
+ if (REPEATED_DELIVERIES.has(name))
182
+ process.on(name, ignore);
183
+ }
184
+ resolveStop();
185
+ };
186
+ for (const name of names)
187
+ process.on(name, stop);
188
+ signal.addEventListener('abort', stop, { once: true });
189
+ return { stopped, release: () => { for (const name of names)
190
+ process.removeListener(name, ignore); } };
191
+ }
192
+ /** Whether a process exists; a process this user may not signal still exists. */
193
+ function processExists(pid) {
194
+ try {
195
+ process.kill(pid, 0);
196
+ return true;
197
+ }
198
+ catch (error) {
199
+ return error.code === 'EPERM';
200
+ }
201
+ }
202
+ async function run(print, apiBase, dependencies) {
203
+ const launched = dependencies.launched ?? launchedFromEnvironment();
204
+ const directory = configDirectory();
205
+ const identity = await readBridgeIdentity(directory);
206
+ if (!identity) {
207
+ print(`This machine is not linked. Run "${bridgeCommand('link', launched)}" first.`);
208
+ return 1;
209
+ }
210
+ const controller = new AbortController();
211
+ const stopWatch = waitForStop(controller.signal, dependencies.platform ?? process.platform);
212
+ const stopWatcher = stopWatch.stopped.then(() => controller.abort());
213
+ // "bridge unlink" in another terminal removes bridge.json; a relink replaces it. Either way this process must stop
214
+ // serving with the identity it started with, so it checks the file every IDENTITY_CHECK_MS and before every token.
215
+ let unlinkedHere = false;
216
+ const stillLinked = async () => {
217
+ const current = await readBridgeIdentity(directory);
218
+ const same = current?.environmentId === identity.environmentId && current.secret === identity.secret;
219
+ if (!same && !unlinkedHere) {
220
+ unlinkedHere = true;
221
+ controller.abort();
222
+ }
223
+ return same;
224
+ };
225
+ const identityCheck = setInterval(() => { void stillLinked(); }, IDENTITY_CHECK_MS);
226
+ identityCheck.unref?.();
227
+ print(`Serving as ${identity.name}. Press Ctrl+C to stop.`);
228
+ const version = dependencies.version ?? '0.0.0';
229
+ // Under the bridge launcher tasks run on the engine version of their desktop; a plain "andorra bridge run" has no store.
230
+ const engines = engineStoreFromEnvironment(process.env, { hostVersion: version });
231
+ const launcherPid = Number(process.env.ANDORRA_BRIDGE_LAUNCHER_PID);
232
+ const launcherAlive = Number.isInteger(launcherPid) && launcherPid > 0 ? () => processExists(launcherPid) : undefined;
233
+ try {
234
+ if (process.env.ANDORRA_CLOUD === '1') {
235
+ await ensureWorkFolder(directory, dependencies.workDirectory).catch(error => print(`Could not share the work folder: ${message(error)}`));
236
+ // Clones made by an earlier engine name this file; it is pointed at the engine now running.
237
+ await installCredentialHelperFromEnvironment(directory).catch(error => print(`Could not write the Git credential helper: ${message(error)}`));
238
+ }
239
+ const outcome = await (dependencies.runHost ?? runBridgeHost)({
240
+ directory,
241
+ relayUrl: relayUrlFromEnvironment(),
242
+ version,
243
+ token: async () => {
244
+ if (!(await stillLinked()))
245
+ throw new Error('This machine was unlinked.');
246
+ return environmentToken(apiBase, identity.environmentId, identity.secret);
247
+ },
248
+ signal: controller.signal,
249
+ log: print,
250
+ ...(process.env.ANDORRA_CLOUD === '1' ? { heartbeat: activity => heartbeat(apiBase, identity.environmentId, identity.secret, activity) } : {}),
251
+ ...(engines ? { engines } : {}),
252
+ ...(launcherAlive ? { launcherAlive } : {}),
253
+ });
254
+ if (unlinkedHere) {
255
+ print('This machine was unlinked. Stopped serving.');
256
+ return 0;
257
+ }
258
+ if (outcome === 'unlinked') {
259
+ await clearBridgeIdentity(directory);
260
+ print(`This machine was removed from your account. Run "${bridgeCommand('link', launched)}" to link it again.`);
261
+ return 1;
262
+ }
263
+ if (outcome === 'restart') {
264
+ print('Restarting with a newer Andorra Code.');
265
+ return HOST_RESTART_EXIT_CODE;
266
+ }
267
+ print('Stopped serving.');
268
+ return 0;
269
+ }
270
+ finally {
271
+ await engines?.close();
272
+ clearInterval(identityCheck);
273
+ controller.abort();
274
+ await stopWatcher;
275
+ stopWatch.release();
276
+ }
277
+ }
278
+ async function folders(args, print, launched) {
279
+ const directory = configDirectory();
280
+ const [action, value] = args;
281
+ if (action === 'list') {
282
+ const list = (await loadConfig(directory)).bridge?.folders ?? [];
283
+ if (!list.length)
284
+ print('No folders shared.');
285
+ for (const folder of list)
286
+ print(`${folder.id} ${folder.path}${folder.label ? ` (${folder.label})` : ''}`);
287
+ return 0;
288
+ }
289
+ if (action === 'add' && value) {
290
+ try {
291
+ const stored = await shareFolder(directory, value);
292
+ print(`Sharing ${stored.path} (id ${stored.id}).`);
293
+ return 0;
294
+ }
295
+ catch (error) {
296
+ print(message(error));
297
+ return 1;
298
+ }
299
+ }
300
+ if (action === 'remove' && value) {
301
+ let removed = false;
302
+ await changeConfigFile(directory, config => {
303
+ const current = config.bridge?.folders ?? [];
304
+ const kept = current.filter(folder => folder.id !== value);
305
+ removed = kept.length !== current.length;
306
+ return removed ? { ...config, bridge: { ...config.bridge, folders: kept } } : config;
307
+ });
308
+ print(removed ? `Stopped sharing folder ${value}.` : `No folder with id ${value}.`);
309
+ return removed ? 0 : 1;
310
+ }
311
+ print(bridgeUsage(launched));
312
+ return 1;
313
+ }
314
+ export async function runBridgeCommand(args, print, dependencies = {}) {
315
+ const [command, ...rest] = args;
316
+ const apiBase = dependencies.apiBase ?? cloudApiBase(process.env) ?? AUTH_DEPLOYMENT.apiBaseUrl;
317
+ switch (command) {
318
+ case 'cloud-boot':
319
+ return runCloudBoot({ apiBase, directory: configDirectory(), stdin: await readBoundedStdin(), print });
320
+ case 'git-credential':
321
+ // Git runs this on a Cloud machine (see ./github.ts). Standard output goes to Git and carries the credential alone.
322
+ return runGitCredential({
323
+ action: rest[0], stdin: rest[0] === 'get' ? await readBoundedStdin() : '', apiBase, directory: configDirectory(), print,
324
+ warn: line => {
325
+ process.stderr.write(`${line}
326
+ `);
327
+ },
328
+ });
329
+ case 'link':
330
+ return link(rest, print, apiBase, dependencies);
331
+ case 'run':
332
+ return run(print, apiBase, dependencies);
333
+ case 'status': {
334
+ const identity = await readBridgeIdentity(configDirectory());
335
+ print(identity ? `Linked as ${identity.name} (${identity.environmentId}).` : 'Not linked.');
336
+ return 0;
337
+ }
338
+ case 'unlink': {
339
+ const directory = configDirectory();
340
+ if (!(await readBridgeIdentity(directory))) {
341
+ print('Not linked.');
342
+ return 0;
343
+ }
344
+ await clearBridgeIdentity(directory);
345
+ print('Unlinked this machine. It can also be removed from your account under Settings → Environments in Andorra Code.');
346
+ return 0;
347
+ }
348
+ case 'folders':
349
+ return folders(rest, print, dependencies.launched ?? launchedFromEnvironment());
350
+ case undefined:
351
+ case '--help':
352
+ case '-h':
353
+ print(bridgeUsage(dependencies.launched ?? launchedFromEnvironment()));
354
+ return 0;
355
+ default:
356
+ print(bridgeUsage(dependencies.launched ?? launchedFromEnvironment()));
357
+ return 1;
358
+ }
359
+ }
@@ -0,0 +1,70 @@
1
+ export type ControlErrorCode = 'code_expired' | 'code_unknown' | 'code_used' | 'boot_expired' | 'boot_used' | 'boot_unknown' | 'environment_limit' | 'invalid_name' | 'not_found' | 'unauthorized' | 'cloud_not_enabled' | 'cloud_plan' | 'cloud_environment' | 'invalid_version' | 'cloud_unavailable' | 'stopping' | 'no_capacity' | 'unlinked' | 'network' | 'server';
2
+ export declare class ControlError extends Error {
3
+ readonly code: ControlErrorCode;
4
+ constructor(code: ControlErrorCode, message: string);
5
+ }
6
+ export interface LinkStart {
7
+ code: string;
8
+ pollToken: string;
9
+ expiresAt: string;
10
+ }
11
+ /**
12
+ * `account` is the claiming account's masked email address, or '' when the service could not read it. No secret comes
13
+ * back: the machine made its own and sent only its hash with link/start, so the answer can be asked for again.
14
+ */
15
+ export type LinkPoll = {
16
+ status: 'pending';
17
+ } | {
18
+ status: 'linked';
19
+ environmentId: string;
20
+ name: string;
21
+ account: string;
22
+ };
23
+ export interface EnvironmentToken {
24
+ token: string;
25
+ expiresAt: string;
26
+ }
27
+ export interface EnvironmentRecord {
28
+ id: string;
29
+ name: string;
30
+ kind: 'machine' | 'cloud';
31
+ createdAt: string;
32
+ }
33
+ export type CloudState = 'none' | 'starting' | 'running' | 'stopping' | 'stopped';
34
+ export interface CloudStatus {
35
+ state: CloudState;
36
+ enabled: boolean;
37
+ /** Why Cloud is not enabled, when the service says: `plan` is an account on the Free plan. */
38
+ reason?: 'plan';
39
+ environmentId?: string;
40
+ label?: string;
41
+ version?: string;
42
+ step?: 'machine' | 'bridge';
43
+ deleteAt?: string;
44
+ error?: 'boot_timeout' | 'no_capacity';
45
+ /** Why a stopping or stopped instance was stopped. */
46
+ stopReason?: CloudStopReason;
47
+ }
48
+ export type CloudStopReason = 'idle' | 'user' | 'boot_timeout';
49
+ /** Starts a link for a machine whose secret hashes to `secretHash` (SHA-256, hex). */
50
+ export declare function linkStart(base: string, secretHash: string): Promise<LinkStart>;
51
+ export declare function linkPoll(base: string, pollToken: string): Promise<LinkPoll>;
52
+ export declare function environmentToken(base: string, id: string, secret: string): Promise<EnvironmentToken>;
53
+ /** Links a Cloud instance: the boot code proves the caller, and only the hash of the instance's own secret is sent. */
54
+ export declare function cloudBoot(base: string, bootCode: string, secretHash: string): Promise<{
55
+ environmentId: string;
56
+ name: string;
57
+ }>;
58
+ export declare function heartbeat(base: string, environmentId: string, secret: string, activity: {
59
+ running: number;
60
+ attached: number;
61
+ }): Promise<void>;
62
+ export declare function listEnvironments(base: string, accessToken: string): Promise<EnvironmentRecord[]>;
63
+ export declare function claimEnvironment(base: string, accessToken: string, code: string, name: string): Promise<EnvironmentRecord>;
64
+ export declare function renameEnvironment(base: string, accessToken: string, id: string, name: string): Promise<EnvironmentRecord>;
65
+ export declare function removeEnvironment(base: string, accessToken: string, id: string): Promise<void>;
66
+ export declare function cloudGet(base: string, accessToken: string): Promise<CloudStatus>;
67
+ export declare function cloudStart(base: string, accessToken: string, version: string): Promise<CloudStatus>;
68
+ export declare function cloudStop(base: string, accessToken: string): Promise<CloudStatus>;
69
+ /** Deletes the account's Cloud; with `environmentId`, only while that is still the account's Cloud (another answers none). */
70
+ export declare function cloudDelete(base: string, accessToken: string, environmentId?: string): Promise<CloudStatus>;
@@ -0,0 +1,238 @@
1
+ export class ControlError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.code = code;
6
+ this.name = 'ControlError';
7
+ }
8
+ }
9
+ const CONTROL_TIMEOUT_MS = 15_000;
10
+ const HEARTBEAT_TIMEOUT_MS = 10_000;
11
+ const MAX_CONTROL_BODY_CHARS = 64 * 1024;
12
+ const STOP_REASONS = ['idle', 'user', 'boot_timeout'];
13
+ async function call(base, method, path, options = {}) {
14
+ let response;
15
+ let text;
16
+ const headers = {};
17
+ if (options.body !== undefined)
18
+ headers['Content-Type'] = 'application/json';
19
+ if (options.accessToken !== undefined)
20
+ headers.Authorization = `Bearer ${options.accessToken}`;
21
+ try {
22
+ response = await globalThis.fetch(`${base.replace(/\/+$/, '')}/environments${path ? `/${path}` : ''}`, {
23
+ method,
24
+ headers,
25
+ ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}),
26
+ signal: AbortSignal.timeout(options.timeoutMs ?? CONTROL_TIMEOUT_MS),
27
+ redirect: 'error',
28
+ });
29
+ text = (await response.text()).slice(0, MAX_CONTROL_BODY_CHARS);
30
+ }
31
+ catch (error) {
32
+ throw new ControlError('network', `The Andorra service could not be reached: ${error instanceof Error ? error.message : String(error)}`);
33
+ }
34
+ let value = {};
35
+ try {
36
+ const parsed = JSON.parse(text);
37
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed))
38
+ value = parsed;
39
+ }
40
+ catch { }
41
+ return { status: response.status, value };
42
+ }
43
+ const post = (base, path, body) => call(base, 'POST', path, { body });
44
+ function serverError(status, value) {
45
+ const detail = typeof value.error === 'string' ? value.error : `HTTP ${status}`;
46
+ return new ControlError('server', `The Andorra service refused the request (${detail}).`);
47
+ }
48
+ function text(value, key) {
49
+ const found = value[key];
50
+ if (typeof found !== 'string' || !found)
51
+ throw new ControlError('server', `The Andorra service answered without ${key}.`);
52
+ return found;
53
+ }
54
+ /** Starts a link for a machine whose secret hashes to `secretHash` (SHA-256, hex). */
55
+ export async function linkStart(base, secretHash) {
56
+ const { status, value } = await post(base, 'link/start', { secretHash });
57
+ if (status !== 200)
58
+ throw serverError(status, value);
59
+ return { code: text(value, 'code'), pollToken: text(value, 'pollToken'), expiresAt: text(value, 'expiresAt') };
60
+ }
61
+ export async function linkPoll(base, pollToken) {
62
+ const { status, value } = await post(base, 'link/poll', { pollToken });
63
+ if (status === 410)
64
+ throw new ControlError('code_expired', 'The link code expired before it was used.');
65
+ if (status !== 200)
66
+ throw serverError(status, value);
67
+ if (value.status === 'pending')
68
+ return { status: 'pending' };
69
+ if (value.status === 'linked') {
70
+ return {
71
+ status: 'linked', environmentId: text(value, 'environmentId'), name: text(value, 'name'),
72
+ // Printed on the machine's terminal, so nothing in it may move the cursor or change the colours.
73
+ account: typeof value.account === 'string' ? value.account.replace(/[\u0000-\u001f\u007f-\u009f]/g, '').slice(0, 320) : '',
74
+ };
75
+ }
76
+ throw new ControlError('server', 'The Andorra service answered the link poll with an unknown status.');
77
+ }
78
+ export async function environmentToken(base, id, secret) {
79
+ const { status, value } = await post(base, 'token', { environmentId: id, secret });
80
+ if (status === 401)
81
+ throw new ControlError('unlinked', 'This machine is no longer linked to an Andorra account.');
82
+ if (status !== 200)
83
+ throw serverError(status, value);
84
+ return { token: text(value, 'token'), expiresAt: text(value, 'expiresAt') };
85
+ }
86
+ const BOOT_REFUSALS = {
87
+ 404: { code: 'boot_unknown', message: 'The start code was not recognised.' },
88
+ 409: { code: 'boot_used', message: 'The start code was already used.' },
89
+ 410: { code: 'boot_expired', message: 'The start code expired.' },
90
+ };
91
+ /** Links a Cloud instance: the boot code proves the caller, and only the hash of the instance's own secret is sent. */
92
+ export async function cloudBoot(base, bootCode, secretHash) {
93
+ const { status, value } = await post(base, 'cloud/boot', { bootCode, secretHash });
94
+ const refusal = BOOT_REFUSALS[status];
95
+ if (refusal !== undefined)
96
+ throw new ControlError(refusal.code, refusal.message);
97
+ if (status !== 200)
98
+ throw serverError(status, value);
99
+ return { environmentId: text(value, 'environmentId'), name: text(value, 'name') };
100
+ }
101
+ export async function heartbeat(base, environmentId, secret, activity) {
102
+ const { status, value } = await call(base, 'POST', 'cloud/heartbeat', { body: { environmentId, secret, running: activity.running, attached: activity.attached }, timeoutMs: HEARTBEAT_TIMEOUT_MS });
103
+ if (status === 401)
104
+ throw new ControlError('unlinked', 'This machine is no longer linked to an Andorra account.');
105
+ if (status !== 200)
106
+ throw serverError(status, value);
107
+ }
108
+ // The calls below act for the signed-in account and carry its access token.
109
+ const REFUSALS = {
110
+ code_unknown: { status: 404, code: 'code_unknown', message: 'That code was not recognised.' },
111
+ code_expired: { status: 410, code: 'code_expired', message: 'That code expired.' },
112
+ code_used: { status: 409, code: 'code_used', message: 'That code was already used.' },
113
+ environment_limit: { status: 409, code: 'environment_limit', message: 'The account has linked the most machines allowed.' },
114
+ invalid_name: { status: 400, code: 'invalid_name', message: 'The machine name was refused.' },
115
+ cloud_environment: { status: 409, code: 'cloud_environment', message: 'Delete Cloud from Settings \u2192 Environments.' },
116
+ };
117
+ function accountError(status, value, notFound = false) {
118
+ if (status === 401)
119
+ return new ControlError('unauthorized', 'The Andorra service did not accept this sign-in.');
120
+ const refusal = typeof value.error === 'string' ? REFUSALS[value.error] : undefined;
121
+ if (refusal !== undefined && refusal.status === status)
122
+ return new ControlError(refusal.code, refusal.message);
123
+ if (notFound && status === 404)
124
+ return new ControlError('not_found', 'That machine is not linked to this account.');
125
+ return serverError(status, value);
126
+ }
127
+ function environmentRecord(value) {
128
+ if (!value || typeof value !== 'object' || Array.isArray(value))
129
+ return undefined;
130
+ const { id, name, kind, createdAt } = value;
131
+ if (typeof id !== 'string' || !id || typeof name !== 'string' || (kind !== 'machine' && kind !== 'cloud') || typeof createdAt !== 'string')
132
+ return undefined;
133
+ return { id, name, kind, createdAt };
134
+ }
135
+ function environmentOf(value) {
136
+ const found = environmentRecord(value.environment);
137
+ if (!found)
138
+ throw new ControlError('server', 'The Andorra service answered without an environment.');
139
+ return found;
140
+ }
141
+ export async function listEnvironments(base, accessToken) {
142
+ const { status, value } = await call(base, 'GET', '', { accessToken });
143
+ if (status !== 200)
144
+ throw accountError(status, value);
145
+ if (!Array.isArray(value.environments))
146
+ throw new ControlError('server', 'The Andorra service answered without environments.');
147
+ return value.environments.flatMap(entry => environmentRecord(entry) ?? []);
148
+ }
149
+ export async function claimEnvironment(base, accessToken, code, name) {
150
+ const { status, value } = await call(base, 'POST', 'link/claim', { accessToken, body: { code, name } });
151
+ if (status !== 200)
152
+ throw accountError(status, value);
153
+ return environmentOf(value);
154
+ }
155
+ export async function renameEnvironment(base, accessToken, id, name) {
156
+ const { status, value } = await call(base, 'PATCH', encodeURIComponent(id), { accessToken, body: { name } });
157
+ if (status !== 200)
158
+ throw accountError(status, value, true);
159
+ return environmentOf(value);
160
+ }
161
+ export async function removeEnvironment(base, accessToken, id) {
162
+ const { status, value } = await call(base, 'DELETE', encodeURIComponent(id), { accessToken });
163
+ if (status !== 200)
164
+ throw accountError(status, value, true);
165
+ }
166
+ const CLOUD_REFUSALS = {
167
+ cloud_not_enabled: { status: 403, code: 'cloud_not_enabled', message: 'Cloud is not available for this account.' },
168
+ stopping: { status: 409, code: 'stopping', message: 'Cloud is still stopping.' },
169
+ no_capacity: { status: 503, code: 'no_capacity', message: 'Cloud has no capacity right now.' },
170
+ invalid_version: { status: 400, code: 'invalid_version', message: 'This version of Andorra Code cannot start Cloud. Update Andorra Code and try again.' },
171
+ };
172
+ const CLOUD_STATES = ['none', 'starting', 'running', 'stopping', 'stopped'];
173
+ const CLOUD_LABEL = /^Andorra-Code-Cloud-[1-9][0-9]{9}$/;
174
+ const CLOUD_ENVIRONMENT_ID = /^env_[A-Za-z0-9_-]{22}$/;
175
+ const CLOUD_VERSION = /^\d{1,4}\.\d{1,4}\.\d{1,4}$/;
176
+ const ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$/;
177
+ /** Keeps only the fields of a Cloud answer that have the expected shape; an unknown state is an error. */
178
+ function cloudStatus(value) {
179
+ const { state, enabled, reason, environmentId, label, version, step, deleteAt, error, stopReason } = value;
180
+ if (typeof state !== 'string' || !CLOUD_STATES.includes(state))
181
+ throw new ControlError('server', 'The Andorra service answered with an unknown Cloud state.');
182
+ const status = { state: state, enabled: enabled === true };
183
+ if (enabled !== true && reason === 'plan')
184
+ status.reason = 'plan';
185
+ if (typeof environmentId === 'string' && CLOUD_ENVIRONMENT_ID.test(environmentId))
186
+ status.environmentId = environmentId;
187
+ if (typeof label === 'string' && CLOUD_LABEL.test(label))
188
+ status.label = label;
189
+ if (typeof version === 'string' && CLOUD_VERSION.test(version))
190
+ status.version = version;
191
+ if (step === 'machine' || step === 'bridge')
192
+ status.step = step;
193
+ if (typeof deleteAt === 'string' && ISO_TIME.test(deleteAt) && !Number.isNaN(Date.parse(deleteAt)))
194
+ status.deleteAt = deleteAt;
195
+ if (error === 'boot_timeout' || error === 'no_capacity')
196
+ status.error = error;
197
+ if ((state === 'stopping' || state === 'stopped') && typeof stopReason === 'string' && STOP_REASONS.includes(stopReason))
198
+ status.stopReason = stopReason;
199
+ return status;
200
+ }
201
+ function cloudError(status, value) {
202
+ const refusal = typeof value.error === 'string' ? CLOUD_REFUSALS[value.error] : undefined;
203
+ if (refusal !== undefined && refusal.status === status) {
204
+ if (refusal.code === 'cloud_not_enabled' && value.reason === 'plan')
205
+ return new ControlError('cloud_plan', 'Cloud is not included in the Free plan.');
206
+ return new ControlError(refusal.code, refusal.message);
207
+ }
208
+ if (status === 401)
209
+ return accountError(status, value);
210
+ return new ControlError('cloud_unavailable', 'Cloud is not available right now. Try again in a moment.');
211
+ }
212
+ export async function cloudGet(base, accessToken) {
213
+ const { status, value } = await call(base, 'GET', 'cloud', { accessToken });
214
+ if (status !== 200)
215
+ throw cloudError(status, value);
216
+ return cloudStatus(value);
217
+ }
218
+ export async function cloudStart(base, accessToken, version) {
219
+ const { status, value } = await call(base, 'POST', 'cloud/start', { accessToken, body: { version } });
220
+ if (status !== 200)
221
+ throw cloudError(status, value);
222
+ return cloudStatus(value);
223
+ }
224
+ export async function cloudStop(base, accessToken) {
225
+ const { status, value } = await call(base, 'POST', 'cloud/stop', { accessToken });
226
+ if (status !== 200)
227
+ throw cloudError(status, value);
228
+ return cloudStatus(value);
229
+ }
230
+ /** Deletes the account's Cloud; with `environmentId`, only while that is still the account's Cloud (another answers none). */
231
+ export async function cloudDelete(base, accessToken, environmentId) {
232
+ const path = environmentId === undefined ? 'cloud' : `cloud?environmentId=${encodeURIComponent(environmentId)}`;
233
+ const { status, value } = await call(base, 'DELETE', path, { accessToken });
234
+ if (status !== 200)
235
+ throw cloudError(status, value);
236
+ // The service answers none, or the environment a start put in place of the deleted one while the delete ran.
237
+ return cloudStatus({ state: 'none', enabled: true, ...value });
238
+ }