opencode-moli 0.0.0-stage → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,795 @@
1
+ /**
2
+ * Optional Moli bootstrap: fetch the official installer, report its SHA256, run
3
+ * it, then confirm the engine actually answers.
4
+ *
5
+ * Why this is a fallback chain and not one download call: on the development
6
+ * machine every single route to the GitHub release host failed at once — direct
7
+ * `Invoke-WebRequest`, `Invoke-WebRequest` with an explicit proxy, `curl.exe`
8
+ * with and without a proxy, and Moli itself. A one-shot download that reports
9
+ * only "failed" leaves the user guessing, so each route is attempted in turn and
10
+ * every outcome is reported.
11
+ *
12
+ * Two further constraints shape the code:
13
+ *
14
+ * - Verification is real but honest. The installer's SHA256 is computed and
15
+ * reported. When the caller supplies `expectedSha256`, a mismatch aborts before
16
+ * execution. Moli publishes no checksum file to compare against, so there is no
17
+ * default expectation to check — inventing one would be worse than reporting
18
+ * the digest that was actually run.
19
+ * - Installation is never a side effect. It runs only when a tool call asks for
20
+ * it, because it downloads and executes third-party code.
21
+ *
22
+ * Every long-running step runs through {@link runAsync}: a child process is
23
+ * spawned without blocking the event loop, the caller awaits its `close` event,
24
+ * and a timeout or abort signal kills it. The DSH host keeps serving requests
25
+ * while an install is in flight — including the official installer's own
26
+ * engine download, which can hang for a long time when the release host is
27
+ * unreachable without a proxy.
28
+ *
29
+ * Proxy handling is centralized at the head of this module (see the "Unified
30
+ * forward-proxy behaviour" section) and the platform decides how the official
31
+ * installer is fed that proxy: POSIX gets proxy environment variables (curl
32
+ * reads them), Windows gets a DefaultWebProxy prelude (Invoke-WebRequest reads
33
+ * that instead).
34
+ *
35
+ * @module dsh-moli/lib/install
36
+ */
37
+ import { spawn, spawnSync } from 'node:child_process';
38
+ import { createHash } from 'node:crypto';
39
+ import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs';
40
+ import { createConnection } from 'node:net';
41
+ import { tmpdir } from 'node:os';
42
+ import { dirname, join } from 'node:path';
43
+ import { findMoli } from './moli.js';
44
+
45
+ /** Official installer for the latest release. */
46
+ export const INSTALLER_URL = process.platform === 'win32'
47
+ ? 'https://github.com/lexmount/moli/releases/latest/download/moli-installer.ps1'
48
+ : 'https://github.com/lexmount/moli/releases/latest/download/moli-installer.sh';
49
+
50
+ /** Moli's own README instructions, for the manual path. */
51
+ export const MANUAL_INSTALL = {
52
+ powershell: 'powershell -ExecutionPolicy ByPass -c "irm https://github.com/lexmount/moli/releases/latest/download/moli-installer.ps1 | iex"',
53
+ shell: 'curl --proto \'=https\' --tlsv1.2 -fsSL https://github.com/lexmount/moli/releases/latest/download/moli-installer.sh | sh',
54
+ releases: 'https://github.com/lexmount/moli/releases/latest',
55
+ verify: 'The installer has no published checksum; after downloading, compare its SHA256 against the digest this tool reports for the run that succeeded.',
56
+ };
57
+
58
+ /** PowerShell prelude that makes older hosts negotiate TLS 1.2. */
59
+ const TLS_PRELUDE = '[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;';
60
+
61
+ /**
62
+ * Unified forward-proxy behaviour for this pipeline.
63
+ *
64
+ * Every proxy decision — parsing/validation, liveness probing, curl argv, the
65
+ * PowerShell DefaultWebProxy prelude, and the child-process environment for the
66
+ * official installer — lives here, so the download routes and (later) the
67
+ * installer execution always agree on one proxy configuration instead of
68
+ * re-deriving it in each spot.
69
+ *
70
+ * The platforms disagree about how a proxy is honoured, and that fact is
71
+ * encoded here:
72
+ *
73
+ * - Linux / macOS — `curl` (used inside moli-installer.sh) reads the standard
74
+ * `HTTPS_PROXY` / `HTTP_PROXY` / `ALL_PROXY` environment variables, so
75
+ * injecting them into the installer's child process is enough.
76
+ * - Windows — `Invoke-WebRequest` (used inside moli-installer.ps1) does NOT
77
+ * read those variables; it honours the WinINET system proxy, i.e. .NET's
78
+ * `DefaultWebProxy`, so the installer must be preceded by a prelude that
79
+ * sets that object.
80
+ */
81
+
82
+ /** Resolve a proxy URL into a structured configuration; undefined when unusable. */
83
+ function resolveProxy(input) {
84
+ if (typeof input !== 'string' || input.length === 0) return undefined;
85
+ let parsed;
86
+ try {
87
+ parsed = new URL(input);
88
+ } catch {
89
+ return undefined;
90
+ }
91
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return undefined;
92
+ const host = parsed.hostname === '' ? undefined : parsed.hostname;
93
+ // A proxy URL without an explicit port uses the scheme default (http 80,
94
+ // https 443); a bare `http://proxy` would otherwise parse as port 0 and be
95
+ // silently discarded while proxyListens probes port 80 for the same string.
96
+ const port = parsed.port === ''
97
+ ? (parsed.protocol === 'https:' ? 443 : 80)
98
+ : Number(parsed.port);
99
+ if (host === undefined || !Number.isInteger(port) || port <= 0 || port > 65535) return undefined;
100
+ return {
101
+ url: input,
102
+ scheme: parsed.protocol.slice(0, -1),
103
+ host,
104
+ port,
105
+ auth: parsed.username !== '' || parsed.password !== ''
106
+ ? { user: decodeURIComponent(parsed.username), pass: decodeURIComponent(parsed.password) }
107
+ : undefined,
108
+ };
109
+ }
110
+
111
+ /** Whether a URL targets loopback and must never be handed to a proxy. */
112
+ function isLoopbackUrl(url) {
113
+ return /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])/iu.test(url);
114
+ }
115
+
116
+ /** curl argv that routes a download through the proxy. */
117
+ function curlProxyArgs(proxy) {
118
+ const config = resolveProxy(proxy);
119
+ return config === undefined ? [] : ['--proxy', config.url];
120
+ }
121
+
122
+ /** curl argv that keeps a direct route off the proxy (loopback only). */
123
+ function curlBypassArgs(url) {
124
+ return isLoopbackUrl(url) ? ['--noproxy', '*'] : [];
125
+ }
126
+
127
+ /**
128
+ * PowerShell prelude that clears the default web proxy for a loopback download.
129
+ *
130
+ * PowerShell 5.1's `Invoke-WebRequest` has no `-NoProxy`, and the system proxy
131
+ * is read from the registry, so the only portable way to bypass it is to clear
132
+ * the default proxy object for the process.
133
+ *
134
+ * @param loopback - whether the target URL is loopback.
135
+ * @returns the PowerShell statement, or an empty string when not needed.
136
+ */
137
+ function powershellProxyBypass(loopback) {
138
+ return loopback
139
+ ? '[System.Net.WebRequest]::DefaultWebProxy = New-Object System.Net.WebProxy;'
140
+ : '';
141
+ }
142
+
143
+ /**
144
+ * PowerShell prelude that makes `Invoke-WebRequest` route through a proxy.
145
+ *
146
+ * `IWR` ignores `HTTPS_PROXY`/`HTTP_PROXY` environment variables; it honours
147
+ * the WinINET system proxy, i.e. .NET's `DefaultWebProxy`. Setting that object
148
+ * before running moli-installer.ps1 is what actually makes the Windows
149
+ * installer's internal engine download honour the configured proxy. When the
150
+ * proxy URL carries credentials, they are assigned explicitly as well: the
151
+ * `WebProxy` constructor does parse userinfo in the address, but an explicit
152
+ * `NetworkCredential` is the unambiguous form.
153
+ *
154
+ * @param proxy - proxy URL.
155
+ * @returns the PowerShell statement, or an empty string when absent.
156
+ */
157
+ export function powershellProxyPrelude(proxy) {
158
+ const config = resolveProxy(proxy);
159
+ if (config === undefined) return '';
160
+ const esc = value => value.replace(/'/gu, "''");
161
+ let prelude = `$__dshMoliProxy = New-Object System.Net.WebProxy('${esc(config.url)}');`;
162
+ if (config.auth !== undefined) {
163
+ prelude += `$__dshMoliProxy.Credentials = New-Object System.Net.NetworkCredential('${esc(config.auth.user)}', '${esc(config.auth.pass)}');`;
164
+ }
165
+ prelude += `[System.Net.WebRequest]::DefaultWebProxy = $__dshMoliProxy;`;
166
+ return prelude;
167
+ }
168
+
169
+ /**
170
+ * Environment variables that make curl (inside moli-installer.sh) route
171
+ * through the proxy.
172
+ *
173
+ * Both cases are set because the tools disagree about which form they read:
174
+ * Windows builds of curl recognise the upper-case names, POSIX tools the
175
+ * lower-case ones.
176
+ *
177
+ * @param proxy - proxy URL.
178
+ * @returns an object to spread into the child's `env`; empty when absent.
179
+ */
180
+ export function proxyEnv(proxy) {
181
+ const config = resolveProxy(proxy); if (config === undefined) return {};
182
+ return {
183
+ HTTPS_PROXY: config.url,
184
+ HTTP_PROXY: config.url,
185
+ https_proxy: config.url,
186
+ http_proxy: config.url,
187
+ ALL_PROXY: config.url,
188
+ all_proxy: config.url,
189
+ };
190
+ }
191
+
192
+ /**
193
+ * Check whether a forward proxy is actually accepting connections.
194
+ *
195
+ * A proxy setting can outlive the program that provided it: an accelerator that
196
+ * writes a system proxy and is later closed leaves `ProxyEnable=1` pointing at a
197
+ * dead port. Every command then sends each request to that port and waits for the
198
+ * connect to time out — including requests to loopback. Probing first keeps the
199
+ * fallback chain fast instead of spending a minute on routes that cannot work.
200
+ *
201
+ * @param proxy - proxy URL, e.g. `http://127.0.0.1:7890`.
202
+ * @param timeoutMs - how long to wait for the connect.
203
+ * @returns whether something is listening.
204
+ */
205
+ export function proxyListens(proxy, timeoutMs = 700) {
206
+ const config = resolveProxy(proxy);
207
+ if (config === undefined) return Promise.resolve(false);
208
+ return new Promise(resolve => {
209
+ const socket = createConnection({ host: config.host, port: config.port });
210
+ const settle = value => {
211
+ socket.removeAllListeners();
212
+ socket.destroy();
213
+ resolve(value);
214
+ };
215
+ socket.setTimeout(timeoutMs);
216
+ socket.once('connect', () => settle(true));
217
+ socket.once('timeout', () => settle(false));
218
+ socket.once('error', () => settle(false));
219
+ });
220
+ }
221
+
222
+ /**
223
+ * SHA256 a file, reading it whole (installer scripts are small).
224
+ *
225
+ * @param path - file to hash.
226
+ * @returns the lowercase hex digest.
227
+ */
228
+ export function sha256File(path) {
229
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
230
+ }
231
+
232
+ /**
233
+ * Normalize stderr text into one readable line.
234
+ *
235
+ * Keep the leading meaningful lines and drop control bytes so the message
236
+ * survives a JSON round trip.
237
+ *
238
+ * @param text - raw stderr text.
239
+ * @returns the condensed message.
240
+ */
241
+ function condenseStderr(text) {
242
+ return String(text)
243
+ .replace(/\u001b\[[0-9;]*m/gu, '')
244
+ .replace(/\r/gu, '')
245
+ .split('\n')
246
+ .map(line => line.trim())
247
+ .filter(line => line.length > 0)
248
+ .slice(0, 6)
249
+ .join(' | ');
250
+ }
251
+
252
+ /**
253
+ * Kill a process and everything it spawned.
254
+ *
255
+ * The process that actually does the work — the installer's internal engine
256
+ * download — is a grandchild: POSIX spawns `sh`, which runs `moli-installer.sh`,
257
+ * which runs `curl`; Windows spawns `powershell.exe -Command "... & script.ps1"`
258
+ * and the `Invoke-WebRequest` inside the script does the download. Killing only
259
+ * the direct child would leak that download: the plugin would report a timeout
260
+ * or abort while the installer kept pulling the ~100 MB engine in the temp dir.
261
+ *
262
+ * - POSIX: spawn with `detached: true` makes the child a process-group leader,
263
+ * so a negative pid signal reaches the whole group.
264
+ * - Windows: there is no process group to signal, so `taskkill /T` walks the
265
+ * tree instead.
266
+ *
267
+ * @param child - the direct child process.
268
+ * @param signal - SIGTERM or SIGKILL (POSIX only; Windows always force-kills).
269
+ */
270
+ function killTree(child, signal) {
271
+ if (child === undefined || child.pid === undefined) return;
272
+ if (process.platform === 'win32') {
273
+ try {
274
+ spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 10000 });
275
+ } catch { /* best effort */ }
276
+ return;
277
+ }
278
+ try { process.kill(-child.pid, signal); } catch { /* best effort */ }
279
+ // Fall back to the direct child in case the group kill did not reach it.
280
+ try { child.kill(signal); } catch { /* best effort */ }
281
+ }
282
+
283
+ /**
284
+ * Run one command asynchronously, never blocking the event loop.
285
+ *
286
+ * stdout and stderr go to real files (the plugin's existing sandbox discipline:
287
+ * a child under DSH's Windows sandbox cannot open inherited pipes, so pipe
288
+ * capture is unreliable), and the caller awaits the `close` event. A timeout
289
+ * sends SIGTERM then SIGKILL to the whole process group; an abort signal kills
290
+ * immediately. The caller's event loop keeps serving while the child runs —
291
+ * including the official installer's internal engine download, which can hang
292
+ * without a proxy.
293
+ *
294
+ * @param options - command, argv, env, timeout, optional stdout file, abort signal.
295
+ * @returns the settled outcome; never throws for a non-zero exit.
296
+ */
297
+ function runAsync(options) {
298
+ const dir = mkdtempSync(join(tmpdir(), 'dsh-moli-run-'));
299
+ const outPath = options.stdoutFile ?? join(dir, 'stdout.bin');
300
+ const errPath = join(dir, 'stderr.txt');
301
+ let outFd;
302
+ let errFd;
303
+ let timer;
304
+ let child;
305
+ let settled = false;
306
+
307
+ const settle = value => {
308
+ if (settled) return;
309
+ settled = true;
310
+ if (timer !== undefined) clearTimeout(timer);
311
+ if (child !== undefined) child.removeAllListeners();
312
+ if (outFd !== undefined) closeSync(outFd);
313
+ if (errFd !== undefined) closeSync(errFd);
314
+ outFd = undefined;
315
+ errFd = undefined;
316
+ const stdout = existsSync(outPath) ? readFileSync(outPath) : Buffer.alloc(0);
317
+ const stderrText = existsSync(errPath) ? readFileSync(errPath, 'utf8') : '';
318
+ rmSync(dir, { recursive: true, force: true });
319
+ resolve({ status: value.status, spawnError: value.spawnError, stdout, stderr: stderrText });
320
+ };
321
+
322
+ // Promise executor cannot be async; the resolve is captured via closure.
323
+ let resolve;
324
+ const promise = new Promise(r => { resolve = r; });
325
+
326
+ try {
327
+ outFd = openSync(outPath, 'w');
328
+ errFd = openSync(errPath, 'w');
329
+ } catch (error) {
330
+ rmSync(dir, { recursive: true, force: true });
331
+ resolve({ status: null, stdout: Buffer.alloc(0), stderr: '', spawnError: `open failed: ${error.message}` });
332
+ return promise;
333
+ }
334
+
335
+ try {
336
+ child = spawn(options.command, options.args, {
337
+ stdio: ['ignore', outFd, errFd],
338
+ env: options.env ?? process.env,
339
+ windowsHide: true,
340
+ // POSIX: the child becomes a process-group leader so killTree can reach
341
+ // the whole tree (sh → moli-installer.sh → curl) with one negative-pid
342
+ // signal. Windows must NOT detach: a detached console child's stdio
343
+ // handles become invalid and powershell.exe exits 0 without running its
344
+ // command, so killTree force-kills there via taskkill /T /F, which needs
345
+ // no detach at all.
346
+ detached: process.platform !== 'win32',
347
+ });
348
+ } catch (error) {
349
+ settle({ status: null, stdout: Buffer.alloc(0), stderr: '', spawnError: `${error.code ?? 'spawn failed'}: ${error.message}` });
350
+ return promise;
351
+ }
352
+
353
+ child.once('error', error => settle({
354
+ status: null,
355
+ stdout: Buffer.alloc(0),
356
+ stderr: '',
357
+ spawnError: `${error.code ?? 'spawn failed'}: ${error.message}`,
358
+ }));
359
+ child.once('close', code => settle({
360
+ status: code ?? 0,
361
+ stdout: Buffer.alloc(0), // populated by settle from the file
362
+ stderr: '',
363
+ }));
364
+
365
+ const timeoutMs = options.timeoutMs;
366
+ if (timeoutMs !== undefined) {
367
+ timer = setTimeout(() => {
368
+ if (settled || child === undefined) return;
369
+ killTree(child, 'SIGTERM');
370
+ // Give the tree a short grace period, then force it.
371
+ const killer = setTimeout(() => {
372
+ if (!settled && child !== undefined) {
373
+ killTree(child, 'SIGKILL');
374
+ }
375
+ }, 2000);
376
+ killer.unref?.();
377
+ }, timeoutMs);
378
+ }
379
+
380
+ if (options.signal !== undefined && options.signal !== null) {
381
+ if (options.signal.aborted === true) {
382
+ killTree(child, 'SIGKILL');
383
+ } else {
384
+ options.signal.addEventListener('abort', () => {
385
+ if (!settled && child !== undefined) {
386
+ killTree(child, 'SIGKILL');
387
+ }
388
+ }, { once: true });
389
+ }
390
+ }
391
+
392
+ return promise;
393
+ }
394
+
395
+ /**
396
+ * Run one command synchronously, blocking until it exits.
397
+ *
398
+ * This is the Windows path's runner: Windows is deliberately not
399
+ * asynchronized (its installer has bounded `Invoke-WebRequest` timeouts and
400
+ * the platform was not part of the Linux hang investigation), so the whole
401
+ * install stays synchronous there. stdout and stderr still go to real files —
402
+ * under DSH's Windows sandbox a child cannot open inherited pipes — and the
403
+ * caller gets the file contents read back.
404
+ *
405
+ * @param options - command, argv, env, timeout, optional stdout file.
406
+ * @returns the settled outcome; never throws for a non-zero exit.
407
+ */
408
+ function runSync(options) {
409
+ const dir = mkdtempSync(join(tmpdir(), 'dsh-moli-run-'));
410
+ const outPath = options.stdoutFile ?? join(dir, 'stdout.bin');
411
+ const errPath = join(dir, 'stderr.txt');
412
+ let outFd;
413
+ let errFd;
414
+ try {
415
+ outFd = openSync(outPath, 'w');
416
+ errFd = openSync(errPath, 'w');
417
+ const result = spawnSync(options.command, options.args, {
418
+ stdio: ['ignore', outFd, errFd],
419
+ env: options.env ?? process.env,
420
+ timeout: options.timeoutMs,
421
+ windowsHide: true,
422
+ });
423
+ const stdout = existsSync(outPath) ? readFileSync(outPath) : Buffer.alloc(0);
424
+ const stderrText = existsSync(errPath) ? readFileSync(errPath, 'utf8') : '';
425
+ const failed = result.error !== undefined && result.error !== null;
426
+ return {
427
+ status: failed ? null : (result.status ?? 0),
428
+ stdout,
429
+ stderr: condenseStderr(stderrText),
430
+ spawnError: failed ? `${result.error.code ?? 'spawn failed'}: ${result.error.message}` : undefined,
431
+ };
432
+ } finally {
433
+ if (outFd !== undefined) closeSync(outFd);
434
+ if (errFd !== undefined) closeSync(errFd);
435
+ rmSync(dir, { recursive: true, force: true });
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Run one download attempt, treating a zero-byte file as failure.
441
+ *
442
+ * @param options - argv, environment, and the target path to check afterwards.
443
+ * @returns the attempt outcome.
444
+ */
445
+ async function attempt(options) {
446
+ const outcome = await runAsync({
447
+ command: options.command,
448
+ args: options.args,
449
+ env: options.env,
450
+ timeoutMs: options.timeoutMs,
451
+ });
452
+ const bytes = existsSync(options.target) ? statSync(options.target).size : 0;
453
+ const failed = outcome.spawnError !== undefined;
454
+ const exit = failed ? null : outcome.status;
455
+ const ok = !failed && exit === 0 && bytes > 0;
456
+ return {
457
+ method: options.method,
458
+ ok,
459
+ exit,
460
+ bytes,
461
+ error: ok
462
+ ? undefined
463
+ : failed
464
+ ? outcome.spawnError
465
+ : exit === 0
466
+ ? 'the download produced an empty file'
467
+ : `exit ${String(exit)}${outcome.stderr === '' ? '' : `: ${outcome.stderr}`}`,
468
+ };
469
+ }
470
+
471
+ /**
472
+ * Run a stdout-producing download route (the moli self-bootstrap) to the target.
473
+ *
474
+ * @param route - the route descriptor with `command` and `args`.
475
+ * @param target - the file the child's stdout is written to.
476
+ * @param timeoutMs - download deadline.
477
+ * @returns the attempt outcome.
478
+ */
479
+ async function attemptStdout(route, target, timeoutMs) {
480
+ const outcome = await runAsync({
481
+ command: route.command,
482
+ args: route.args,
483
+ env: { ...process.env, MOLI_DL_TARGET: target },
484
+ timeoutMs,
485
+ stdoutFile: target,
486
+ });
487
+ const bytes = existsSync(target) ? statSync(target).size : 0;
488
+ const failed = outcome.spawnError !== undefined;
489
+ const ok = !failed && outcome.status === 0 && bytes > 0;
490
+ return {
491
+ method: route.method,
492
+ ok,
493
+ exit: failed ? null : outcome.status,
494
+ bytes,
495
+ error: ok
496
+ ? undefined
497
+ : failed
498
+ ? outcome.spawnError
499
+ : bytes === 0
500
+ ? 'empty output'
501
+ : `exit ${String(outcome.status)}`,
502
+ };
503
+ }
504
+
505
+ /**
506
+ * Try every available route to the installer, in order of least surprise.
507
+ *
508
+ * @param options - installer URL, target path, proxy, timeout, and injection points.
509
+ * @returns the successful digest plus the full per-method log.
510
+ */
511
+ export async function downloadInstaller(options) {
512
+ const target = options.target;
513
+ const url = options.installerUrl ?? INSTALLER_URL;
514
+ const timeoutMs = options.timeoutMs ?? 60000;
515
+ const powershell = options.powershell ?? (process.platform === 'win32' ? 'powershell.exe' : 'powershell');
516
+ const onWindows = process.platform === 'win32';
517
+
518
+ // Head: one proxy decision, then every route below agrees on it.
519
+ const proxyConfig = resolveProxy(options.proxy);
520
+ const proxyAlive = proxyConfig === undefined ? false : await proxyListens(proxyConfig.url);
521
+ const proxy = proxyConfig === undefined ? undefined : proxyConfig.url;
522
+
523
+ // Never hand a loopback URL to a proxy — with a stale system proxy setting the
524
+ // request would go to a dead port and wait out the connect timeout. Windows
525
+ // PowerShell 5.1 has no `-NoProxy` on Invoke-WebRequest, and the system proxy is
526
+ // read from the registry, so the only portable way to bypass it is to clear the
527
+ // default proxy object for the process.
528
+ const bypass = powershellProxyBypass(isLoopbackUrl(url));
529
+
530
+ const iwr = extra => [
531
+ '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command',
532
+ `${TLS_PRELUDE}${bypass} Invoke-WebRequest -UseBasicParsing ${extra} -Uri '${url}' -OutFile $env:MOLI_DL_TARGET -TimeoutSec ${String(Math.ceil(timeoutMs / 1000))}`,
533
+ ];
534
+
535
+ // Route order is platform-aware, in order of least surprise.
536
+ const routes = [];
537
+ if (onWindows) {
538
+ routes.push({
539
+ method: 'Invoke-WebRequest (direct)',
540
+ command: powershell,
541
+ args: iwr(''),
542
+ });
543
+ // Only attempt proxy routes when something is actually listening there.
544
+ if (proxy !== undefined && proxyAlive) {
545
+ routes.push({
546
+ method: `Invoke-WebRequest (proxy ${proxy})`,
547
+ command: powershell,
548
+ args: iwr(`-Proxy '${proxy}'`),
549
+ });
550
+ }
551
+ }
552
+ routes.push({
553
+ method: 'curl (direct)',
554
+ command: onWindows ? 'curl.exe' : 'curl',
555
+ args: ['-sSL', ...curlBypassArgs(url), '--max-time', String(Math.ceil(timeoutMs / 1000)), '-o', target, url],
556
+ });
557
+ if (proxy !== undefined && proxyAlive) {
558
+ routes.push({
559
+ method: `curl (proxy ${proxy})`,
560
+ command: onWindows ? 'curl.exe' : 'curl',
561
+ args: ['-sSL', ...curlBypassArgs(url), '--max-time', String(Math.ceil(timeoutMs / 1000)), ...curlProxyArgs(proxy), '-o', target, url],
562
+ });
563
+ }
564
+ // Moli can bootstrap itself: when it is present but broken, or when reinstalling,
565
+ // its own TLS handling is another independent route to the release host.
566
+ const exe = options.locate === undefined ? undefined : options.locate(options.exePath);
567
+ if (exe !== undefined) {
568
+ routes.push({
569
+ method: 'moli fetch (self-bootstrap)',
570
+ command: exe,
571
+ args: ['fetch', url, '--insecure-disable-tls-host-verification', ...(proxy === undefined || !proxyAlive ? [] : ['--http-proxy', proxy])],
572
+ stdoutToFile: true,
573
+ });
574
+ }
575
+
576
+ const log = [];
577
+ for (const route of routes) {
578
+ if (existsSync(target)) rmSync(target, { force: true });
579
+ // Every route runs asynchronously on every platform: the child process is
580
+ // spawned without blocking the DSH host's event loop, and the per-route
581
+ // timeout keeps a hung download from stalling the host. Windows and POSIX
582
+ // behave identically here.
583
+ const outcome = route.stdoutToFile === undefined
584
+ ? await attempt({
585
+ method: route.method,
586
+ command: route.command,
587
+ args: route.args,
588
+ target,
589
+ timeoutMs,
590
+ env: { ...process.env, MOLI_DL_TARGET: target },
591
+ })
592
+ : await attemptStdout(route, target, timeoutMs);
593
+ log.push({ method: outcome.method, ok: outcome.ok, bytes: outcome.bytes, error: outcome.error });
594
+ if (outcome.ok) {
595
+ return { ok: true, path: target, bytes: outcome.bytes, sha256: sha256File(target), method: outcome.method, attempts: log };
596
+ }
597
+ }
598
+ return { ok: false, attempts: log, error: `every download route failed (${String(log.length)} tried)` };
599
+ }
600
+
601
+ /**
602
+ * Read the engine's version banner asynchronously.
603
+ *
604
+ * @param exe - absolute path to the moli binary.
605
+ * @param options - timeout and abort signal.
606
+ * @returns the version string, or undefined when the call failed.
607
+ */
608
+ async function moliVersionAsync(exe, options = {}) {
609
+ const outcome = await runAsync({
610
+ command: exe,
611
+ args: ['--version'],
612
+ timeoutMs: options.timeoutMs ?? 15000,
613
+ signal: options.signal,
614
+ });
615
+ if (outcome.status !== 0 || outcome.spawnError !== undefined) return undefined;
616
+ const text = outcome.stdout.toString('utf8').trim();
617
+ return text === '' ? undefined : text;
618
+ }
619
+
620
+ /**
621
+ * Synchronous twin of {@link moliVersionAsync}, used on Windows.
622
+ *
623
+ * @param exe - absolute path to the moli binary.
624
+ * @param timeoutMs - version-call deadline.
625
+ * @returns the version string, or undefined when the call failed.
626
+ */
627
+ function moliVersionSync(exe, timeoutMs = 15000) {
628
+ const outcome = runSync({ command: exe, args: ['--version'], timeoutMs });
629
+ if (outcome.status !== 0 || outcome.spawnError !== undefined) return undefined;
630
+ const text = outcome.stdout.toString('utf8').trim();
631
+ return text === '' ? undefined : text;
632
+ }
633
+
634
+ /**
635
+ * Install Moli and confirm it answers.
636
+ *
637
+ * @param options - expected checksum, timeouts, proxy, abort signal, and injection points for tests.
638
+ * @returns the settled outcome value.
639
+ */
640
+ export async function installMoli(options = {}) {
641
+ const timeoutMs = options.timeoutMs ?? 180000;
642
+ const workDir = mkdtempSync(join(tmpdir(), 'dsh-moli-install-'));
643
+ const target = join(workDir, process.platform === 'win32' ? 'moli-installer.ps1' : 'moli-installer.sh');
644
+ try {
645
+ // Head: one proxy decision, shared by the download below and the run after it.
646
+ const proxyConfig = resolveProxy(options.proxy);
647
+ const proxyAlive = proxyConfig === undefined ? false : await proxyListens(proxyConfig.url);
648
+ const proxy = proxyConfig === undefined ? undefined : proxyConfig.url;
649
+
650
+ const download = await downloadInstaller({
651
+ target,
652
+ installerUrl: options.installerUrl,
653
+ proxy,
654
+ timeoutMs: options.downloadTimeoutMs ?? 60000,
655
+ locate: options.locate ?? findMoli,
656
+ exePath: options.exePath,
657
+ });
658
+
659
+ if (download.ok !== true) {
660
+ return {
661
+ ok: false,
662
+ error: download.error,
663
+ attempts: download.attempts,
664
+ note: 'No route to the release host worked. The manual install command below is the fallback.',
665
+ manualInstall: MANUAL_INSTALL,
666
+ };
667
+ }
668
+
669
+ // Verify before executing anything, whenever the caller states an expectation.
670
+ if (typeof options.expectedSha256 === 'string' && options.expectedSha256.length > 0) {
671
+ const expected = options.expectedSha256.trim().toLowerCase();
672
+ if (expected !== download.sha256) {
673
+ return {
674
+ ok: false,
675
+ error: `installer checksum mismatch: expected ${expected}, got ${download.sha256}`,
676
+ installerSha256: download.sha256,
677
+ expectedSha256: expected,
678
+ method: download.method,
679
+ note: 'Refusing to execute the installer.',
680
+ manualInstall: MANUAL_INSTALL,
681
+ };
682
+ }
683
+ }
684
+
685
+ // Run the official installer, routing its internal engine download through
686
+ // the proxy the way each platform honours it:
687
+ // - POSIX (Linux/macOS): moli-installer.sh uses curl, which reads the proxy
688
+ // environment variables, so injecting them is enough.
689
+ // - Windows: moli-installer.ps1 uses Invoke-WebRequest, which ignores env
690
+ // variables and honours .NET's DefaultWebProxy, so the script must be
691
+ // preceded by a prelude that sets that object.
692
+ const env = { ...process.env, ...(proxyAlive ? proxyEnv(proxy) : {}) };
693
+ let args;
694
+ if (process.platform === 'win32') {
695
+ const prelude = `${TLS_PRELUDE}${proxyAlive ? powershellProxyPrelude(proxy) : ''}`;
696
+ const script = `& '${target.replace(/'/gu, "''")}'`;
697
+ args = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', `${prelude} ${script}`];
698
+ } else {
699
+ args = [target];
700
+ }
701
+ let run;
702
+ if (process.platform === 'win32') {
703
+ // Windows runs asynchronously too: spawn the installer without blocking
704
+ // the DSH host's event loop. The outer timeout sends SIGTERM then
705
+ // SIGKILL, and an abort signal kills it immediately, so the host keeps
706
+ // serving requests while PowerShell's Invoke-WebRequest does its work.
707
+ run = await runAsync({
708
+ command: options.powershell ?? 'powershell.exe',
709
+ args,
710
+ env,
711
+ timeoutMs,
712
+ signal: options.signal,
713
+ });
714
+ } else {
715
+ // Linux/macOS keeps its existing asynchronous behaviour.
716
+ run = await runAsync({
717
+ command: 'sh',
718
+ args,
719
+ env,
720
+ timeoutMs,
721
+ signal: options.signal,
722
+ });
723
+ }
724
+ const runFailed = run.spawnError !== undefined;
725
+ const runStatus = runFailed ? null : run.status;
726
+
727
+ const locate = options.locate ?? findMoli;
728
+ const exe = locate(options.exePath);
729
+ const version = exe === undefined
730
+ ? undefined
731
+ : process.platform === 'win32'
732
+ ? moliVersionSync(exe)
733
+ : await moliVersionAsync(exe, { signal: options.signal });
734
+
735
+ if (version === undefined) {
736
+ return {
737
+ ok: false,
738
+ error: runFailed
739
+ ? `running the installer failed: ${run.spawnError}`
740
+ : `the installer ${runStatus === 0 ? 'reported success' : `exited ${String(runStatus)}`}, but no working moli binary was found afterwards`,
741
+ installerSha256: download.sha256,
742
+ installerBytes: download.bytes,
743
+ method: download.method,
744
+ searchedPaths: options.candidates ?? undefined,
745
+ manualInstall: MANUAL_INSTALL,
746
+ };
747
+ }
748
+
749
+ return {
750
+ ok: true,
751
+ exe,
752
+ version,
753
+ installerSha256: download.sha256,
754
+ installerBytes: download.bytes,
755
+ method: download.method,
756
+ note: 'Installed from the official release installer. The SHA256 above is what was actually run; Moli publishes no checksum file to compare it against.',
757
+ };
758
+ } finally {
759
+ rmSync(workDir, { recursive: true, force: true });
760
+ }
761
+ }
762
+
763
+ /**
764
+ * Remove an installed Moli engine. Windows deletes the installer-owned
765
+ * `%LOCALAPPDATA%\Moli` tree; POSIX removes the located binary and prunes the
766
+ * install directories it sits in when they end up empty.
767
+ *
768
+ * @param override - explicit path from configuration, when set.
769
+ * @returns the removed path, or undefined when nothing was installed.
770
+ */
771
+ export function uninstallMoli(override) {
772
+ const exe = findMoli(override);
773
+ if (exe === undefined) return undefined;
774
+ if (process.platform === 'win32') {
775
+ const root = process.env.LOCALAPPDATA ? join(process.env.LOCALAPPDATA, 'Moli') : undefined;
776
+ if (root !== undefined && existsSync(root)) {
777
+ rmSync(root, { recursive: true, force: true });
778
+ return root;
779
+ }
780
+ // No installer-owned tree: nothing to remove. Returning here keeps the
781
+ // uninstall from falling through to the POSIX branch and deleting whatever
782
+ // findMoli located — which could be a user-provided path or a test fixture.
783
+ return undefined;
784
+ }
785
+ rmSync(exe, { force: true });
786
+ const dir = dirname(exe);
787
+ for (const parent of [dir, dirname(dir)]) {
788
+ try {
789
+ if (existsSync(parent) && readdirSync(parent).length === 0) rmSync(parent, { force: true });
790
+ } catch {
791
+ // A non-empty or protected parent is fine; the binary is already gone.
792
+ }
793
+ }
794
+ return exe;
795
+ }