@galaxy-stack/blackhole-cli 3.0.7 → 3.0.9

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.
@@ -1,28 +1,137 @@
1
+ /**
2
+ * author Bùi Trọng Hiếu
3
+ * email kevinbui210191@gmail.com
4
+ * create date 15/10/2026
5
+ * modify date 12/11/2026
6
+ * desc Bậc npm (gói @galaxy-blackhole/blackhole-harness) đứng trước git clone/ZIP; dò runtime ở cả apps/host/node_modules lẫn node_modules bị npm hoist; status in nguồn npm
7
+ */
1
8
  /**
2
9
  * `blackhole harness install | status | remove`: put the Galaxy Blackhole harness on a machine
3
10
  * that never had a checkout of it.
4
11
  *
5
12
  * The CLI is published without the harness, so a fresh `npm i -g` has no launcher to boot. This
6
- * module fetches one — `git clone --depth 1` when git is installed, the GitHub archive otherwise —
7
- * unpacks it under `~/.galaxy/harness/blackhole-tauri` (or wherever `--dir` says), installs the
8
- * runtime dependencies the launcher needs, and records where it went so the resolver finds it
9
- * again. Every step is printed before it runs: a multi-minute download must never look like a hang.
13
+ * module fetches one — the published npm package first, then `git clone --depth 1` when git is
14
+ * installed, the GitHub archive otherwise — unpacks it under
15
+ * `~/.galaxy/harness/blackhole-harness` (or wherever `--dir` says), makes sure the launcher's
16
+ * runtime is there, and records where it went so the resolver finds it again. Every step is printed
17
+ * before it runs: a multi-minute download must never look like a hang.
18
+ *
19
+ * 12/11/2026 — the npm rung. `npm i --omit=dev --prefix <dir> @galaxy-blackhole/blackhole-harness@latest`
20
+ * is ONE install (measured: 684 packages with the kernel's own dependencies) instead of a 39 MB
21
+ * clone plus a second npm run in `apps/host`, and npm hoists the kernel to `<dir>/node_modules`
22
+ * instead of `apps/host/node_modules` — so "is it installed?" now asks for both paths.
10
23
  */
11
24
  import { spawn } from "node:child_process";
12
- import { createWriteStream, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
25
+ import { createWriteStream, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, rmSync, writeFileSync } from "node:fs";
13
26
  import { homedir } from "node:os";
14
- import { basename, dirname, join, resolve } from "node:path";
27
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
15
28
  import { Readable } from "node:stream";
16
29
  import { pipeline } from "node:stream/promises";
17
30
  import { extractZip } from "./zip.js";
18
31
  import { defaultHarnessDir, defaultHarnessParent, findBun, findTauriLocation, harnessHome, installRecordPaths, isHarnessCheckout, systemLocateEnvironment, } from "./locate.js";
19
32
  import { resolveNodeRuntime, systemNodeLookup } from "./node-runtime.js";
33
+ import { npmArgv, npmMissingMessage, resolveNpm, runNpm, whichOnPath } from "../npm-cli.js";
20
34
  /** The repository the harness is published from. */
21
35
  export const HARNESS_REPO = "https://github.com/galaxy-blackhole/blackhole-harness";
22
36
  /** The branch a shallow clone and the archive URL both read. */
23
37
  export const HARNESS_BRANCH = "main";
24
38
  /** The checkout directory name every install ends with. */
25
39
  export const HARNESS_DIR_NAME = "blackhole-harness";
40
+ /** The npm package that carries the harness (rename with `GBH_HARNESS_PACKAGE`). */
41
+ export const HARNESS_PACKAGE = "@galaxy-blackhole/blackhole-harness";
42
+ /** The dist-tag the npm rung asks for (pin a version with `GBH_HARNESS_SPEC`). */
43
+ export const HARNESS_PACKAGE_SPEC = "latest";
44
+ /**
45
+ * Every place the host runtime can be, relative to the harness root, in preference order.
46
+ *
47
+ * Two layouts, one fact. A repository checkout pins the kernel inside `apps/host`
48
+ * (`bun install` / `npm ci` there); the published npm package carries the kernel as one of its own
49
+ * dependencies, and npm hoists it to the `node_modules` of the directory it installed into
50
+ * (measured 12/11/2026: `npm i --prefix /tmp/x …` → `/tmp/x/node_modules/@deepseek-ai/dsh/lib/bin.js`,
51
+ * no `apps/host/node_modules` at all). The launcher itself finds either by walking parent
52
+ * `node_modules`; this CLI has to look in both places before it calls a tree bootable.
53
+ */
54
+ export const DSH_RUNTIME_ENTRIES = Object.freeze([
55
+ "apps/host/node_modules/@deepseek-ai/dsh/lib/bin.js",
56
+ "node_modules/@deepseek-ai/dsh/lib/bin.js",
57
+ ]);
58
+ /**
59
+ * The host runtime the launcher boots, relative to the checkout root.
60
+ *
61
+ * This one file decides whether "downloaded" means "installable": the launcher refuses to boot
62
+ * without it (`harness runtime not found at …`), and on Windows the old installer called npm
63
+ * directly, so it printed "xong" over a tree that could never start.
64
+ */
65
+ export const DSH_RUNTIME_ENTRY = DSH_RUNTIME_ENTRIES[0];
66
+ /**
67
+ * Absolute paths of the host runtime inside one tree, in preference order.
68
+ * @param root - harness root.
69
+ * @returns the checkout path first, the npm-hoisted path second.
70
+ */
71
+ export function dshRuntimeCandidates(root) {
72
+ return DSH_RUNTIME_ENTRIES.map(entry => join(root, ...entry.split("/")));
73
+ }
74
+ /**
75
+ * Absolute path of the checkout-shaped host runtime (the one older messages name).
76
+ * @param root - harness root.
77
+ * @returns `<root>/apps/host/node_modules/@deepseek-ai/dsh/lib/bin.js`.
78
+ */
79
+ export function dshRuntimePath(root) {
80
+ return dshRuntimeCandidates(root)[0];
81
+ }
82
+ /**
83
+ * The host runtime that is actually on disk.
84
+ * @param root - harness root.
85
+ * @param exists - filesystem probe; `existsSync` in production.
86
+ * @returns the absolute path that answered, or undefined when neither layout has it.
87
+ */
88
+ export function findDshRuntime(root, exists = existsSync) {
89
+ return dshRuntimeCandidates(root).find(path => exists(path));
90
+ }
91
+ /**
92
+ * Whether a tree can actually boot the harness — in either layout.
93
+ * @param root - harness root.
94
+ * @param exists - filesystem probe; `existsSync` in production.
95
+ * @returns true when the host runtime entry is there.
96
+ */
97
+ export function hasDshRuntime(root, exists = existsSync) {
98
+ return findDshRuntime(root, exists) !== undefined;
99
+ }
100
+ /**
101
+ * Absolute path to print for a tree's runtime: the one that answered, else the checkout-shaped one.
102
+ * @param root - harness root.
103
+ * @param exists - filesystem probe; `existsSync` in production.
104
+ * @returns the path `web --dry-run` and `harness status` show.
105
+ */
106
+ export function dshRuntimeResolved(root, exists = existsSync) {
107
+ return findDshRuntime(root, exists) ?? dshRuntimePath(root);
108
+ }
109
+ /**
110
+ * The runtime entry relative to the harness root, with forward slashes: what `harness status`
111
+ * prints beside `runtime: có` (`apps/host/node_modules/…` or `node_modules/…`).
112
+ * @param root - harness root.
113
+ * @param exists - filesystem probe; `existsSync` in production.
114
+ * @returns the relative entry that answered, or the checkout-shaped one when nothing did.
115
+ */
116
+ export function dshRuntimeEntry(root, exists = existsSync) {
117
+ const found = findDshRuntime(root, exists);
118
+ return found === undefined ? DSH_RUNTIME_ENTRY : relative(root, found).split(sep).join("/");
119
+ }
120
+ /**
121
+ * What to print when the checkout is there but its runtime is not: the missing file, the one
122
+ * command that reinstalls it, and the reason it is usually missing (no npm on the machine).
123
+ * @param root - checkout root.
124
+ * @returns several lines, safe to print from `install`, `web` and `chat`.
125
+ */
126
+ export function harnessRuntimeMissingMessage(root) {
127
+ return [
128
+ "harness đã tải nhưng thiếu runtime: " + dshRuntimePath(root),
129
+ " hoặc: " + join(root, "node_modules", "@deepseek-ai", "dsh", "lib", "bin.js") + " (bản cài bằng npm)",
130
+ ' sửa: chạy "blackhole harness install --force" (cài lại: npm i @galaxy-blackhole/blackhole-harness, hoặc npm ci trong apps/host)',
131
+ " nếu vẫn thiếu: máy chưa có npm — cài Node.js kèm npm (https://nodejs.org) rồi chạy lại;",
132
+ " hoặc cài bun (https://bun.sh) và chạy: bun install --cwd " + join(root, "apps", "host"),
133
+ ].join("\n");
134
+ }
26
135
  /**
27
136
  * The archive URL for a repository: GitHub serves the branch head as a zip, which needs no git.
28
137
  * @param repo - repository URL (an `.git` suffix is dropped).
@@ -45,14 +154,58 @@ function downloadFailure(url, error) {
45
154
  return new Error("tải harness thất bại" + notFound + ": " + reason +
46
155
  "\n nguồn khác: blackhole harness install --from <url .zip | repo git>, hoặc đặt GBH_TAURI_ARCHIVE / GBH_TAURI_REPO.");
47
156
  }
48
- /** Spawn a child with inherited stdio, so a package manager's own progress is visible. */
49
- function runInherit(command, args, cwd) {
50
- return new Promise(resolvePromise => {
51
- const child = spawn(command, [...args], { cwd, stdio: "inherit" });
52
- child.once("error", () => resolvePromise(1));
53
- child.once("close", code => resolvePromise(code ?? 1));
157
+ /** How many of a failed step's own lines are printed: npm's diagnosis is always in the tail. */
158
+ const TAIL_LINES = 15;
159
+ /**
160
+ * Run one dependency step with piped stdio.
161
+ *
162
+ * The lines are streamed as they arrive (a multi-minute install must not look like a hang) and
163
+ * kept, because a failure that swallows npm's output is a failure nobody can act on.
164
+ * @param write - progress sink for the child's own lines.
165
+ * @returns the runner `installHarness` uses by default.
166
+ */
167
+ function runCaptured(write) {
168
+ return (command, args, cwd) => new Promise(resolvePromise => {
169
+ const child = spawn(command, [...args], { cwd, stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, NO_COLOR: "1" } });
170
+ let output = "";
171
+ let pending = "";
172
+ const absorb = (chunk) => {
173
+ const text = chunk.toString("utf8");
174
+ output = (output + text).slice(-65_536);
175
+ pending += text;
176
+ const lines = pending.split(/\r?\n/u);
177
+ pending = lines.pop() ?? "";
178
+ for (const line of lines)
179
+ if (line.trim().length > 0)
180
+ write(" " + line.trimEnd());
181
+ };
182
+ child.stdout?.on("data", absorb);
183
+ child.stderr?.on("data", absorb);
184
+ child.once("error", (error) => resolvePromise({ code: null, output: (output + error.message).trim() }));
185
+ child.once("close", code => {
186
+ if (pending.trim().length > 0)
187
+ write(" " + pending.trimEnd());
188
+ resolvePromise({ code, output: (output + pending).trim() });
189
+ });
54
190
  });
55
191
  }
192
+ /**
193
+ * Print the last {@link TAIL_LINES} lines a step wrote, so its own diagnosis reaches the user.
194
+ * @param write - progress sink.
195
+ * @param output - what the step printed.
196
+ * @param label - the step, as it was announced.
197
+ * @param code - its exit code.
198
+ */
199
+ function writeTail(write, output, label, code) {
200
+ const lines = output.split(/\r?\n/u).filter(line => line.trim().length > 0);
201
+ if (lines.length === 0) {
202
+ write("output: (không có output) — " + label + ", mã " + String(code));
203
+ return;
204
+ }
205
+ write("output: " + String(TAIL_LINES) + " dòng cuối của " + label + " (mã " + String(code) + "):");
206
+ for (const line of lines.slice(-TAIL_LINES))
207
+ write(" | " + line.trimEnd());
208
+ }
56
209
  /** Stream one HTTP(S) URL into a file, following redirects (`codeload.github.com` does that). */
57
210
  async function downloadToFile(url, dest) {
58
211
  const response = await fetch(url, { redirect: "follow" });
@@ -98,38 +251,108 @@ export function readHarnessVersion(root) {
98
251
  }
99
252
  }
100
253
  /**
101
- * Whether `apps/host/node_modules` is populated.
102
- * @param root - checkout root.
103
- * @returns presence and the number of top-level entries.
254
+ * The npm package `harness install` fetches.
255
+ * @param environment - environment facts; `GBH_HARNESS_PACKAGE` renames the package.
256
+ * @returns the package name, defaulting to {@link HARNESS_PACKAGE}.
104
257
  */
105
- export function hostModulesState(root) {
106
- const dir = join(root, "apps", "host", "node_modules");
258
+ export function harnessPackageName(environment) {
259
+ const overridden = (environment.env.GBH_HARNESS_PACKAGE ?? "").trim();
260
+ return overridden.length > 0 ? overridden : HARNESS_PACKAGE;
261
+ }
262
+ /**
263
+ * The version or dist-tag the npm rung asks for.
264
+ * @param environment - environment facts; `GBH_HARNESS_SPEC` pins a version.
265
+ * @returns the spec, defaulting to `latest`.
266
+ */
267
+ export function harnessPackageSpec(environment) {
268
+ const pinned = (environment.env.GBH_HARNESS_SPEC ?? "").trim();
269
+ return pinned.length > 0 ? pinned : HARNESS_PACKAGE_SPEC;
270
+ }
271
+ /**
272
+ * The one argument npm receives for the harness.
273
+ * @param environment - environment facts.
274
+ * @returns `@galaxy-blackhole/blackhole-harness@latest`.
275
+ */
276
+ export function harnessPackageRequest(environment) {
277
+ return harnessPackageName(environment) + "@" + harnessPackageSpec(environment);
278
+ }
279
+ /**
280
+ * The argv of the npm fetch, exactly as it is logged.
281
+ * @param prefix - directory npm installs into (`--prefix`).
282
+ * @param request - `<name>@<version|dist-tag>`.
283
+ * @returns `npm i --omit=dev --prefix <dir> <request> --no-audit --no-fund`.
284
+ */
285
+ export function npmFetchArgs(prefix, request) {
286
+ return ["i", "--omit=dev", "--prefix", prefix, request, "--no-audit", "--no-fund"];
287
+ }
288
+ /**
289
+ * The npm package a tree was installed from, read from the tree's own `package.json`.
290
+ *
291
+ * The published build names itself `@galaxy-blackhole/blackhole-harness`; the repository checkout
292
+ * still calls itself `@galaxy-blackhole/gbh-tauri`, so the name is what tells the two apart.
293
+ * @param root - harness root.
294
+ * @param environment - environment facts; the override counts as the npm name.
295
+ * @returns the package name and version, or undefined when this tree is not the npm build.
296
+ */
297
+ export function readHarnessPackage(root, environment) {
107
298
  try {
108
- const entries = readdirSync(dir).filter(name => !name.startsWith("."));
109
- return { present: entries.length > 0, packages: entries.length };
299
+ const parsed = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
300
+ const name = parsed.name;
301
+ const version = parsed.version;
302
+ if (typeof name !== "string" || name.trim() !== harnessPackageName(environment))
303
+ return undefined;
304
+ return Object.freeze({
305
+ name: name.trim(),
306
+ ...(typeof version === "string" && version.trim().length > 0 ? { version: version.trim() } : {}),
307
+ });
110
308
  }
111
309
  catch {
112
- return { present: false, packages: 0 };
310
+ return undefined;
113
311
  }
114
312
  }
115
313
  /**
116
- * Resolve npm without a shell: on Windows `npm` is a `.cmd` shim, which `spawn` refuses to run
117
- * directly, so the JS entry beside the shim is started through node instead (the same rule the DSH
118
- * resolver uses). A shim whose package is gone falls back to `cmd.exe /c`, the last resort.
314
+ * Whether the kernel is installed, and in which layout.
315
+ *
316
+ * The repository checkout keeps it in `apps/host/node_modules`; the npm package gets it hoisted to
317
+ * `<root>/node_modules` and has no `apps/host/node_modules` at all, so both are asked.
318
+ * @param root - checkout root.
319
+ * @returns presence, the number of top-level entries, the runtime flag and the directory that answered.
119
320
  */
120
- function npmInvocation(environment, node) {
121
- const found = environment.which("npm");
122
- if (found === undefined)
123
- return undefined;
124
- if (/\.(cmd|bat)$/iu.test(found)) {
125
- const cli = join(dirname(found), "node_modules", "npm", "bin", "npm-cli.js");
126
- if (environment.exists(cli))
127
- return { command: node, args: [cli] };
128
- return { command: environment.env.ComSpec ?? "cmd.exe", args: ["/d", "/s", "/c", found] };
321
+ export function hostModulesState(root) {
322
+ const runtime = hasDshRuntime(root);
323
+ const layouts = [
324
+ [join(root, "apps", "host", "node_modules"), "apps/host/node_modules"],
325
+ [join(root, "node_modules"), "node_modules"],
326
+ ];
327
+ for (const [dir, label] of layouts) {
328
+ try {
329
+ const entries = readdirSync(dir).filter(name => !name.startsWith("."));
330
+ if (entries.length > 0)
331
+ return { present: true, packages: entries.length, runtime, dir: label };
332
+ }
333
+ catch {
334
+ // Missing directory: the other layout is the answer.
335
+ }
129
336
  }
130
- if (/\.(js|mjs|cjs)$/iu.test(found))
131
- return { command: node, args: [found] };
132
- return { command: found, args: [] };
337
+ return { present: false, packages: 0, runtime, dir: "apps/host/node_modules" };
338
+ }
339
+ /**
340
+ * The npm ladder's facts, taken from the locate facts this installer already has.
341
+ * @param environment - PATH and filesystem facts.
342
+ * @param node - node binary that runs npm's JS entry.
343
+ * @returns a lookup `resolveNpm` can walk.
344
+ */
345
+ function npmLookupFor(environment, node) {
346
+ const env = environment.env;
347
+ return {
348
+ platform: process.platform,
349
+ env,
350
+ node,
351
+ exists: environment.exists,
352
+ // The injected `which` first (that is what tests drive), then a PATH scan of our own: the same
353
+ // npm has to be found when `which`/`where` itself is missing from a stripped environment.
354
+ which: name => environment.which(name) ?? whichOnPath(name, env, process.platform, environment.exists),
355
+ };
133
356
  }
134
357
  /**
135
358
  * The dependency steps a checkout needs, in order.
@@ -137,6 +360,11 @@ function npmInvocation(environment, node) {
137
360
  * Bun is the repository's own tool (`bun install`, then `bun install` in `apps/host`, which is not
138
361
  * a workspace member). Without Bun the host's pinned `@deepseek-ai/*` runtime is installed with
139
362
  * npm instead, which is enough for the host process but not for the CLI's own tooling.
363
+ *
364
+ * npm gets a lockfile when the checkout has one: `npm ci --omit=dev` installs exactly the pinned
365
+ * tree and fails loudly on a mismatch, and `npm install --omit=dev` is the fallback for that
366
+ * failure — and the only step when there is no `package-lock.json` at all (this repository ships
367
+ * `bun.lock`, so that is the normal path).
140
368
  * @param root - checkout root.
141
369
  * @param environment - PATH and filesystem facts.
142
370
  * @param node - node binary for npm's JS entry.
@@ -151,13 +379,149 @@ export function planDependencies(root, environment, node = process.execPath) {
151
379
  steps.push({ command: bun, args: ["install"], cwd: host, label: "bun install (apps/host)" });
152
380
  return steps;
153
381
  }
154
- const npm = npmInvocation(environment, node);
382
+ const npm = resolveNpm(npmLookupFor(environment, node));
155
383
  if (npm === undefined)
156
384
  return [];
157
385
  const host = join(root, "apps", "host");
158
386
  if (!environment.exists(join(host, "package.json")))
159
387
  return [];
160
- return [{ command: npm.command, args: [...npm.args, "install", "--omit=dev", "--no-audit", "--no-fund"], cwd: host, label: "npm install --omit=dev (apps/host)" }];
388
+ const flags = ["--omit=dev", "--no-audit", "--no-fund"];
389
+ const install = {
390
+ command: npm.command,
391
+ args: [...npmArgv(npm, ["install", ...flags])],
392
+ cwd: host,
393
+ label: "npm install --omit=dev (apps/host)",
394
+ };
395
+ if (!environment.exists(join(host, "package-lock.json")))
396
+ return [install];
397
+ return [{
398
+ command: npm.command,
399
+ args: [...npmArgv(npm, ["ci", ...flags])],
400
+ cwd: host,
401
+ label: "npm ci --omit=dev (apps/host)",
402
+ fallback: install,
403
+ }];
404
+ }
405
+ /**
406
+ * Why there is no dependency step to run, in the user's terms.
407
+ * @param root - checkout root.
408
+ * @param environment - PATH and filesystem facts.
409
+ * @returns the note `harness install` prints when it cannot install anything.
410
+ */
411
+ function dependencyGapNote(root, environment) {
412
+ const host = join(root, "apps", "host");
413
+ if (!environment.exists(join(host, "package.json"))) {
414
+ return "checkout không có apps/host/package.json — không có gì để cài (tải lại bằng --force)";
415
+ }
416
+ const lookup = npmLookupFor(environment, process.execPath);
417
+ if (resolveNpm(lookup) === undefined)
418
+ return npmMissingMessage(lookup);
419
+ return "không có package manager chạy được — cài Node.js (kèm npm) hoặc bun (https://bun.sh) rồi chạy lại";
420
+ }
421
+ /**
422
+ * The production npm fetch: run npm through the ladder that never needs PATH (it also covers node
423
+ * + `npm-cli.js`), streaming npm's own lines so a two-minute install never looks like a hang.
424
+ * @param environment - PATH and filesystem facts.
425
+ * @param node - node binary that can run npm's JS entry.
426
+ * @param write - progress sink for npm's lines.
427
+ * @returns the runner {@link fetchNpmHarness} calls.
428
+ */
429
+ function npmFetchRunner(environment, node, write) {
430
+ return async (args, cwd) => {
431
+ const result = await runNpm(args, {
432
+ lookup: npmLookupFor(environment, node),
433
+ cwd,
434
+ onLine: line => write(" " + line.trimEnd()),
435
+ });
436
+ return { code: result.code, output: result.output };
437
+ };
438
+ }
439
+ /**
440
+ * Move an npm installation into a checkout-shaped root.
441
+ *
442
+ * `npm i --prefix <dir>` leaves the package at `<dir>/node_modules/<name>` and hoists every
443
+ * dependency (the kernel included) to `<dir>/node_modules`. The launcher wants `apps/cli/src/main.ts`
444
+ * at the root and resolves its kernel by walking parent `node_modules`, so the package's own
445
+ * entries move up beside that `node_modules`.
446
+ * @param prefix - the `--prefix` directory npm installed into.
447
+ * @param packageName - the package that carries the harness.
448
+ * @param tree - directory to build the checkout in.
449
+ * @returns true when the package was there and the tree was built.
450
+ */
451
+ export function flattenNpmPackage(prefix, packageName, tree) {
452
+ const modules = join(prefix, "node_modules");
453
+ const installed = join(modules, ...packageName.split("/"));
454
+ if (!existsSync(join(installed, "package.json")))
455
+ return false;
456
+ mkdirSync(tree, { recursive: true });
457
+ // A nested node_modules only exists when npm could not hoist a version conflict; it is merged
458
+ // afterwards, because the hoisted tree is the one every other package resolves through.
459
+ let nested;
460
+ for (const entry of readdirSync(installed)) {
461
+ if (entry === "node_modules") {
462
+ nested = join(installed, entry);
463
+ continue;
464
+ }
465
+ renameSync(join(installed, entry), join(tree, entry));
466
+ }
467
+ if (existsSync(modules))
468
+ renameSync(modules, join(tree, "node_modules"));
469
+ if (nested !== undefined && existsSync(nested)) {
470
+ const target = join(tree, "node_modules");
471
+ mkdirSync(target, { recursive: true });
472
+ for (const entry of readdirSync(nested)) {
473
+ const to = join(target, entry);
474
+ if (!existsSync(to))
475
+ renameSync(join(nested, entry), to);
476
+ }
477
+ }
478
+ // The package itself now lives at the root; keeping the copy inside node_modules would be a
479
+ // second, stale tree (19 MB) that the launcher never reads.
480
+ const copy = join(tree, "node_modules", ...packageName.split("/"));
481
+ rmSync(copy, { recursive: true, force: true });
482
+ try {
483
+ rmdirSync(dirname(copy));
484
+ }
485
+ catch { /* the scope holds other packages: keep it */ }
486
+ return true;
487
+ }
488
+ /**
489
+ * Fetch the published harness with npm into a checkout-shaped tree.
490
+ *
491
+ * Measured 12/11/2026 — `npm i --omit=dev --prefix /tmp/x @galaxy-blackhole/blackhole-harness@latest`:
492
+ * 684 packages in 1m43s, package at `/tmp/x/node_modules/@galaxy-blackhole/blackhole-harness`,
493
+ * kernel at `/tmp/x/node_modules/@deepseek-ai/dsh/lib/bin.js`, and no `apps/host/node_modules`.
494
+ * That is why this rung installs no dependencies afterwards: they are already there.
495
+ * @param input - the prefix npm writes, the tree to build, cwd, facts, runner and progress sink.
496
+ * @returns whether a bootable tree is in `input.tree`, and the package request (or the failure).
497
+ */
498
+ async function fetchNpmHarness(input) {
499
+ const lookup = npmLookupFor(input.environment, input.node);
500
+ if (resolveNpm(lookup) === undefined)
501
+ return { ok: false, note: "máy không có npm — " + npmMissingMessage(lookup).split("\n")[0] };
502
+ const request = harnessPackageRequest(input.environment);
503
+ const args = npmFetchArgs(input.prefix, request);
504
+ input.write("nguồn: npm " + args.join(" "));
505
+ rmSync(input.prefix, { recursive: true, force: true });
506
+ const outcome = asOutcome(await input.npmInstall(args, input.parent));
507
+ if (outcome.code !== 0) {
508
+ writeTail(input.write, outcome.output, "npm i " + request, outcome.code);
509
+ rmSync(input.prefix, { recursive: true, force: true });
510
+ rmSync(input.tree, { recursive: true, force: true });
511
+ return { ok: false, note: "npm i " + request + " thoát mã " + String(outcome.code) };
512
+ }
513
+ const packageName = harnessPackageName(input.environment);
514
+ const flattened = flattenNpmPackage(input.prefix, packageName, input.tree);
515
+ rmSync(input.prefix, { recursive: true, force: true });
516
+ if (!flattened) {
517
+ rmSync(input.tree, { recursive: true, force: true });
518
+ return { ok: false, note: "npm không để lại node_modules/" + packageName };
519
+ }
520
+ if (!isHarnessCheckout(input.environment, input.tree)) {
521
+ rmSync(input.tree, { recursive: true, force: true });
522
+ return { ok: false, note: "gói " + request + " không có apps/cli/src/main.ts" };
523
+ }
524
+ return { ok: true, note: request };
161
525
  }
162
526
  /** Write the record every later lookup reads, beside the default slot and beside `$GBH_HOME`. */
163
527
  function writeInstallRecord(root, environment, via) {
@@ -176,40 +540,66 @@ function writeInstallRecord(root, environment, via) {
176
540
  }
177
541
  return written;
178
542
  }
179
- /** Run every dependency step; report which manager answered and whether the host is ready. */
543
+ /** Normalise what an injected runner returned. */
544
+ function asOutcome(value) {
545
+ return typeof value === "number" ? { code: value, output: "" } : value;
546
+ }
547
+ /**
548
+ * Run every dependency step; report which manager answered and whether the host can boot.
549
+ *
550
+ * "Ready" is no longer "the directory exists": the launcher boots one file
551
+ * ({@link DSH_RUNTIME_ENTRY}), and a run that exits 0 without it is a failure with its own tail
552
+ * printed — that is the Windows bug where the download said "xong" and the boot said
553
+ * `harness runtime not found`.
554
+ */
180
555
  async function runDependencies(input) {
181
556
  if (input.skip)
182
- return { deps: "skipped", ready: hostModulesState(input.root).present, note: "--no-deps: chưa cài phụ thuộc" };
183
- if (!input.force && hostModulesState(input.root).present) {
184
- input.write("phụ thuộc: apps/host/node_modules đã có — bỏ qua (dùng --force để cài lại)");
557
+ return { deps: "skipped", ready: hasDshRuntime(input.root), note: "--no-deps: chưa cài phụ thuộc" };
558
+ if (!input.force && hasDshRuntime(input.root)) {
559
+ input.write("phụ thuộc: " + dshRuntimeEntry(input.root) + " đã có — bỏ qua (dùng --force để cài lại)");
185
560
  return { deps: "skipped", ready: true };
186
561
  }
187
562
  const steps = planDependencies(input.root, input.environment);
188
563
  if (steps.length === 0) {
189
- return {
190
- deps: "skipped",
191
- ready: false,
192
- note: "không thấy bun hay npm trên PATH — cài Node.js (kèm npm) hoặc bun (https://bun.sh) rồi chạy lại",
193
- };
564
+ return { deps: "skipped", ready: false, note: dependencyGapNote(input.root, input.environment) };
194
565
  }
195
- const manager = basename(steps[0].command).toLowerCase().startsWith("bun") ? "bun" : "npm";
566
+ const manager = /\bnpm\b/u.test(steps[0].label) ? "npm" : "bun";
567
+ let last = "";
196
568
  for (const step of steps) {
197
569
  input.write("phụ thuộc: " + step.label + " (cwd " + step.cwd + ")");
198
- const code = await input.run(step.command, step.args, step.cwd);
199
- if (code !== 0) {
200
- return { deps: "failed", ready: hostModulesState(input.root).present, note: step.label + " thoát mã " + String(code) };
570
+ let used = step;
571
+ let outcome = asOutcome(await input.run(step.command, step.args, step.cwd));
572
+ if (outcome.code !== 0 && step.fallback !== undefined) {
573
+ input.write("phụ thuộc: " + step.label + " lỗi (mã " + String(outcome.code) + ") — thử " + step.fallback.label);
574
+ used = step.fallback;
575
+ outcome = asOutcome(await input.run(used.command, used.args, used.cwd));
576
+ }
577
+ last = outcome.output;
578
+ if (outcome.code !== 0) {
579
+ writeTail(input.write, outcome.output, used.label, outcome.code);
580
+ return { deps: "failed", ready: false, note: used.label + " thoát mã " + String(outcome.code) };
201
581
  }
202
582
  }
583
+ if (!hasDshRuntime(input.root)) {
584
+ // npm exits 0 for an empty tree and for skipped optional dependencies; its own output is the
585
+ // only place that says so, and silence here is what made the old install look successful.
586
+ writeTail(input.write, last, "bước cài phụ thuộc", 0);
587
+ return { deps: "failed", ready: false, note: harnessRuntimeMissingMessage(input.root) };
588
+ }
203
589
  return {
204
590
  deps: manager,
205
- ready: hostModulesState(input.root).present,
591
+ ready: true,
206
592
  ...(manager === "npm"
207
- ? { note: "đã cài apps/host bằng npm; repo dùng bun cho bước đầy đủ (bun run setup) — cài bun tại https://bun.sh nếu launcher báo thiếu gói" }
593
+ ? { note: "đã cài apps/host bằng npm (có " + DSH_RUNTIME_ENTRY + "); repo dùng bun cho bước đầy đủ (bun run setup) — cài bun tại https://bun.sh nếu launcher báo thiếu gói khác" }
208
594
  : {}),
209
595
  };
210
596
  }
211
597
  /**
212
- * Download (or reuse) the harness checkout and install its dependencies.
598
+ * Download (or reuse) the harness checkout and make sure it can boot.
599
+ *
600
+ * Rungs, in order: `--from` when the user named a source (and `--from npm` forces the npm package),
601
+ * then the published npm package, then `git clone --depth 1`, then the GitHub ZIP. `--no-deps` keeps
602
+ * its old meaning — download only — so it skips npm, which always installs the package's dependencies.
213
603
  * @param options - destination, force, source override, progress sink and injected process facts.
214
604
  * @returns the checkout root, how it arrived and whether it is ready to boot.
215
605
  * @throws when the download fails, the archive has no launcher, or the destination is unsafe.
@@ -217,9 +607,10 @@ async function runDependencies(input) {
217
607
  export async function installHarness(options = {}) {
218
608
  const environment = options.environment ?? systemLocateEnvironment();
219
609
  const write = options.write ?? (line => { process.stdout.write(line + "\n"); });
220
- const run = options.run ?? runInherit;
610
+ const run = options.run ?? runCaptured(write);
221
611
  const download = options.download ?? downloadToFile;
222
612
  const node = options.node ?? process.execPath;
613
+ const npmInstall = options.npmInstall ?? npmFetchRunner(environment, node, write);
223
614
  const root = resolveInstallRoot(options, environment);
224
615
  assertReplaceable(root);
225
616
  write("harness: " + root);
@@ -233,34 +624,60 @@ export async function installHarness(options = {}) {
233
624
  return { root, via: "existing", downloaded: false, deps: deps.deps, ready: deps.ready, ...(deps.note === undefined ? {} : { note: deps.note }) };
234
625
  }
235
626
  const archive = (environment.env.GBH_TAURI_ARCHIVE ?? "").trim();
236
- const repo = (environment.env.GBH_TAURI_REPO ?? "").trim() || HARNESS_REPO;
627
+ const pinnedRepo = (environment.env.GBH_TAURI_REPO ?? "").trim();
628
+ const repo = pinnedRepo.length > 0 ? pinnedRepo : HARNESS_REPO;
237
629
  const branch = (environment.env.GBH_TAURI_BRANCH ?? "").trim() || HARNESS_BRANCH;
238
630
  const from = (options.from ?? "").trim();
239
- const zipSource = from.length > 0 ? /\.zip(?:\?.*)?$/iu.test(from) : archive.length > 0;
240
- const gitSource = from.length > 0 ? (zipSource ? "" : from) : repo;
631
+ // "--from npm" names a source, not a URL: it forces the published package and forbids the fallback.
632
+ const forcedNpm = /^npm$/iu.test(from);
633
+ const fromUrl = forcedNpm ? "" : from;
634
+ const zipSource = fromUrl.length > 0 ? /\.zip(?:\?.*)?$/iu.test(fromUrl) : archive.length > 0;
635
+ const gitSource = fromUrl.length > 0 ? (zipSource ? "" : fromUrl) : repo;
636
+ // npm is the default rung unless the user pinned a source of their own. With --no-deps it steps
637
+ // aside: npm cannot install the package without its dependencies, and --no-deps promises
638
+ // "tải về rồi thôi", which the git/ZIP rungs still deliver.
639
+ const npmDefault = fromUrl.length === 0 && archive.length === 0 && pinnedRepo.length === 0;
640
+ const npmWanted = options.noDeps !== true && (forcedNpm || npmDefault);
641
+ if (options.noDeps === true && (forcedNpm || npmDefault)) {
642
+ write("nguồn: --no-deps: bỏ qua npm (npm luôn cài kèm phụ thuộc) — tải bản git/ZIP");
643
+ }
241
644
  const parent = dirname(root);
242
645
  mkdirSync(parent, { recursive: true });
243
646
  const staging = join(parent, "." + HARNESS_DIR_NAME + "-tai-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 6));
647
+ const npmPrefix = staging + "-npm";
244
648
  let via = "zip";
245
649
  try {
246
- const git = zipSource ? undefined : environment.which("git");
247
- if (!zipSource && gitSource.length > 0 && git !== undefined) {
650
+ if (npmWanted) {
651
+ const fetched = await fetchNpmHarness({ prefix: npmPrefix, tree: staging, parent, node, environment, npmInstall, write });
652
+ if (fetched.ok)
653
+ via = "npm";
654
+ else if (forcedNpm) {
655
+ throw new Error("cài harness từ npm thất bại: " + fetched.note +
656
+ "\n bỏ --from npm để thử git clone/ZIP, hoặc thử lại khi mạng tới registry.npmjs.org ổn định.");
657
+ }
658
+ else {
659
+ write("npm không dùng được (" + fetched.note + ") — chuyển sang git clone / ZIP");
660
+ }
661
+ }
662
+ const git = zipSource || via === "npm" ? undefined : environment.which("git");
663
+ if (via !== "npm" && !zipSource && gitSource.length > 0 && git !== undefined) {
248
664
  write("nguồn: git clone --depth 1 --branch " + branch + " " + gitSource);
249
- const code = await run(git, ["clone", "--depth", "1", "--branch", branch, gitSource, staging], parent);
250
- if (code === 0)
665
+ // A runner may answer with a code or with a code plus output; both mean the same here.
666
+ const cloned = asOutcome(await run(git, ["clone", "--depth", "1", "--branch", branch, gitSource, staging], parent));
667
+ if (cloned.code === 0)
251
668
  via = "git";
252
669
  else {
253
670
  rmSync(staging, { recursive: true, force: true });
254
- write("git clone lỗi (mã " + String(code) + ") — chuyển sang tải ZIP");
671
+ write("git clone lỗi (mã " + String(cloned.code) + ") — chuyển sang tải ZIP");
255
672
  }
256
673
  }
257
674
  if (via === "zip") {
258
675
  // A --from that names a local repository is only reachable through git; without it the ZIP
259
676
  // fallback would build a meaningless archive URL, so say what is missing instead.
260
- if (!zipSource && from.length > 0 && git === undefined) {
261
- throw new Error("--from " + from + " cần git để clone, và máy này không có git trên PATH. Cài git, hoặc dùng --from <url .zip>.");
677
+ if (!zipSource && fromUrl.length > 0 && git === undefined) {
678
+ throw new Error("--from " + fromUrl + " cần git để clone, và máy này không có git trên PATH. Cài git, hoặc dùng --from <url .zip>.");
262
679
  }
263
- const url = zipSource ? (from.length > 0 ? from : archive) : archiveUrl(gitSource.length > 0 ? gitSource : HARNESS_REPO, branch);
680
+ const url = zipSource ? (fromUrl.length > 0 ? fromUrl : archive) : archiveUrl(gitSource.length > 0 ? gitSource : HARNESS_REPO, branch);
264
681
  write("nguồn: tải ZIP " + url);
265
682
  const file = staging + ".zip";
266
683
  try {
@@ -278,7 +695,7 @@ export async function installHarness(options = {}) {
278
695
  write("đã giải nén: " + String(summary.files) + " tệp, " + String(summary.dirs) + " thư mục" + (summary.links === 0 ? "" : ", " + String(summary.links) + " symlink"));
279
696
  }
280
697
  if (!isHarnessCheckout(environment, staging)) {
281
- throw new Error("gói tải về không có apps/cli/src/main.ts — không phải checkout blackhole-tauri");
698
+ throw new Error("gói tải về không có apps/cli/src/main.ts — không phải checkout blackhole-harness");
282
699
  }
283
700
  rmSync(root, { recursive: true, force: true });
284
701
  renameSync(staging, root);
@@ -286,12 +703,26 @@ export async function installHarness(options = {}) {
286
703
  catch (error) {
287
704
  rmSync(staging, { recursive: true, force: true });
288
705
  rmSync(staging + ".zip", { force: true });
706
+ rmSync(npmPrefix, { recursive: true, force: true });
289
707
  throw error;
290
708
  }
291
709
  const version = readHarnessVersion(root);
292
710
  write("đã tải: " + root + (version === undefined ? "" : " (harness " + version + ")"));
293
711
  for (const record of writeInstallRecord(root, environment, via))
294
712
  write("ghi nhớ: " + record);
713
+ if (via === "npm") {
714
+ // The package's own dependencies came with it, hoisted beside the tree: a second npm install
715
+ // would only re-install the kernel. Readiness is the runtime file, in either layout.
716
+ const ready = hasDshRuntime(root);
717
+ return {
718
+ root, via, downloaded: true,
719
+ deps: ready ? "npm" : "failed",
720
+ ready,
721
+ ...(ready
722
+ ? { note: "cài từ npm " + harnessPackageRequest(environment) + " — gói đã kèm phụ thuộc, không chạy bước npm install riêng" }
723
+ : { note: harnessRuntimeMissingMessage(root) }),
724
+ };
725
+ }
295
726
  const deps = await runDependencies({ root, environment, run, write, force: true, skip: options.noDeps === true });
296
727
  return { root, via, downloaded: true, deps: deps.deps, ready: deps.ready, ...(deps.note === undefined ? {} : { note: deps.note }) };
297
728
  }
@@ -313,15 +744,17 @@ export function harnessStatusFacts(environment = systemLocateEnvironment()) {
313
744
  const root = location?.root;
314
745
  const hostVersion = root === undefined ? undefined : readHarnessVersion(join(root, "apps", "host"));
315
746
  const version = root === undefined ? undefined : readHarnessVersion(root);
747
+ const packageSource = root === undefined ? undefined : readHarnessPackage(root, environment);
316
748
  const bun = findBun(environment);
317
749
  return Object.freeze({
318
750
  ...(location === undefined ? {} : { location }),
319
751
  ...(version === undefined ? {} : { version }),
320
752
  ...(hostVersion === undefined ? {} : { hostVersion }),
753
+ ...(packageSource === undefined ? {} : { packageSource }),
321
754
  ...(node === undefined ? {} : { node }),
322
755
  ...(nodeError === undefined ? {} : { nodeError }),
323
756
  ...(bun === undefined ? {} : { bun }),
324
- hostModules: root === undefined ? { present: false, packages: 0 } : hostModulesState(root),
757
+ hostModules: root === undefined ? { present: false, packages: 0, runtime: false, dir: "apps/host/node_modules" } : hostModulesState(root),
325
758
  home: harnessHome(environment),
326
759
  defaultDir: defaultHarnessDir(environment),
327
760
  });