@buaa_smat/hometrans 26.0.6-devecocli.1 → 26.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2618 @@
1
+ /**
2
+ * `ht init` — interactive initialization for HomeTrans.
3
+ *
4
+ * Displays the HomeTrans banner, lets the user select which editors to
5
+ * configure, then copies bundled skills/agents/commands into the chosen editors.
6
+ */
7
+ import fs from 'node:fs/promises';
8
+ import fsSync from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import crypto from 'node:crypto';
12
+ import { execFileSync, spawnSync } from 'node:child_process';
13
+ import { fileURLToPath } from 'node:url';
14
+ import chalk from 'chalk';
15
+ import figlet from 'figlet';
16
+ import inquirer from 'inquirer';
17
+ import { defaultEditors, deriveSdkPaths, ENV_KEYS, envFromProcess, SHARED_AGENTS_FALLBACK, } from './config-store.js';
18
+ import { persistEnvVars } from './env-vars.js';
19
+ import { installTo, listBundledAgents, listBundledCommands, listBundledSkills, } from '../platform/installer.js';
20
+ import { pathExists } from '../platform/compose.js';
21
+ import { DEFAULT_INSTALL_LANGUAGE, loadLanguageOverlay, stageEnglishRoots, } from '../platform/language.js';
22
+ import { editorDisplayName, platformForEditor } from '../platform/registry.js';
23
+ import { mapAgentColorToHex } from '../platform/transform.js';
24
+ function ensureChalkColor() {
25
+ if (process.stdout.isTTY && chalk.level === 0) {
26
+ chalk.level = 1;
27
+ }
28
+ }
29
+ /**
30
+ * Did the user abort an inquirer prompt with Ctrl-C / Esc?
31
+ * inquirer v14 (@inquirer/core) rejects with an `ExitPromptError` in that case.
32
+ * We must distinguish this from a genuine non-interactive failure (no TTY),
33
+ * otherwise Ctrl-C silently gets swallowed and the install proceeds anyway.
34
+ */
35
+ export function isPromptAbort(err) {
36
+ return err instanceof Error && err.name === 'ExitPromptError';
37
+ }
38
+ /** Print a cancellation notice and exit with the conventional SIGINT code. */
39
+ function abortInit() {
40
+ console.log(chalk.yellow('\n Cancelled. No changes were made beyond this point.\n'));
41
+ process.exit(130);
42
+ }
43
+ const __filename = fileURLToPath(import.meta.url);
44
+ const __dirname = path.dirname(__filename);
45
+ /**
46
+ * Whether `ht init` should exit non-zero. Per-target failures are collected
47
+ * instead of thrown (one broken target must not abort the rest), and every
48
+ * selected target being skipped means nothing was deployed — both are failures
49
+ * for scripts and CI. The shared ~/.agents fallback (no editors selected) is
50
+ * not a failure on its own.
51
+ */
52
+ export function initFailed(result, noEditorsSelected) {
53
+ if (result.errors.length > 0)
54
+ return true;
55
+ return !noEditorsSelected && result.configured.length === 0;
56
+ }
57
+ export async function dirExists(dirPath) {
58
+ try {
59
+ const stat = await fs.stat(dirPath);
60
+ return stat.isDirectory();
61
+ }
62
+ catch {
63
+ return false;
64
+ }
65
+ }
66
+ function resolveSkillsRoot() {
67
+ return path.resolve(__dirname, '..', '..', 'skills');
68
+ }
69
+ function resolveAgentsRoot() {
70
+ return path.resolve(__dirname, '..', '..', 'agents');
71
+ }
72
+ function resolveCommandsRoot() {
73
+ return path.resolve(__dirname, '..', '..', 'commands');
74
+ }
75
+ /**
76
+ * Install the bundled skills/agents/commands into one editor's target dirs.
77
+ *
78
+ * The real work lives in `src/platform/installer.ts`, which composes each
79
+ * document from the platform table (`editors.json`) plus the optional
80
+ * `platforms/` overlays — the same pipeline `devecocli plugin install` uses.
81
+ */
82
+ export async function installForEditor(editor, skillsRoot, agentsRoot, commandsRoot, result, options = {}) {
83
+ const platform = platformForEditor(editor);
84
+ // Output label (`Claude Code`), not the canonical id (`claude-code`) — the id
85
+ // stays the config key / selection value everywhere.
86
+ const label = editorDisplayName(editor.name);
87
+ const marker = platform.markerDir;
88
+ if (marker && !(await dirExists(marker))) {
89
+ result.skipped.push(`${label} (not installed)`);
90
+ return;
91
+ }
92
+ const roots = {
93
+ skillsRoot,
94
+ agentsRoot,
95
+ commandsRoot,
96
+ platformsRoot: resolvePlatformsRoot(),
97
+ };
98
+ const skillsDir = platform.skillsDir;
99
+ const agentsDir = platform.agentsDir;
100
+ // Same-name items already in the editor's dirs → ask before overwriting.
101
+ const skillConflicts = [];
102
+ if (skillsDir) {
103
+ for (const name of await listBundledSkills(skillsRoot)) {
104
+ if (await pathExists(path.join(skillsDir, name)))
105
+ skillConflicts.push(name);
106
+ }
107
+ }
108
+ const agentConflicts = [];
109
+ if (agentsDir) {
110
+ for (const name of await listBundledAgents(agentsRoot)) {
111
+ if (await pathExists(path.join(agentsDir, name)))
112
+ agentConflicts.push(name);
113
+ }
114
+ }
115
+ const commandConflicts = [];
116
+ const commandTargetDir = platform.commandsAsSkills && platform.skillsDir ? platform.skillsDir : platform.commandsDir;
117
+ if (commandTargetDir) {
118
+ for (const name of await listBundledCommands(commandsRoot)) {
119
+ // commandsAsSkills platforms store each command as skills/<name>/SKILL.md
120
+ const targetName = platform.commandsAsSkills && platform.skillsDir ? name.replace(/\.md$/, '') : name;
121
+ if (await pathExists(path.join(commandTargetDir, targetName)))
122
+ commandConflicts.push(name);
123
+ }
124
+ }
125
+ let overwrite = true;
126
+ const hasConflicts = skillConflicts.length > 0 || agentConflicts.length > 0 || commandConflicts.length > 0;
127
+ if (hasConflicts && !options.force) {
128
+ overwrite = await confirmOverwrite(label, skillConflicts, agentConflicts, commandConflicts);
129
+ }
130
+ // N = incremental install: keep the conflicting items untouched, still copy
131
+ // everything that doesn't exist in the target dirs yet.
132
+ const skip = (names) => (overwrite ? new Set() : new Set(names));
133
+ const skipSkills = skip(skillConflicts);
134
+ const skipAgents = skip(agentConflicts);
135
+ const skipCommands = skip(commandConflicts);
136
+ try {
137
+ const r = await installTo(platform, roots, {
138
+ force: options.force,
139
+ skipSkills,
140
+ skipAgents,
141
+ skipCommands,
142
+ });
143
+ if (r.skills > 0 && skillsDir) {
144
+ result.configured.push(`${label} skills (${r.skills} -> ${prettyHome(skillsDir)})`);
145
+ }
146
+ if (r.agents > 0 && agentsDir) {
147
+ result.configured.push(`${label} agents (${r.agents} -> ${prettyHome(agentsDir)})`);
148
+ }
149
+ if (r.commands > 0) {
150
+ const shown = platform.commandsAsSkills && platform.skillsDir
151
+ ? platform.skillsDir
152
+ : platform.commandsDir ?? platform.skillsDir ?? '';
153
+ result.configured.push(`${label} commands (${r.commands} -> ${prettyHome(shown)})`);
154
+ }
155
+ if (!overwrite) {
156
+ result.skipped.push(`${label} existing kept: ${skipSkills.size} skills, ${skipAgents.size} agents, ${skipCommands.size} commands (new items installed)`);
157
+ }
158
+ for (const note of r.skipped)
159
+ result.skipped.push(note);
160
+ for (const issue of r.issues) {
161
+ const line = `[${issue.level}] ${label}: ${issue.message}`;
162
+ if (issue.level === 'error')
163
+ result.errors.push(line);
164
+ else
165
+ result.skipped.push(line);
166
+ }
167
+ }
168
+ catch (err) {
169
+ result.errors.push(`${label}: ${err.message}`);
170
+ }
171
+ }
172
+ /** Optional overlay root (`<packageRoot>/platforms`); absent in published builds. */
173
+ export function resolvePlatformsRoot() {
174
+ return path.resolve(__dirname, '..', '..', 'platforms');
175
+ }
176
+ /** English overlay root (`<packageRoot>/i18n`). */
177
+ function resolveI18nRoot() {
178
+ return path.resolve(__dirname, '..', '..', 'i18n');
179
+ }
180
+ /** `--lang` wins; `--all` and non-interactive shells get the default; otherwise ask. */
181
+ async function chooseInstallLanguage(options) {
182
+ if (options.lang)
183
+ return options.lang;
184
+ if (options.all)
185
+ return DEFAULT_INSTALL_LANGUAGE;
186
+ try {
187
+ const answers = await inquirer.prompt([
188
+ {
189
+ type: 'select',
190
+ name: 'language',
191
+ message: 'Select the language to install:',
192
+ choices: [
193
+ { name: '中文', value: 'zh' },
194
+ { name: 'English', value: 'en' },
195
+ ],
196
+ default: DEFAULT_INSTALL_LANGUAGE,
197
+ loop: false,
198
+ },
199
+ ]);
200
+ return answers.language;
201
+ }
202
+ catch (err) {
203
+ if (isPromptAbort(err))
204
+ abortInit();
205
+ return DEFAULT_INSTALL_LANGUAGE;
206
+ }
207
+ }
208
+ /** Backwards-compatible export; the implementation moved to the platform layer. */
209
+ export const mapAgentMarkdownColorToHex = mapAgentColorToHex;
210
+ /**
211
+ * Ask whether same-name skills/agents/commands already present in the editor's target
212
+ * dirs may be overwritten. Returns true (overwrite) when the user confirms or
213
+ * the shell is non-interactive (legacy behavior); false keeps existing files —
214
+ * the caller then only refreshes the API-key config files. Ctrl-C aborts init.
215
+ */
216
+ async function confirmOverwrite(editorName, skillConflicts, agentConflicts, commandConflicts) {
217
+ console.log(chalk.yellow(` ! ${editorName}: the following already exist and would be overwritten:`));
218
+ if (skillConflicts.length > 0) {
219
+ console.log(chalk.yellow(` skills: ${skillConflicts.join(', ')}`));
220
+ }
221
+ if (agentConflicts.length > 0) {
222
+ console.log(chalk.yellow(` agents: ${agentConflicts.join(', ')}`));
223
+ }
224
+ if (commandConflicts.length > 0) {
225
+ console.log(chalk.yellow(` commands: ${commandConflicts.join(', ')}`));
226
+ }
227
+ try {
228
+ const answers = await inquirer.prompt([
229
+ {
230
+ type: 'confirm',
231
+ name: 'overwrite',
232
+ message: `Overwrite them in ${editorName}? (N = keep existing files; new items are still installed and API-key configs refreshed)`,
233
+ default: true,
234
+ },
235
+ ]);
236
+ return answers.overwrite;
237
+ }
238
+ catch (err) {
239
+ if (isPromptAbort(err))
240
+ abortInit();
241
+ console.log(chalk.yellow(' Non-interactive: overwriting by default.'));
242
+ return true;
243
+ }
244
+ }
245
+ /**
246
+ * Display paths as full absolute OS-native paths (e.g. on Windows:
247
+ * `C:\Users\<you>\.claude\skills`) — no `~` abbreviation, no separator
248
+ * rewriting, so output matches what the user can copy into their shell.
249
+ */
250
+ export function prettyHome(p) {
251
+ return p;
252
+ }
253
+ /** Bundled at the package root, alongside skills/ and agents/. */
254
+ function resolveEnvRequirementsPath() {
255
+ return path.resolve(__dirname, '..', '..', 'env-requirements.json');
256
+ }
257
+ /**
258
+ * Load env-requirements.json. The leading `$`-prefixed keys are documentation
259
+ * and ignored. Returns null (with a warning) if the file is missing or invalid
260
+ * so `ht init` degrades gracefully instead of crashing.
261
+ */
262
+ export async function loadEnvRequirements() {
263
+ const p = resolveEnvRequirementsPath();
264
+ let raw;
265
+ try {
266
+ raw = await fs.readFile(p, 'utf-8');
267
+ }
268
+ catch {
269
+ console.log(chalk.yellow(` ! env-requirements.json not found at ${p} — skipping impact check.`));
270
+ return null;
271
+ }
272
+ try {
273
+ const parsed = JSON.parse(raw);
274
+ if (!parsed.tools || !Array.isArray(parsed.requirements)) {
275
+ throw new Error('expected { tools: {...}, requirements: [...] }');
276
+ }
277
+ return parsed;
278
+ }
279
+ catch (err) {
280
+ console.log(chalk.yellow(` ! env-requirements.json is invalid (${err.message}) — skipping impact check.`));
281
+ return null;
282
+ }
283
+ }
284
+ /** Locate a command on PATH (`where` on Windows, `which` elsewhere). */
285
+ function whichSync(cmd) {
286
+ const isWin = process.platform === 'win32';
287
+ try {
288
+ const out = execFileSync(isWin ? 'where' : 'which', [cmd], {
289
+ encoding: 'utf-8',
290
+ timeout: 5000,
291
+ stdio: ['ignore', 'pipe', 'ignore'],
292
+ });
293
+ const lines = out.split('\n').map((l) => l.trim()).filter(Boolean);
294
+ return lines[0] || null;
295
+ }
296
+ catch {
297
+ return null;
298
+ }
299
+ }
300
+ /**
301
+ * Run a tool's verify command and return its first non-empty output line.
302
+ * Reads the configured stream first (stdout by default; stderr for `java
303
+ * -version`), falling back to the combined output if that stream is empty.
304
+ */
305
+ function captureVerify(cmd, args, stream) {
306
+ const r = spawnSync(cmd, args, { encoding: 'utf-8', timeout: 5000 });
307
+ if (r.error)
308
+ return null;
309
+ const primary = stream === 'stderr' ? r.stderr : r.stdout;
310
+ const text = primary && primary.trim() ? primary : `${r.stdout ?? ''}\n${r.stderr ?? ''}`;
311
+ const line = (text ?? '').split('\n').map((l) => l.trim()).filter(Boolean)[0];
312
+ return line || null;
313
+ }
314
+ async function fileExists(p) {
315
+ try {
316
+ await fs.access(p);
317
+ return true;
318
+ }
319
+ catch {
320
+ return false;
321
+ }
322
+ }
323
+ /** Parse the first dotted-number sequence into [major, minor, patch]. */
324
+ export function parseVersion(s) {
325
+ const m = s.match(/(\d+)(?:\.(\d+))?(?:\.(\d+))?/);
326
+ if (!m)
327
+ return null;
328
+ return [Number(m[1] || 0), Number(m[2] || 0), Number(m[3] || 0)];
329
+ }
330
+ function cmpVersion(a, b) {
331
+ for (let i = 0; i < 3; i++) {
332
+ const d = a[i] - b[i];
333
+ if (d !== 0)
334
+ return d < 0 ? -1 : 1;
335
+ }
336
+ return 0;
337
+ }
338
+ /**
339
+ * Is `version` inside the [min, max) window? Unparseable versions or an absent
340
+ * range are treated as satisfied (we never block on what we can't measure).
341
+ */
342
+ export function versionInRange(version, range) {
343
+ if (!range || (!range.min && !range.max))
344
+ return true;
345
+ const pv = parseVersion(version);
346
+ if (!pv)
347
+ return true;
348
+ if (range.min) {
349
+ const pm = parseVersion(range.min);
350
+ if (pm && cmpVersion(pv, pm) < 0)
351
+ return false;
352
+ }
353
+ if (range.max) {
354
+ const px = parseVersion(range.max);
355
+ if (px && cmpVersion(pv, px) >= 0)
356
+ return false;
357
+ }
358
+ return true;
359
+ }
360
+ /** Human-readable form of a range, e.g. ">= 3.10", "< 2.0", "[1.0, 2.0)". */
361
+ function describeRange(range) {
362
+ if (!range)
363
+ return '';
364
+ if (range.min && range.max)
365
+ return `[${range.min}, ${range.max})`;
366
+ if (range.min)
367
+ return `>= ${range.min}`;
368
+ if (range.max)
369
+ return `< ${range.max}`;
370
+ return '';
371
+ }
372
+ /**
373
+ * Detect every tool declared in env-requirements.json. `source: 'env-dir'`
374
+ * tools are a directory check; `source: 'path'` tools are located by trying
375
+ * each alias on PATH, then the optional DevEco fallback path. When a `verify`
376
+ * command is present we also capture and parse the tool's version.
377
+ */
378
+ async function detectEnvironment(spec, env) {
379
+ const status = new Map();
380
+ const isWin = process.platform === 'win32';
381
+ const baseDir = (key) => key === 'DEVECO_SDK_HOME'
382
+ ? env.DEVECO_SDK_HOME
383
+ : key === 'DEVECO_HOME'
384
+ ? env.DEVECO_HOME
385
+ : '';
386
+ for (const [id, tool] of Object.entries(spec.tools)) {
387
+ if (tool.source === 'env-dir') {
388
+ const dir = tool.envVar ? baseDir(tool.envVar) : '';
389
+ const ok = dir ? await dirExists(dir) : false;
390
+ status.set(id, { found: ok, path: ok ? dir : undefined });
391
+ continue;
392
+ }
393
+ // source 'python-import': probe a pip package by importing it with the
394
+ // first Python interpreter found on PATH. Same alias resolution as the
395
+ // python tool itself, and no shell — keeps `-c` code quoting-proof.
396
+ if (tool.source === 'python-import') {
397
+ const aliases = tool.aliases?.length ? tool.aliases : ['python', 'python3', 'py'];
398
+ const code = `import ${(tool.imports ?? [id]).join(', ')}`;
399
+ let found = false;
400
+ let resolved;
401
+ for (const alias of aliases) {
402
+ const p = whichSync(alias);
403
+ if (!p)
404
+ continue;
405
+ resolved = p;
406
+ const r = spawnSync(p, ['-c', code], { encoding: 'utf-8', timeout: 30_000 });
407
+ if (r.status === 0) {
408
+ found = true;
409
+ break;
410
+ }
411
+ }
412
+ status.set(id, { found, path: resolved });
413
+ continue;
414
+ }
415
+ // source 'path': try each alias on PATH, then the fallback path.
416
+ const aliases = tool.aliases?.length ? tool.aliases : [id];
417
+ let resolvedPath = null;
418
+ let cmdToRun = null;
419
+ for (const alias of aliases) {
420
+ const p = whichSync(alias);
421
+ if (p) {
422
+ resolvedPath = p;
423
+ cmdToRun = alias;
424
+ break;
425
+ }
426
+ }
427
+ let viaFallback = false;
428
+ if (!resolvedPath && tool.fallback) {
429
+ const base = baseDir(tool.fallback.base);
430
+ if (base) {
431
+ const exe = isWin ? `${tool.fallback.exe}.exe` : tool.fallback.exe;
432
+ const cand = path.join(base, ...tool.fallback.segments, exe);
433
+ if (await fileExists(cand)) {
434
+ resolvedPath = cand;
435
+ cmdToRun = cand;
436
+ viaFallback = true;
437
+ }
438
+ }
439
+ }
440
+ const st = { found: !!resolvedPath, path: resolvedPath ?? undefined };
441
+ if (resolvedPath && cmdToRun && tool.verify) {
442
+ const raw = captureVerify(cmdToRun, tool.verify, tool.versionStream === 'stderr' ? 'stderr' : 'stdout');
443
+ if (raw) {
444
+ st.note = viaFallback ? `${raw} (via ${tool.fallback.base} fallback)` : raw;
445
+ if (tool.versionRegex) {
446
+ const m = raw.match(new RegExp(tool.versionRegex));
447
+ if (m && m[1])
448
+ st.version = m[1];
449
+ }
450
+ }
451
+ else if (viaFallback) {
452
+ st.note = `via ${tool.fallback.base} fallback`;
453
+ }
454
+ }
455
+ else if (viaFallback) {
456
+ st.note = `via ${tool.fallback.base} fallback`;
457
+ }
458
+ status.set(id, st);
459
+ }
460
+ return status;
461
+ }
462
+ /**
463
+ * A dependency is satisfied when its tool is present AND its detected version
464
+ * (if known) falls in the required range (dependency range overrides the tool
465
+ * default). Returns the reason token shown in the impact table when not.
466
+ */
467
+ function evaluateDependency(dep, spec, tools) {
468
+ const st = tools.get(dep.tool);
469
+ const range = dep.version ?? spec.tools[dep.tool]?.version ?? null;
470
+ if (!st || !st.found) {
471
+ return { satisfied: false, reason: dep.tool };
472
+ }
473
+ if (st.version && !versionInRange(st.version, range)) {
474
+ return {
475
+ satisfied: false,
476
+ reason: `${dep.tool} ${st.version} (need ${describeRange(range)})`,
477
+ };
478
+ }
479
+ return { satisfied: true, reason: '' };
480
+ }
481
+ /** Print detected tools + the per-skill/agent impact table. */
482
+ export async function runEnvironmentCheck(env) {
483
+ console.log('');
484
+ console.log(chalk.cyan(' Environment Check'));
485
+ const spec = await loadEnvRequirements();
486
+ if (!spec)
487
+ return;
488
+ const tools = await detectEnvironment(spec, env);
489
+ const order = Object.keys(spec.tools);
490
+ for (const name of order) {
491
+ const st = tools.get(name);
492
+ const tool = spec.tools[name];
493
+ const label = (tool.label ?? name).padEnd(12);
494
+ if (st.found) {
495
+ let note = st.note ?? '';
496
+ if (st.version && tool.version && !versionInRange(st.version, tool.version)) {
497
+ note += ` (requires ${describeRange(tool.version)})`;
498
+ }
499
+ const noteStr = note ? chalk.gray(` (${note})`) : '';
500
+ console.log(` ${chalk.green('+')} ${label} ${st.path ?? ''}${noteStr}`);
501
+ }
502
+ else {
503
+ console.log(` ${chalk.yellow('!')} ${label} ${chalk.yellow('not found')} ${chalk.gray(tool.hint ?? '')}`);
504
+ }
505
+ }
506
+ console.log('');
507
+ console.log(chalk.cyan(' Impact on skills/agents:'));
508
+ const nameW = 28;
509
+ console.log(chalk.gray(` ${'Name'.padEnd(nameW)} ${'Kind'.padEnd(6)} ${'Status'.padEnd(8)} Missing`));
510
+ let allOk = true;
511
+ for (const row of spec.requirements) {
512
+ const unmetReq = [];
513
+ const unmetOpt = [];
514
+ for (const dep of row.dependencies) {
515
+ const { satisfied, reason } = evaluateDependency(dep, spec, tools);
516
+ if (satisfied)
517
+ continue;
518
+ if (dep.level === 'required')
519
+ unmetReq.push(reason);
520
+ else
521
+ unmetOpt.push(`${reason}(optional)`);
522
+ }
523
+ let plain;
524
+ let color;
525
+ let parts;
526
+ if (unmetReq.length > 0) {
527
+ plain = 'BLOCKED';
528
+ color = chalk.red;
529
+ parts = [...unmetReq, ...unmetOpt];
530
+ allOk = false;
531
+ }
532
+ else if (unmetOpt.length > 0) {
533
+ plain = 'LIMITED';
534
+ color = chalk.yellow;
535
+ parts = unmetOpt;
536
+ allOk = false;
537
+ }
538
+ else {
539
+ plain = 'OK';
540
+ color = chalk.green;
541
+ parts = [];
542
+ }
543
+ const noteStr = parts.length > 0 && row.note ? chalk.gray(` — ${row.note}`) : '';
544
+ console.log(` ${row.name.padEnd(nameW)} ${row.kind.padEnd(6)} ${color(plain.padEnd(8))} ${parts.join(', ')}${noteStr}`);
545
+ }
546
+ if (!allOk) {
547
+ console.log('');
548
+ console.log(chalk.gray(' Install the missing tools above and re-run `ht init` to clear the impact list.'));
549
+ }
550
+ }
551
+ export async function detectInstalledEditors(editors) {
552
+ const status = new Map();
553
+ const errors = [];
554
+ for (const editor of editors) {
555
+ // Resolve through the platform table so $CODEX_HOME-style roots are honored.
556
+ let marker;
557
+ try {
558
+ marker = platformForEditor(editor).markerDir;
559
+ }
560
+ catch (err) {
561
+ // A hand-edited config entry with no editors.json row cannot be installed
562
+ // anywhere. Report it once here (the caller also drops it from the
563
+ // selection list) instead of aborting the whole init.
564
+ errors.push(`${editorDisplayName(editor.name)}: ${err.message}`);
565
+ continue;
566
+ }
567
+ if (!marker) {
568
+ status.set(editor.name, true);
569
+ }
570
+ else {
571
+ status.set(editor.name, await dirExists(marker));
572
+ }
573
+ }
574
+ return { status, errors };
575
+ }
576
+ /**
577
+ * SDK path variables `ht init` writes as real OS environment variables — the
578
+ * only place they are kept (there is no config file). PATH entries for
579
+ * node/java/hdc are not included here — those are documented as manual PATH
580
+ * setup. Empty values are never exported.
581
+ */
582
+ export const MACHINE_ENV_KEYS = ENV_KEYS;
583
+ /** Mask API-key values for display; show paths in full. */
584
+ function maskEnvValue(name, value) {
585
+ if (/_API_KEY$/.test(name) && value.length > 0) {
586
+ return value.length <= 8 ? '***' : `${value.slice(0, 4)}***${value.slice(-4)}`;
587
+ }
588
+ return value;
589
+ }
590
+ /**
591
+ * Show the resolved SDK values that would become machine environment
592
+ * variables, then ask Y/N before writing them (Windows: setx; macOS/Linux:
593
+ * shell rc block). Variables already present in the OS environment with the
594
+ * exact same value are skipped — they are neither shown nor re-written, and if
595
+ * nothing needs updating the prompt is skipped entirely. Non-interactive shells
596
+ * skip without changing anything. Re-throws ExitPromptError so the caller can
597
+ * abort init on Ctrl-C.
598
+ */
599
+ async function maybePersistMachineEnv(env) {
600
+ const allVars = MACHINE_ENV_KEYS.map((k) => [k, (env[k] ?? '').trim()]).filter(([, value]) => value.length > 0);
601
+ if (allVars.length === 0)
602
+ return;
603
+ // Skip variables already set in the OS environment with the same value — no
604
+ // need to re-write them or re-ask. process.env reflects the environment this
605
+ // process launched with, so a prior `ht init` (seen from a fresh terminal)
606
+ // already shows up here.
607
+ const sameValue = ([name, value]) => (process.env[name] ?? '').trim() === value;
608
+ const alreadySet = allVars.filter(sameValue);
609
+ const vars = allVars.filter((v) => !sameValue(v));
610
+ if (vars.length === 0) {
611
+ console.log('');
612
+ console.log(chalk.green(' + Machine environment variables already set with the current values — nothing to add.'));
613
+ return;
614
+ }
615
+ console.log('');
616
+ console.log(chalk.blue(' Add these to your machine environment variables? Skills and MCP tools read these from the OS environment at runtime.'));
617
+ for (const [name, value] of vars) {
618
+ console.log(` ${chalk.cyan(name)} = ${maskEnvValue(name, value)}`);
619
+ }
620
+ if (alreadySet.length > 0) {
621
+ console.log(chalk.gray(` (${alreadySet.length} already set with the same value — skipped: ${alreadySet
622
+ .map(([name]) => name)
623
+ .join(', ')})`));
624
+ }
625
+ let confirmed;
626
+ try {
627
+ const answers = await inquirer.prompt([
628
+ {
629
+ type: 'confirm',
630
+ name: 'persist',
631
+ message: 'Write these environment variables to this machine?',
632
+ default: true,
633
+ },
634
+ ]);
635
+ confirmed = answers.persist;
636
+ }
637
+ catch (err) {
638
+ if (isPromptAbort(err))
639
+ throw err;
640
+ console.log(chalk.yellow(' Non-interactive: skipped (set them manually if needed).'));
641
+ return;
642
+ }
643
+ if (!confirmed) {
644
+ console.log(chalk.yellow(' Skipped — no system environment variables were set.'));
645
+ console.log(chalk.gray(' Skills that build or check HarmonyOS code will not find the SDK automatically:\n' +
646
+ ' set these variables yourself, or re-run `ht init` and answer Y.'));
647
+ return;
648
+ }
649
+ // The environment is now the only store for these values. On macOS/Linux the
650
+ // managed rc block is replaced as a whole, so it must carry every value —
651
+ // writing only the changed ones would drop the unchanged ones from the block.
652
+ // Windows `setx` sets each name independently, so the changed ones suffice.
653
+ const note = await persistEnvVars(process.platform === 'win32' ? vars : allVars);
654
+ console.log(chalk.green(` + Environment variables ${note}`));
655
+ }
656
+ /**
657
+ * Run `git --version`. Returns the trimmed first output line on success (exit 0),
658
+ * or null when git is missing / exits non-zero. Used by `installGit` for
659
+ * idempotent detection before and after auto-provisioning.
660
+ */
661
+ function gitVersion() {
662
+ try {
663
+ const out = execFileSync('git', ['--version'], {
664
+ encoding: 'utf-8',
665
+ timeout: 15000,
666
+ stdio: ['ignore', 'pipe', 'ignore'],
667
+ shell: process.platform === 'win32',
668
+ });
669
+ return (out ?? '').split('\n').map((l) => l.trim()).filter(Boolean)[0] ?? '';
670
+ }
671
+ catch {
672
+ return null;
673
+ }
674
+ }
675
+ /**
676
+ * Git part of the Dependency Installation step — git is required for the
677
+ * diff-based agent precheck runs and generally assumed by npm and the skills.
678
+ * Idempotent: `git --version` returning normally skips the install. Per-OS auto
679
+ * provisioning:
680
+ * - Windows: `winget install --id Git.Git -e --source winget` when winget is
681
+ * on PATH; otherwise print the manual download URL.
682
+ * - macOS: `brew install git` when Homebrew is on PATH; otherwise offer to
683
+ * install Homebrew first via its official installer, then `brew install git`.
684
+ * MacPorts / `xcode-select --install` are shown as fallbacks.
685
+ * - Linux: print the common package-manager commands (apt / dnf / pacman)
686
+ * — auto-install would need sudo, which we don't want to grab silently.
687
+ * Never throws — failures are reported and `ht init` continues. The
688
+ * "Dependency Installation" section header is printed once by the caller.
689
+ */
690
+ async function installGit(offline) {
691
+ console.log(chalk.gray(' git'));
692
+ const existing = gitVersion();
693
+ if (existing !== null) {
694
+ console.log(chalk.green(` + git already installed (${existing || 'version unknown'}) — skipping.`));
695
+ return;
696
+ }
697
+ // Offline mode: winget/brew need the network — print the manual path instead.
698
+ if (offline) {
699
+ console.log(chalk.yellow(' ! git not found. Offline mode cannot auto-install it — use your offline medium:'));
700
+ console.log(chalk.gray(' Windows: offline Git for Windows installer — https://git-scm.com/download/win'));
701
+ console.log(chalk.gray(' macOS: xcode-select --install, or Homebrew from an offline mirror'));
702
+ console.log(chalk.gray(' Linux: distro package (apt/dnf/pacman) from an offline repo'));
703
+ console.log(chalk.gray(' Then re-run `ht init`.'));
704
+ return;
705
+ }
706
+ const platform = process.platform;
707
+ if (platform === 'win32') {
708
+ await installGitWindows();
709
+ return;
710
+ }
711
+ if (platform === 'darwin') {
712
+ await installGitMacOS();
713
+ return;
714
+ }
715
+ // Linux / other Unix: print instructions only.
716
+ console.log(chalk.yellow(' ! git not found. Install it with your distro package manager:'));
717
+ console.log(chalk.gray(' Debian/Ubuntu: sudo apt-get install -y git'));
718
+ console.log(chalk.gray(' Fedora/RHEL: sudo dnf install -y git'));
719
+ console.log(chalk.gray(' Arch: sudo pacman -S --noconfirm git'));
720
+ console.log(chalk.gray(' Docs: https://git-scm.com/download/linux'));
721
+ }
722
+ /** Windows branch of installGit — uses winget when available, prints download URL otherwise. */
723
+ async function installGitWindows() {
724
+ if (!whichSync('winget')) {
725
+ console.log(chalk.yellow(' ! git not found and winget is unavailable on this Windows host.'));
726
+ console.log(chalk.gray(' Install Git for Windows manually: https://git-scm.com/download/win'));
727
+ console.log(chalk.gray(' Then re-run `ht init`.'));
728
+ return;
729
+ }
730
+ const cmdText = 'winget install --id Git.Git -e --source winget';
731
+ let proceed = true;
732
+ try {
733
+ const answers = await inquirer.prompt([
734
+ {
735
+ type: 'confirm',
736
+ name: 'install',
737
+ message: `git not found. Install it now via winget?\n ${cmdText}`,
738
+ default: true,
739
+ },
740
+ ]);
741
+ proceed = answers.install;
742
+ }
743
+ catch (err) {
744
+ if (isPromptAbort(err))
745
+ abortInit();
746
+ console.log(chalk.yellow(' Non-interactive: proceeding with install.'));
747
+ }
748
+ if (!proceed) {
749
+ console.log(chalk.yellow(' Skipped — install later with:'));
750
+ console.log(chalk.gray(` ${cmdText}`));
751
+ return;
752
+ }
753
+ console.log(chalk.gray(` Running: ${cmdText} ...`));
754
+ try {
755
+ execFileSync('winget', ['install', '--id', 'Git.Git', '-e', '--source', 'winget'], { stdio: 'inherit', timeout: 10 * 60 * 1000, shell: true });
756
+ }
757
+ catch (err) {
758
+ console.log(chalk.red(` ! winget install failed: ${err.message}`));
759
+ console.log(chalk.gray(` Re-run manually: ${cmdText}`));
760
+ console.log(chalk.gray(' Or download the installer: https://git-scm.com/download/win'));
761
+ return;
762
+ }
763
+ const version = gitVersion();
764
+ if (version !== null) {
765
+ console.log(chalk.green(` + git installed & verified (${version || 'version unknown'}).`));
766
+ }
767
+ else {
768
+ console.log(chalk.yellow(' ! Installed, but `git --version` did not return successfully.'));
769
+ console.log(chalk.gray(' Open a new terminal (PATH refresh), then verify: git --version'));
770
+ }
771
+ }
772
+ /** macOS branch of installGit — prefers Homebrew, offers to install Homebrew first if missing. */
773
+ async function installGitMacOS() {
774
+ // Homebrew present → straight `brew install git`.
775
+ if (whichSync('brew')) {
776
+ await runBrewInstallGit();
777
+ return;
778
+ }
779
+ // No Homebrew: offer to install it via the official installer, then brew install git.
780
+ const brewInstallCmd = '/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"';
781
+ console.log(chalk.yellow(' ! git not found and Homebrew is unavailable on this macOS host.'));
782
+ console.log(chalk.gray(' HomeTrans can install Homebrew via the official installer, then run `brew install git`.'));
783
+ console.log(chalk.gray(` ${brewInstallCmd}`));
784
+ console.log(chalk.gray(' Alternatives:'));
785
+ console.log(chalk.gray(' MacPorts: sudo port install git (requires MacPorts already installed)'));
786
+ console.log(chalk.gray(' Xcode CLT: xcode-select --install (ships Apple\'s git build)'));
787
+ let proceed = true;
788
+ try {
789
+ const answers = await inquirer.prompt([
790
+ {
791
+ type: 'confirm',
792
+ name: 'install',
793
+ message: 'Install Homebrew now, then install git via brew?',
794
+ default: true,
795
+ },
796
+ ]);
797
+ proceed = answers.install;
798
+ }
799
+ catch (err) {
800
+ if (isPromptAbort(err))
801
+ abortInit();
802
+ console.log(chalk.yellow(' Non-interactive: proceeding with install.'));
803
+ }
804
+ if (!proceed) {
805
+ console.log(chalk.yellow(' Skipped — install git later using one of the options above.'));
806
+ return;
807
+ }
808
+ console.log(chalk.gray(` Running: ${brewInstallCmd} ...`));
809
+ try {
810
+ execFileSync('/bin/bash', ['-c', `$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)`], {
811
+ stdio: 'inherit',
812
+ timeout: 15 * 60 * 1000,
813
+ });
814
+ }
815
+ catch (err) {
816
+ console.log(chalk.red(` ! Homebrew install failed: ${err.message}`));
817
+ console.log(chalk.gray(' Fallback: xcode-select --install (ships Apple\'s git build)'));
818
+ return;
819
+ }
820
+ if (!whichSync('brew')) {
821
+ console.log(chalk.yellow(' ! Homebrew installed, but `brew` is not on PATH in this shell.'));
822
+ console.log(chalk.gray(' Open a new terminal and run: brew install git'));
823
+ return;
824
+ }
825
+ await runBrewInstallGit();
826
+ }
827
+ /** `brew install git` + verification helper, shared by both Homebrew branches on macOS. */
828
+ async function runBrewInstallGit() {
829
+ const cmdText = 'brew install git';
830
+ console.log(chalk.gray(` Running: ${cmdText} ...`));
831
+ try {
832
+ execFileSync('brew', ['install', 'git'], {
833
+ stdio: 'inherit',
834
+ timeout: 15 * 60 * 1000,
835
+ });
836
+ }
837
+ catch (err) {
838
+ console.log(chalk.red(` ! brew install git failed: ${err.message}`));
839
+ console.log(chalk.gray(' Fallback: xcode-select --install (ships Apple\'s git build)'));
840
+ return;
841
+ }
842
+ const version = gitVersion();
843
+ if (version !== null) {
844
+ console.log(chalk.green(` + git installed & verified (${version || 'version unknown'}).`));
845
+ }
846
+ else {
847
+ console.log(chalk.yellow(' ! Installed, but `git --version` did not return successfully.'));
848
+ console.log(chalk.gray(' Open a new terminal (PATH refresh), then verify: git --version'));
849
+ }
850
+ }
851
+ /**
852
+ * Global npm packages the skills need at runtime: CLI tools first, then the
853
+ * libraries reqgen resolves through its npm-linked node_modules.
854
+ *
855
+ * The tree-sitter pair is pinned as a coupled unit. reqgen's Model contracts
856
+ * hard-code exactly `web-tree-sitter@0.20.8` + `tree-sitter-wasms@0.1.13`
857
+ * (reqgen model/prepare.ts fingerprint + contracts.ts), and the pair only
858
+ * works together: tree-sitter-wasms@0.1.13 ships grammars in the old WASM
859
+ * dynamic-linking format that web-tree-sitter >= 0.26 cannot load
860
+ * (tree-sitter#5171), while web-tree-sitter 0.20.x supports parser ABI 13-14
861
+ * only. Never let either side float to latest independently.
862
+ *
863
+ * `homecheck` is a floor, not a pin: the required release (2.0.0-next.0, the
864
+ * one that renamed the `@arkui-reliability` rule set to
865
+ * `@arkui-semantic-correctness`) is published under the npm `next` tag while
866
+ * `latest` is still 1.0.5, so a bare `homecheck` would install the old one.
867
+ * `^2.0.0-next.0` is written out because a bare `^2.0.0` never matches a
868
+ * prerelease; an installed version at or above 2.0.0 is left untouched, so a
869
+ * later stable release is never downgraded.
870
+ */
871
+ const GLOBAL_NPM_PACKAGES = [
872
+ 'a2h-resource',
873
+ 'homegraph',
874
+ 'arkanalyzer',
875
+ 'homecheck@^2.0.0-next.0',
876
+ '@deveco/deveco-cli',
877
+ 'commander',
878
+ 'zod',
879
+ 'web-tree-sitter@0.20.8',
880
+ 'tree-sitter-wasms@0.1.13',
881
+ ];
882
+ /**
883
+ * reqgen's runtime dependencies. `ht init` links these from the global
884
+ * install into each installed copy's node_modules: bare-specifier ESM
885
+ * imports ignore NODE_PATH, so junctions/symlinks are the only bridge that
886
+ * makes the copied scripts resolve the GLOBAL packages (homegraph's version
887
+ * therefore follows the global install, where the tree-sitter pair is pinned
888
+ * to web-tree-sitter@0.20.8 + tree-sitter-wasms@0.1.13).
889
+ */
890
+ const REQGEN_LINKED_PACKAGES = [
891
+ 'commander',
892
+ 'homegraph',
893
+ 'tree-sitter-wasms',
894
+ 'web-tree-sitter',
895
+ 'zod',
896
+ ];
897
+ /** Absolute path of the global node_modules dir, or null when npm is unusable. */
898
+ function npmGlobalRoot() {
899
+ try {
900
+ const out = execFileSync('npm', ['root', '-g'], {
901
+ encoding: 'utf-8',
902
+ timeout: 30_000,
903
+ shell: process.platform === 'win32',
904
+ stdio: ['ignore', 'pipe', 'ignore'],
905
+ });
906
+ const line = out.split('\n').map((l) => l.trim()).filter(Boolean)[0];
907
+ return line || null;
908
+ }
909
+ catch {
910
+ return null;
911
+ }
912
+ }
913
+ /**
914
+ * The effective npm registry this machine's npm resolves packages from
915
+ * (`npm config get registry`), or null when npm is unusable. npm's cache is
916
+ * keyed by exact request URL, so offline installs only hit entries seeded
917
+ * from the SAME registry the consuming machine is configured with.
918
+ */
919
+ function npmConfigRegistry() {
920
+ try {
921
+ const out = execFileSync('npm', ['config', 'get', 'registry'], {
922
+ encoding: 'utf-8',
923
+ timeout: 30_000,
924
+ shell: process.platform === 'win32',
925
+ stdio: ['ignore', 'pipe', 'ignore'],
926
+ });
927
+ const line = out.split('\n').map((l) => l.trim()).filter(Boolean)[0];
928
+ return line || null;
929
+ }
930
+ catch {
931
+ return null;
932
+ }
933
+ }
934
+ /** Split an npm spec (`pkg`, `pkg@1.2.3`, `@scope/pkg`, `@scope/pkg@1.2.3`)
935
+ * into its name and optional explicit version. */
936
+ function parseNpmSpec(spec) {
937
+ const at = spec.startsWith('@') ? spec.indexOf('@', 1) : spec.indexOf('@');
938
+ return at === -1
939
+ ? { name: spec }
940
+ : { name: spec.slice(0, at), version: spec.slice(at + 1) };
941
+ }
942
+ /** Is a spec's version part an exact version (`1.2.3`, prerelease/build suffix allowed)? */
943
+ function isExactNpmVersion(version) {
944
+ return /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version);
945
+ }
946
+ /**
947
+ * Does an already-installed version satisfy a spec's version part?
948
+ *
949
+ * An exact version is a pin — the installed version must equal it (the
950
+ * tree-sitter pair relies on this). A range (`^`/`~`/`>=`…) is a floor —
951
+ * anything at or above its numeric base counts, so `homecheck@^2.0.0-next.0` is
952
+ * satisfied by 2.0.0-next.0 and by a later stable 2.x, and stays installed. A
953
+ * dist-tag (`next`, `latest`) cannot be resolved without the registry, so an
954
+ * installed package is accepted as-is rather than reinstalled on every run.
955
+ */
956
+ export function npmSpecSatisfied(installed, version) {
957
+ if (isExactNpmVersion(version))
958
+ return installed === version;
959
+ // A range operator in front of a dotted version is a floor.
960
+ const floorText = version.replace(/^[\s^~<>=v]+/, '');
961
+ if (!/^\d+\.\d+/.test(floorText))
962
+ return true;
963
+ const floor = parseVersion(floorText);
964
+ const have = parseVersion(installed);
965
+ if (!floor || !have)
966
+ return true;
967
+ return cmpVersion(have, floor) >= 0;
968
+ }
969
+ /** Installed version of a global npm package, or null when absent/unreadable. */
970
+ async function installedGlobalVersion(root, name) {
971
+ try {
972
+ const raw = await fs.readFile(path.join(root, name, 'package.json'), 'utf-8');
973
+ const version = JSON.parse(raw).version;
974
+ return typeof version === 'string' && version ? version : null;
975
+ }
976
+ catch {
977
+ return null;
978
+ }
979
+ }
980
+ /**
981
+ * Map a package spec to its pinned spec from the bundle manifest
982
+ * (`homegraph` → `homegraph@<version resolved at bundle time>`), so offline
983
+ * installs reproduce the exact versions the cache was seeded with. Falls back
984
+ * to the incoming spec. A spec pinned to an exact version (the tree-sitter pair
985
+ * in GLOBAL_NPM_PACKAGES) is authoritative and passes through unchanged; a
986
+ * range/tag spec (homecheck's `^2.0.0-next.0`) is a requirement, so the
987
+ * bundle's resolved pin wins.
988
+ */
989
+ function pinnedNpmSpec(bundle, pkg) {
990
+ const parsed = parseNpmSpec(pkg);
991
+ if (parsed.version && isExactNpmVersion(parsed.version))
992
+ return pkg;
993
+ const hit = bundle.manifest.npmPackages.find((spec) => parseNpmSpec(spec).name === parsed.name);
994
+ return hit ?? pkg;
995
+ }
996
+ /**
997
+ * Global npm part of the Dependency Installation step. Idempotent: every
998
+ * package already present at the pinned version in `npm root -g` is skipped;
999
+ * missing or version-mismatched packages are passed to one `npm install -g`
1000
+ * (pinned specs reinstall their exact version). With a bundle, installs run
1001
+ * strictly offline against the bundle's seeded cache using manifest-pinned
1002
+ * versions. Never throws — failures print the manual command and `ht init`
1003
+ * continues.
1004
+ */
1005
+ async function installGlobalNpmClis(bundle) {
1006
+ console.log(chalk.gray(bundle
1007
+ ? ' npm globals — offline (from bundle cache)'
1008
+ : ' npm globals (homegraph, arkanalyzer, homecheck, a2h-resource, devecocli, reqgen libs)'));
1009
+ const root = npmGlobalRoot();
1010
+ if (!root) {
1011
+ console.log(chalk.yellow(' ! npm not usable (`npm root -g` failed). Install manually:'));
1012
+ console.log(chalk.gray(` npm install -g ${GLOBAL_NPM_PACKAGES.join(' ')}`));
1013
+ return;
1014
+ }
1015
+ const missing = [];
1016
+ for (const spec of GLOBAL_NPM_PACKAGES) {
1017
+ const { name, version } = parseNpmSpec(spec);
1018
+ const installed = await installedGlobalVersion(root, name);
1019
+ if (installed === null) {
1020
+ missing.push(spec);
1021
+ continue;
1022
+ }
1023
+ // An exact spec must match exactly: an existing-but-different global
1024
+ // version is precisely the silent incompatible pair that pin prevents. A
1025
+ // range spec is a floor (see npmSpecSatisfied).
1026
+ if (version && !npmSpecSatisfied(installed, version)) {
1027
+ console.log(chalk.yellow(` ! ${name}@${installed} is installed but ${spec} is required — reinstalling.`));
1028
+ missing.push(spec);
1029
+ }
1030
+ }
1031
+ if (missing.length === 0) {
1032
+ console.log(chalk.green(' + npm global packages already installed — skipping.'));
1033
+ return;
1034
+ }
1035
+ if (bundle) {
1036
+ const specs = missing.map((p) => pinnedNpmSpec(bundle, p));
1037
+ const args = [
1038
+ 'install',
1039
+ '-g',
1040
+ '--offline',
1041
+ '--no-audit',
1042
+ '--no-fund',
1043
+ '--cache',
1044
+ shellArg(bundle.npmCacheDir),
1045
+ ...specs,
1046
+ ];
1047
+ const cmdText = `npm ${args.join(' ')}`;
1048
+ console.log(chalk.gray(` Running: ${cmdText} ...`));
1049
+ const r = spawnSync('npm', args, {
1050
+ stdio: 'inherit',
1051
+ shell: process.platform === 'win32',
1052
+ timeout: 20 * 60 * 1000,
1053
+ });
1054
+ if (r.status !== 0) {
1055
+ console.log(chalk.yellow(' ! offline npm install failed — the bundle cache may be incomplete, seeded from a different npm registry, or predate the accept-variant fix (caches seeded by npm ≥ 10.8 do not serve npm ≤ 10.7).'));
1056
+ console.log(chalk.gray(' Check `npm config get registry` against the registry recorded in the bundle\'s manifest.json, and `npm -v` against the creating machine\'s npm; or recreate the bundle: ht offline-bundle <dir>'));
1057
+ return;
1058
+ }
1059
+ console.log(chalk.green(` + installed ${missing.length} npm package(s) from the offline bundle.`));
1060
+ return;
1061
+ }
1062
+ const cmdText = `npm install -g ${missing.join(' ')}`;
1063
+ console.log(chalk.gray(` Running: ${cmdText} ...`));
1064
+ const r = spawnSync('npm', ['install', '-g', ...missing], {
1065
+ stdio: 'inherit',
1066
+ shell: process.platform === 'win32',
1067
+ timeout: 10 * 60 * 1000,
1068
+ });
1069
+ if (r.status !== 0) {
1070
+ console.log(chalk.yellow(' ! npm install -g failed. Install manually:'));
1071
+ console.log(chalk.gray(` ${cmdText}`));
1072
+ return;
1073
+ }
1074
+ console.log(chalk.green(` + installed ${missing.length} npm package(s).`));
1075
+ }
1076
+ /**
1077
+ * Link the reqgen runtime dependencies from the global install into the
1078
+ * installed skill copy's node_modules (`npm link` creates junctions/symlinks
1079
+ * there), so the copy's ESM imports resolve to the global packages. Guarded
1080
+ * by a stamp file listing the linked set: unchanged copies skip, and a
1081
+ * changed package list (or a stale node_modules from the old in-skill
1082
+ * `npm ci`) triggers a clean re-link. Never throws.
1083
+ */
1084
+ async function linkReqgenGlobalDeps(skillsDir, editorName) {
1085
+ const reqgenDir = path.join(skillsDir, 'a2h-spec-generate', 'scripts', 'reqgen');
1086
+ if (!(await fileExists(path.join(reqgenDir, 'package.json'))))
1087
+ return;
1088
+ const nodeModules = path.join(reqgenDir, 'node_modules');
1089
+ const stampPath = path.join(nodeModules, '.hometrans-npm-link');
1090
+ const stampBody = REQGEN_LINKED_PACKAGES.join('\n') + '\n';
1091
+ try {
1092
+ const existing = await fs.readFile(stampPath, 'utf-8');
1093
+ if (existing === stampBody)
1094
+ return; // already linked with this exact set
1095
+ }
1096
+ catch {
1097
+ // no stamp → first run, or a stale non-linked node_modules → re-link
1098
+ }
1099
+ // A pre-existing node_modules (e.g. from the old in-skill `npm ci`) would
1100
+ // keep shadowing the links with local package copies; remove it first.
1101
+ if (await dirExists(nodeModules)) {
1102
+ await fs.rm(nodeModules, { recursive: true, force: true });
1103
+ }
1104
+ const cmdText = `npm link ${REQGEN_LINKED_PACKAGES.join(' ')}`;
1105
+ console.log(chalk.gray(` reqgen deps (${editorName}): ${cmdText}`));
1106
+ const r = spawnSync('npm', ['link', ...REQGEN_LINKED_PACKAGES], {
1107
+ stdio: 'inherit',
1108
+ shell: process.platform === 'win32',
1109
+ timeout: 10 * 60 * 1000,
1110
+ cwd: reqgenDir,
1111
+ });
1112
+ if (r.status !== 0) {
1113
+ console.log(chalk.yellow(` ! reqgen dependency link failed for ${editorName}. Manual:`));
1114
+ console.log(chalk.gray(` cd "${reqgenDir}" && ${cmdText}`));
1115
+ return;
1116
+ }
1117
+ await fs.mkdir(nodeModules, { recursive: true });
1118
+ await fs.writeFile(stampPath, stampBody, 'utf-8');
1119
+ console.log(chalk.green(` + reqgen deps linked to global packages (${editorName}).`));
1120
+ }
1121
+ /**
1122
+ * The npm packages seeded into every bundle's cache — the runtime set only.
1123
+ * hometrans itself is NOT fetched from the registry: the bundle carries the
1124
+ * LOCAL build (see packLocalHometransAll) so an offline machine bootstraps the
1125
+ * exact feature set that created the bundle (e.g. `--offline-bundle` itself).
1126
+ *
1127
+ * Every skill ships Node-only scripts, so npm is the whole dependency story:
1128
+ * there is no Python/pip half of the bundle any more.
1129
+ */
1130
+ const OFFLINE_NPM_SEED_SET = [...GLOBAL_NPM_PACKAGES];
1131
+ /** Registry fallback for hometrans when the local `npm pack` fails. */
1132
+ const HOMETRANS_PACKAGE = '@buaa_smat/hometrans';
1133
+ /**
1134
+ * (os, cpu, libc) combos whose platform-native binaries are merged into the
1135
+ * packed tarball's bundled node_modules. The staging install only resolves
1136
+ * binaries for the CREATING machine (e.g. @img/sharp-win32-x64 on Windows),
1137
+ * which left `require('sharp')` broken on offline Macs / Linux. Covers the
1138
+ * realistic target set (HarmonyOS dev machines: Windows + macOS, plus glibc
1139
+ * Linux); extend with musl/other combos if a bundled package ever needs them.
1140
+ */
1141
+ const BUNDLED_NATIVE_PLATFORMS = [
1142
+ { os: 'win32', cpu: 'x64' },
1143
+ { os: 'darwin', cpu: 'arm64' },
1144
+ { os: 'darwin', cpu: 'x64' },
1145
+ { os: 'linux', cpu: 'x64', libc: 'glibc' },
1146
+ { os: 'linux', cpu: 'arm64', libc: 'glibc' },
1147
+ ];
1148
+ /**
1149
+ * Name shape of platform-native binary packages — the optional dependencies a
1150
+ * native host resolves per platform (sharp → `@img/sharp-darwin-arm64`,
1151
+ * esbuild → `@esbuild/win32-x64`, rollup → `@rollup/rollup-darwin-x64`, ...).
1152
+ */
1153
+ const PLATFORM_BINARY_NAME = /^(@[^/]+\/)?[a-z0-9._-]*?(win32|darwin|linux|android|freebsd|openbsd|sunos|aix)-(ia32|x86|x64|arm64|armv7|arm|riscv64|ppc64|s390x|loong64|mips64)(-(gnu|musl|msvc|gnueabihf))?$/;
1154
+ /**
1155
+ * Top-level packages in `nodeModulesDir` that declare platform-native
1156
+ * optional dependencies (e.g. sharp → @img/sharp-*). Defensively per-entry:
1157
+ * an unreadable package is skipped rather than failing the scan.
1158
+ */
1159
+ function findNativeBinaryHosts(nodeModulesDir) {
1160
+ const hosts = [];
1161
+ const consider = (pkgDirPath, name) => {
1162
+ let pkgJson;
1163
+ try {
1164
+ pkgJson = JSON.parse(fsSync.readFileSync(path.join(pkgDirPath, 'package.json'), 'utf-8'));
1165
+ }
1166
+ catch {
1167
+ return;
1168
+ }
1169
+ const hasBinaryDeps = Object.keys(pkgJson.optionalDependencies ?? {}).some((dep) => PLATFORM_BINARY_NAME.test(dep));
1170
+ if (hasBinaryDeps && typeof pkgJson.version === 'string') {
1171
+ hosts.push({ name, version: pkgJson.version });
1172
+ }
1173
+ };
1174
+ let entries = [];
1175
+ try {
1176
+ entries = fsSync.readdirSync(nodeModulesDir);
1177
+ }
1178
+ catch {
1179
+ return hosts;
1180
+ }
1181
+ for (const entry of entries) {
1182
+ let pkgPath = path.join(nodeModulesDir, entry);
1183
+ try {
1184
+ if (!fsSync.statSync(pkgPath).isDirectory())
1185
+ continue;
1186
+ if (entry.startsWith('@')) {
1187
+ for (const child of fsSync.readdirSync(pkgPath)) {
1188
+ const childPath = path.join(pkgPath, child);
1189
+ if (fsSync.statSync(childPath).isDirectory())
1190
+ consider(childPath, `${entry}/${child}`);
1191
+ }
1192
+ }
1193
+ else {
1194
+ consider(pkgPath, entry);
1195
+ }
1196
+ }
1197
+ catch {
1198
+ continue;
1199
+ }
1200
+ }
1201
+ return hosts;
1202
+ }
1203
+ /**
1204
+ * Package names reachable from `roots` through dependencies/optionalDependencies
1205
+ * edges of the installed packages in `nodeModulesDir` — the set npm pack will
1206
+ * actually bundle. dev/peer edges are not followed: packages reached only
1207
+ * through them sit in node_modules but are not carried by the tarball, so
1208
+ * their native binaries would be merged in vain.
1209
+ */
1210
+ function bundledClosureNames(nodeModulesDir, roots) {
1211
+ const seen = new Set();
1212
+ const readPkg = (name) => {
1213
+ try {
1214
+ const raw = fsSync.readFileSync(path.join(nodeModulesDir, ...name.split('/'), 'package.json'), 'utf-8');
1215
+ return JSON.parse(raw);
1216
+ }
1217
+ catch {
1218
+ return null;
1219
+ }
1220
+ };
1221
+ const queue = [...roots];
1222
+ while (queue.length > 0) {
1223
+ const name = queue.pop();
1224
+ if (seen.has(name))
1225
+ continue;
1226
+ seen.add(name);
1227
+ const pkg = readPkg(name);
1228
+ if (!pkg)
1229
+ continue;
1230
+ queue.push(...Object.keys(pkg.dependencies ?? {}));
1231
+ queue.push(...Object.keys(pkg.optionalDependencies ?? {}));
1232
+ }
1233
+ return seen;
1234
+ }
1235
+ /**
1236
+ * Cross-platform half of the bundled-native-binaries fix: for every combo in
1237
+ * BUNDLED_NATIVE_PLATFORMS and every host package found in the bundled tree,
1238
+ * a scratch install with npm's --os/--cpu/--libc overrides resolves that
1239
+ * platform's binary packages; ones missing from the tree are copied in, so
1240
+ * the tarball works on every target platform instead of only the creating
1241
+ * machine's. Existing dirs always win (the creating machine's own resolution
1242
+ * is authoritative); idempotent across re-runs. Never throws — a combo that
1243
+ * fails only warns, because the pack itself can proceed without it.
1244
+ */
1245
+ /** Platform map key for a combo (`win32-x64`, `linux-arm64`, ...). */
1246
+ function platformComboKey(combo) {
1247
+ return `${combo.os}-${combo.cpu}`;
1248
+ }
1249
+ /**
1250
+ * Top-level packages in `nodeModulesDir` whose NAME marks a platform-native
1251
+ * binary package (see PLATFORM_BINARY_NAME) — e.g. @img/sharp-darwin-arm64,
1252
+ * @rollup/rollup-linux-x64-gnu. Defensively per-entry: unreadable entries are
1253
+ * skipped.
1254
+ */
1255
+ function platformBinaryPackageNames(nodeModulesDir) {
1256
+ const names = [];
1257
+ let entries = [];
1258
+ try {
1259
+ entries = fsSync.readdirSync(nodeModulesDir);
1260
+ }
1261
+ catch {
1262
+ return names;
1263
+ }
1264
+ for (const entry of entries) {
1265
+ try {
1266
+ const pkgPath = path.join(nodeModulesDir, entry);
1267
+ if (!fsSync.statSync(pkgPath).isDirectory())
1268
+ continue;
1269
+ if (entry.startsWith('@')) {
1270
+ for (const child of fsSync.readdirSync(pkgPath)) {
1271
+ if (PLATFORM_BINARY_NAME.test(`${entry}/${child}`))
1272
+ names.push(`${entry}/${child}`);
1273
+ }
1274
+ }
1275
+ else if (PLATFORM_BINARY_NAME.test(entry)) {
1276
+ names.push(entry);
1277
+ }
1278
+ }
1279
+ catch {
1280
+ continue;
1281
+ }
1282
+ }
1283
+ return names;
1284
+ }
1285
+ /**
1286
+ * Remove every platform-binary package dir from `nodeModulesDir` and return
1287
+ * the removed names — the per-platform pack loop keeps the staging tree
1288
+ * NEUTRAL between rounds: acquire one combo's binaries, pack, strip them
1289
+ * again. Bundling two platforms' binaries in one tarball is not an option:
1290
+ * npm rejects the install of every binary foreign to the installing machine
1291
+ * with EBADPLATFORM.
1292
+ */
1293
+ function removePlatformBinaryPackages(nodeModulesDir) {
1294
+ const removed = platformBinaryPackageNames(nodeModulesDir);
1295
+ for (const name of removed) {
1296
+ fsSync.rmSync(path.join(nodeModulesDir, ...name.split('/')), { recursive: true, force: true });
1297
+ }
1298
+ return removed;
1299
+ }
1300
+ /**
1301
+ * Copy the platform-native binaries ONE combo needs into the staging
1302
+ * `nodeModulesDir`. A scratch `npm install --os/--cpu/--libc` of every
1303
+ * native-binary host resolves that combo's binary set — companions included,
1304
+ * no name parsing involved (sharp → @img/sharp-darwin-arm64 AND
1305
+ * @img/sharp-libvips-darwin-arm64) — and everything missing from the staging
1306
+ * tree is copied in. `--libc` matters on non-linux creating machines: without
1307
+ * it npm cannot detect a libc family and rejects every libc-gated linux
1308
+ * binary. Returns the copied package names (empty on failure — a failed
1309
+ * combo only warns; the pack can proceed without its binaries). Never throws.
1310
+ */
1311
+ function acquireComboBinaries(nodeModulesDir, hosts, combo, npmRun) {
1312
+ const copied = [];
1313
+ const scratch = fsSync.mkdtempSync(path.join(os.tmpdir(), 'hometrans-native-'));
1314
+ try {
1315
+ fsSync.writeFileSync(path.join(scratch, 'package.json'), JSON.stringify({ name: 'hometrans-native-bins', private: true, version: '0.0.0' }, null, 2), 'utf-8');
1316
+ for (const host of hosts) {
1317
+ const args = [
1318
+ 'install',
1319
+ '--no-save',
1320
+ '--ignore-scripts',
1321
+ '--no-audit',
1322
+ '--no-fund',
1323
+ '--os',
1324
+ combo.os,
1325
+ '--cpu',
1326
+ combo.cpu,
1327
+ ...(combo.libc ? ['--libc', combo.libc] : []),
1328
+ `${host.name}@${host.version}`,
1329
+ ];
1330
+ const r = npmRun(args, scratch);
1331
+ if (r.status !== 0) {
1332
+ console.log(chalk.yellow(` ! native binaries for ${host.name} @ ${platformComboKey(combo)} not bundled (install failed).`));
1333
+ continue;
1334
+ }
1335
+ const scratchNm = path.join(scratch, 'node_modules');
1336
+ let entries = [];
1337
+ try {
1338
+ entries = fsSync.readdirSync(scratchNm);
1339
+ }
1340
+ catch {
1341
+ continue;
1342
+ }
1343
+ for (const entry of entries) {
1344
+ try {
1345
+ const src = path.join(scratchNm, entry);
1346
+ if (!fsSync.statSync(src).isDirectory())
1347
+ continue;
1348
+ const merge = (srcDir, rel) => {
1349
+ const dest = path.join(nodeModulesDir, rel);
1350
+ if (fsSync.existsSync(dest))
1351
+ return;
1352
+ fsSync.cpSync(srcDir, dest, { recursive: true });
1353
+ copied.push(rel);
1354
+ };
1355
+ if (entry.startsWith('@')) {
1356
+ for (const child of fsSync.readdirSync(src)) {
1357
+ const childSrc = path.join(src, child);
1358
+ if (fsSync.statSync(childSrc).isDirectory())
1359
+ merge(childSrc, `${entry}/${child}`);
1360
+ }
1361
+ }
1362
+ else {
1363
+ merge(src, entry);
1364
+ }
1365
+ }
1366
+ catch {
1367
+ continue;
1368
+ }
1369
+ }
1370
+ }
1371
+ }
1372
+ finally {
1373
+ fsSync.rmSync(scratch, { recursive: true, force: true });
1374
+ }
1375
+ return copied;
1376
+ }
1377
+ /**
1378
+ * `npm pack` the hometrans package this CLI runs from into `bundleRoot` as a
1379
+ * SET of self-contained per-platform tarballs — one per combo in
1380
+ * BUNDLED_NATIVE_PLATFORMS (win32-x64, darwin-arm64, darwin-x64, linux-x64
1381
+ * glibc, linux-arm64 glibc). Returns the `<os>-<cpu>` → filename map (e.g.
1382
+ * `darwin-arm64` → `buaa_smat-hometrans-<version>-darwin-arm64.tgz`), or null
1383
+ * on failure — in which case the bundle falls back to registry hometrans
1384
+ * (printed as a warning).
1385
+ *
1386
+ * `file:` dependencies cannot be resolved when a package is installed
1387
+ * FROM A TARBALL — npm opens the file: path before extracting. The published
1388
+ * hometrans avoids this by rewriting the dep to a registry version at publish
1389
+ * time; we cannot (the local tgz may be newer). So the raw pack is re-packed
1390
+ * through a staging copy where EVERY runtime dependency is pre-installed into
1391
+ * node_modules and moved to `bundleDependencies` (file: deps additionally get
1392
+ * their spec rewritten to the local version, making it inert): the tarball
1393
+ * carries its whole runtime closure, and installs from it never touch the
1394
+ * registry — no packuments, no cache, any npm version.
1395
+ *
1396
+ * Native binaries are split PER PLATFORM only when the runtime closure
1397
+ * actually resolves them: npm hard-fails an install (EBADPLATFORM) whose
1398
+ * bundled node_modules contains binaries built for another os/cpu, so a single
1399
+ * tarball cannot serve every platform in that case. Today the closure is plain
1400
+ * JS/wasm, so ONE cross-platform tarball is packed and every `<os>-<cpu>` key
1401
+ * in the manifest points at it; if a native-binary host appears again, the
1402
+ * staging tree is kept NEUTRAL between rounds (for each combo the right
1403
+ * binaries are merged in via a scratch `npm install --os/--cpu/--libc`, the
1404
+ * tarball is packed, and the binaries are stripped again) and every combo is
1405
+ * packed as `buaa_smat-hometrans-<version>-<os>-<cpu>.tgz` — uniform
1406
+ * platform-suffixed naming. The creating machine's combo is packed first (a
1407
+ * partially successful run then still serves the machine that built the
1408
+ * bundle, and its entry doubles as the back-compat single-tarball
1409
+ * `hometransTarball` manifest field).
1410
+ */
1411
+ export function packLocalHometransAll(bundleRoot) {
1412
+ const repoRoot = path.resolve(__dirname, '..', '..');
1413
+ const npmRun = (args, cwd) => spawnSync('npm', args, {
1414
+ encoding: 'utf-8',
1415
+ shell: process.platform === 'win32',
1416
+ timeout: 20 * 60 * 1000,
1417
+ cwd,
1418
+ });
1419
+ const tgzFromStdout = (out) => out.split('\n').map((l) => l.trim()).filter((l) => l.endsWith('.tgz')).pop() ?? null;
1420
+ const staging = fsSync.mkdtempSync(path.join(os.tmpdir(), 'hometrans-pack-'));
1421
+ try {
1422
+ // 1. Raw pack from the repo (runs `prepare` → build; honors the files field).
1423
+ const raw = npmRun(['pack', '--pack-destination', shellArg(staging)], repoRoot);
1424
+ if (raw.status !== 0)
1425
+ return null;
1426
+ const rawName = tgzFromStdout(raw.stdout || '');
1427
+ if (!rawName)
1428
+ return null;
1429
+ // 2. Extract into a staging package dir.
1430
+ const pkgDir = path.join(staging, 'pkg');
1431
+ fsSync.mkdirSync(pkgDir, { recursive: true });
1432
+ const untar = spawnSync('tar', ['--strip-components=1', '-xf', path.join(staging, rawName), '-C', pkgDir], { timeout: 5 * 60 * 1000 });
1433
+ if (untar.status !== 0)
1434
+ return null;
1435
+ // 3. Find the file: dependencies declared by the package.
1436
+ const pkgJsonPath = path.join(pkgDir, 'package.json');
1437
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1438
+ const pkgJson = JSON.parse(fsSync.readFileSync(pkgJsonPath, 'utf-8'));
1439
+ const fileDeps = Object.entries(pkgJson.dependencies ?? {}).filter(([, spec]) => spec.startsWith('file:'));
1440
+ if (fileDeps.length > 0) {
1441
+ // 4. Install each file: dep (with its full dependency closure) into the
1442
+ // staging node_modules, then rewrite its spec to the LOCAL version
1443
+ // (e.g. "file:tools/.../pkg-1.2.3.tgz" → "1.2.3") and mark
1444
+ // it bundled. npm pack only bundles deps that stay in `dependencies`;
1445
+ // bundled deps are extracted from the tarball at install time and
1446
+ // never resolved from a registry, so the rewritten spec is inert.
1447
+ // `--ignore-scripts` — we only need the files; `--no-save` keeps the
1448
+ // rewritten manifest authoritative.
1449
+ for (const [name, spec] of fileDeps) {
1450
+ const inst = npmRun(['install', '--no-save', '--ignore-scripts', '--no-audit', '--no-fund', spec], pkgDir);
1451
+ if (inst.status !== 0)
1452
+ return null;
1453
+ const installedPkgPath = path.join(pkgDir, 'node_modules', ...name.split('/'), 'package.json');
1454
+ const installed = JSON.parse(fsSync.readFileSync(installedPkgPath, 'utf-8'));
1455
+ if (!installed.version)
1456
+ return null;
1457
+ pkgJson.dependencies[name] = installed.version;
1458
+ delete pkgJson.bundleDependencies;
1459
+ }
1460
+ }
1461
+ // 5. Install the FULL runtime closure (registry deps like chalk/commander/
1462
+ // figlet/inquirer land in node_modules next to the file: dep trees;
1463
+ // already-satisfied deps are kept in place without a fetch) and mark
1464
+ // every runtime dependency bundled, so the packed tarball installs
1465
+ // offline with zero registry lookups.
1466
+ const inst = npmRun(['install', '--omit=dev', '--no-save', '--ignore-scripts', '--no-audit', '--no-fund'], pkgDir);
1467
+ if (inst.status !== 0)
1468
+ return null;
1469
+ pkgJson.bundledDependencies = [
1470
+ ...new Set([...(pkgJson.bundledDependencies ?? []), ...Object.keys(pkgJson.dependencies ?? {})]),
1471
+ ];
1472
+ delete pkgJson.bundleDependencies;
1473
+ fsSync.rmSync(path.join(pkgDir, 'package-lock.json'), { force: true });
1474
+ // 6. Strip lifecycle scripts — `prepare` runs scripts/build.js, which the
1475
+ // files field excludes from the pack; dist/ is already built.
1476
+ pkgJson.scripts = {};
1477
+ fsSync.writeFileSync(pkgJsonPath, JSON.stringify(pkgJson, null, 2), 'utf-8');
1478
+ // 7. Per-platform packs. Neutralize the tree first (the staging install
1479
+ // resolved only the creating machine's binaries); every combo — the
1480
+ // creating machine's included — then acquires its binary set the same
1481
+ // way, packs, and strips it again.
1482
+ const nodeModulesDir = path.join(pkgDir, 'node_modules');
1483
+ const bundledRoots = pkgJson.bundledDependencies ?? [];
1484
+ const hosts = findNativeBinaryHosts(nodeModulesDir).filter((h) => bundledClosureNames(nodeModulesDir, bundledRoots).has(h.name));
1485
+ removePlatformBinaryPackages(nodeModulesDir);
1486
+ const stem = `${(pkgJson.name ?? 'hometrans').replace('@', '').replace('/', '-')}-${pkgJson.version ?? '0.0.0'}`;
1487
+ const creatingCombo = BUNDLED_NATIVE_PLATFORMS.find((c) => c.os === process.platform && c.cpu === process.arch && (!c.libc || c.libc === 'glibc'));
1488
+ const combos = creatingCombo
1489
+ ? [creatingCombo, ...BUNDLED_NATIVE_PLATFORMS.filter((c) => c !== creatingCombo)]
1490
+ : [...BUNDLED_NATIVE_PLATFORMS];
1491
+ const tarballs = {};
1492
+ const packInto = (destName) => {
1493
+ const tmpPacks = path.join(staging, 'packs');
1494
+ fsSync.mkdirSync(tmpPacks, { recursive: true });
1495
+ const final = npmRun(['pack', '--pack-destination', shellArg(tmpPacks)], pkgDir);
1496
+ if (final.status !== 0)
1497
+ return false;
1498
+ const natural = tgzFromStdout(final.stdout || '');
1499
+ if (!natural)
1500
+ return false;
1501
+ const dest = path.join(bundleRoot, destName);
1502
+ fsSync.rmSync(dest, { force: true });
1503
+ fsSync.cpSync(path.join(tmpPacks, natural), dest);
1504
+ return true;
1505
+ };
1506
+ // No bundled package resolves platform-native binaries (every runtime dep
1507
+ // is plain JS or wasm), so the tarball is byte-identical for every target:
1508
+ // pack it ONCE and point every platform key at that one file. The lookup
1509
+ // map keeps its shape, so the bootstrap scripts and `ht init
1510
+ // --offline-bundle` need no special case; only the bundle shrinks (one
1511
+ // ~25 MB file instead of five) and the four extra pack rounds disappear.
1512
+ // As soon as a runtime dependency ships native optional deps again,
1513
+ // `hosts` is non-empty and the per-platform split below takes over.
1514
+ if (hosts.length === 0) {
1515
+ const destName = `${stem}.tgz`;
1516
+ if (!packInto(destName))
1517
+ return null;
1518
+ for (const combo of BUNDLED_NATIVE_PLATFORMS) {
1519
+ tarballs[platformComboKey(combo)] = destName;
1520
+ }
1521
+ console.log(chalk.gray(` + packed local hometrans ${destName} (one cross-platform tarball — no native deps)`));
1522
+ return tarballs;
1523
+ }
1524
+ for (const combo of combos) {
1525
+ const key = platformComboKey(combo);
1526
+ try {
1527
+ acquireComboBinaries(nodeModulesDir, hosts, combo, npmRun);
1528
+ const destName = `${stem}-${key}.tgz`;
1529
+ if (!packInto(destName)) {
1530
+ console.log(chalk.yellow(` ! npm pack for ${key} failed — that platform's tarball is not bundled.`));
1531
+ continue;
1532
+ }
1533
+ tarballs[key] = destName;
1534
+ console.log(chalk.gray(` + packed local hometrans ${destName} (${key})`));
1535
+ }
1536
+ finally {
1537
+ removePlatformBinaryPackages(nodeModulesDir);
1538
+ }
1539
+ }
1540
+ return Object.keys(tarballs).length > 0 ? tarballs : null;
1541
+ }
1542
+ catch {
1543
+ return null;
1544
+ }
1545
+ finally {
1546
+ fsSync.rmSync(staging, { recursive: true, force: true });
1547
+ }
1548
+ }
1549
+ /**
1550
+ * Validate and load a bundle produced by `ht offline-bundle`. Throws a plain
1551
+ * Error with an actionable message when the directory is not a usable bundle.
1552
+ */
1553
+ export async function loadOfflineBundle(dir) {
1554
+ const abs = path.resolve(dir);
1555
+ const manifestPath = path.join(abs, 'manifest.json');
1556
+ let raw;
1557
+ try {
1558
+ raw = await fs.readFile(manifestPath, 'utf-8');
1559
+ }
1560
+ catch {
1561
+ throw new Error(`${abs} is not an offline bundle (missing manifest.json). Create one on a networked machine with: ht offline-bundle <dir>`);
1562
+ }
1563
+ let manifest;
1564
+ try {
1565
+ manifest = JSON.parse(raw);
1566
+ }
1567
+ catch (err) {
1568
+ throw new Error(`${manifestPath} is not valid JSON: ${err.message}`);
1569
+ }
1570
+ if (!Array.isArray(manifest.npmPackages)) {
1571
+ throw new Error(`${manifestPath} is missing npmPackages — recreate the bundle.`);
1572
+ }
1573
+ const npmCacheDir = path.join(abs, 'npm-cache');
1574
+ if (!(await dirExists(npmCacheDir))) {
1575
+ throw new Error(`offline bundle ${abs} is missing npm-cache/ — recreate the bundle.`);
1576
+ }
1577
+ if (manifest.hometransTarball && !(await fileExists(path.join(abs, manifest.hometransTarball)))) {
1578
+ throw new Error(`offline bundle ${abs} is missing ${manifest.hometransTarball} (listed in manifest.json) — recreate the bundle.`);
1579
+ }
1580
+ for (const [platform, file] of Object.entries(manifest.hometransTarballs ?? {})) {
1581
+ if (!(await fileExists(path.join(abs, file))) || typeof file !== 'string' || !file) {
1582
+ throw new Error(`offline bundle ${abs} is missing ${String(file)} (hometransTarballs.${platform} in manifest.json) — recreate the bundle.`);
1583
+ }
1584
+ }
1585
+ return {
1586
+ dir: abs,
1587
+ manifest,
1588
+ npmCacheDir,
1589
+ };
1590
+ }
1591
+ /** The accept header npm ≥ 10.8 sends for packuments (full metadata doc). */
1592
+ const PACKUMENT_ACCEPT_FULL = 'application/json';
1593
+ /** The accept header npm ≤ 10.7 (incl. 9.x) sends for packuments (corgi doc). */
1594
+ const PACKUMENT_ACCEPT_CORGI = 'application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*';
1595
+ function sha1Hex(text) {
1596
+ return crypto.createHash('sha1').update(text).digest('hex');
1597
+ }
1598
+ /** cacache bucket file path for a key, relative to the npm cache dir. */
1599
+ function cacheBucketPath(npmCacheDir, key) {
1600
+ const hash = crypto.createHash('sha256').update(key).digest('hex');
1601
+ return path.join(npmCacheDir, '_cacache', 'index-v5', hash.slice(0, 2), hash.slice(2, 4), hash.slice(4));
1602
+ }
1603
+ /** Parse a cacache bucket file into its (sha1-validated) index entries. */
1604
+ function parseCacheIndexFile(bucket) {
1605
+ let raw;
1606
+ try {
1607
+ raw = fsSync.readFileSync(bucket, 'utf-8');
1608
+ }
1609
+ catch {
1610
+ return [];
1611
+ }
1612
+ const out = [];
1613
+ for (const line of raw.split('\n')) {
1614
+ if (!line)
1615
+ continue;
1616
+ const tab = line.indexOf('\t');
1617
+ if (tab <= 0)
1618
+ continue;
1619
+ const json = line.slice(tab + 1);
1620
+ if (sha1Hex(json) !== line.slice(0, tab))
1621
+ continue; // corrupt line — cacache skips it too
1622
+ try {
1623
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
1624
+ const entry = JSON.parse(json);
1625
+ if (entry && typeof entry.key === 'string')
1626
+ out.push(entry);
1627
+ }
1628
+ catch {
1629
+ // skip
1630
+ }
1631
+ }
1632
+ return out;
1633
+ }
1634
+ /** Append an index entry to its bucket file (same layout cacache insert writes). */
1635
+ function appendCacheIndexEntry(npmCacheDir, entry) {
1636
+ const bucket = cacheBucketPath(npmCacheDir, entry.key);
1637
+ fsSync.mkdirSync(path.dirname(bucket), { recursive: true });
1638
+ const json = JSON.stringify(entry);
1639
+ fsSync.appendFileSync(bucket, `\n${sha1Hex(json)}\t${json}`, 'utf-8');
1640
+ }
1641
+ /** Rewrite a bucket file with exactly these entries (cacache compact layout). */
1642
+ function rewriteCacheIndexFile(bucket, entries) {
1643
+ const body = entries.map((entry) => {
1644
+ const json = JSON.stringify(entry);
1645
+ return `${sha1Hex(json)}\t${json}`;
1646
+ });
1647
+ fsSync.writeFileSync(bucket, `\n${body.join('\n')}`, 'utf-8');
1648
+ }
1649
+ /** All bucket files under the cache's index, recursively. */
1650
+ function cacheIndexFiles(npmCacheDir) {
1651
+ const root = path.join(npmCacheDir, '_cacache', 'index-v5');
1652
+ const files = [];
1653
+ try {
1654
+ for (const entry of fsSync.readdirSync(root, { recursive: true, withFileTypes: true })) {
1655
+ if (entry.isFile())
1656
+ files.push(path.join(entry.parentPath ?? entry.path, entry.name));
1657
+ }
1658
+ }
1659
+ catch {
1660
+ return files;
1661
+ }
1662
+ return files;
1663
+ }
1664
+ /** Content file path for a cacache integrity string, or null when unparseable. */
1665
+ function cacheContentPath(npmCacheDir, integrity) {
1666
+ const match = /^([a-z0-9-]+)-([A-Za-z0-9+/=]+)$/.exec(integrity);
1667
+ if (!match)
1668
+ return null;
1669
+ try {
1670
+ const hex = Buffer.from(match[2], 'base64').toString('hex');
1671
+ return path.join(npmCacheDir, '_cacache', 'content-v2', match[1], hex.slice(0, 2), hex.slice(2, 4), hex.slice(4));
1672
+ }
1673
+ catch {
1674
+ return null;
1675
+ }
1676
+ }
1677
+ /**
1678
+ * Fix 1 from the header comment: for every cached PACKUMENT (registry URL
1679
+ * without a `.tgz` tail) whose response varies on accept, append index
1680
+ * entries for the missing accept variant(s), pointing at the same content.
1681
+ * The body served to a corgi request is the full-metadata document — a
1682
+ * strict superset of the abbreviated one, parsed happily by old npm. A
1683
+ * variant counts as present only when its content file still exists on disk,
1684
+ * so this also repairs caches whose variant content was lost (e.g. pruned
1685
+ * by an older tool). Returns the number of appended entries.
1686
+ */
1687
+ export function clonePackumentAcceptVariants(npmCacheDir, registry) {
1688
+ const prefix = `make-fetch-happen:request-cache:${registry.replace(/\/+$/, '')}/`;
1689
+ let appended = 0;
1690
+ for (const bucket of cacheIndexFiles(npmCacheDir)) {
1691
+ const entries = parseCacheIndexFile(bucket);
1692
+ if (entries.length === 0)
1693
+ continue;
1694
+ const byKey = new Map();
1695
+ for (const entry of entries) {
1696
+ const list = byKey.get(entry.key) ?? [];
1697
+ list.push(entry);
1698
+ byKey.set(entry.key, list);
1699
+ }
1700
+ for (const [key, list] of byKey) {
1701
+ if (!key.startsWith(prefix) || key.endsWith('.tgz'))
1702
+ continue;
1703
+ // Variant is servable only when the content behind it exists on disk.
1704
+ const present = new Set();
1705
+ let source = null; // newest entry with live content
1706
+ for (const entry of list) {
1707
+ const accept = entry.metadata?.reqHeaders?.accept;
1708
+ if (!entry.integrity)
1709
+ continue;
1710
+ const contentPath = cacheContentPath(npmCacheDir, entry.integrity);
1711
+ if (!contentPath || !fsSync.existsSync(contentPath))
1712
+ continue;
1713
+ if (typeof accept === 'string')
1714
+ present.add(accept);
1715
+ source = entry;
1716
+ }
1717
+ if (!source || !source.integrity)
1718
+ continue;
1719
+ const meta = source.metadata;
1720
+ if (!meta?.resHeaders || !/\baccept\b/i.test(meta.resHeaders.vary ?? ''))
1721
+ continue;
1722
+ for (const accept of [PACKUMENT_ACCEPT_FULL, PACKUMENT_ACCEPT_CORGI]) {
1723
+ if (present.has(accept))
1724
+ continue;
1725
+ appendCacheIndexEntry(npmCacheDir, {
1726
+ key,
1727
+ integrity: source.integrity,
1728
+ time: Date.now(),
1729
+ size: source.size,
1730
+ metadata: {
1731
+ ...meta,
1732
+ reqHeaders: { ...(meta.reqHeaders ?? {}), accept },
1733
+ },
1734
+ });
1735
+ appended++;
1736
+ }
1737
+ }
1738
+ }
1739
+ return appended;
1740
+ }
1741
+ /**
1742
+ * Fix 2 from the header comment: drop every `pacote:tarball:file:` index
1743
+ * entry (cached copies of local tarballs installed during seeding) and
1744
+ * garbage-collect content files no index entry references anymore. Returns
1745
+ * the freed bytes.
1746
+ */
1747
+ function pruneNpmCacheLocalTarballs(npmCacheDir) {
1748
+ let freed = 0;
1749
+ for (const bucket of cacheIndexFiles(npmCacheDir)) {
1750
+ const entries = parseCacheIndexFile(bucket);
1751
+ if (entries.length === 0)
1752
+ continue;
1753
+ const local = entries.filter((e) => e.key.startsWith('pacote:tarball:file:'));
1754
+ if (local.length === 0)
1755
+ continue;
1756
+ if (local.length === entries.length) {
1757
+ // One key per bucket (sha256-keyed) — the whole file is this key's history.
1758
+ fsSync.rmSync(bucket, { force: true });
1759
+ }
1760
+ else {
1761
+ // Theoretical hash collision — rewrite without the local-tarball lines.
1762
+ rewriteCacheIndexFile(bucket, entries.filter((e) => !e.key.startsWith('pacote:tarball:file:')));
1763
+ }
1764
+ }
1765
+ // Conservative GC: a content file survives when ANY surviving index line
1766
+ // references its integrity.
1767
+ const referenced = new Set();
1768
+ for (const bucket of cacheIndexFiles(npmCacheDir)) {
1769
+ for (const entry of parseCacheIndexFile(bucket)) {
1770
+ if (entry.integrity)
1771
+ referenced.add(entry.integrity);
1772
+ }
1773
+ }
1774
+ const contentRoot = path.join(npmCacheDir, '_cacache', 'content-v2');
1775
+ let contentFiles = [];
1776
+ try {
1777
+ contentFiles = fsSync
1778
+ .readdirSync(contentRoot, { recursive: true, withFileTypes: true })
1779
+ .filter((e) => e.isFile())
1780
+ .map((e) => path.join(e.parentPath ?? e.path, e.name));
1781
+ }
1782
+ catch {
1783
+ return freed;
1784
+ }
1785
+ for (const file of contentFiles) {
1786
+ const rel = path.relative(contentRoot, file).split(path.sep);
1787
+ if (rel.length < 4)
1788
+ continue;
1789
+ const algo = rel[0];
1790
+ const hex = rel.slice(1).join('');
1791
+ if (!/^[0-9a-f]+$/.test(hex) || !/^[a-z0-9-]+$/.test(algo))
1792
+ continue;
1793
+ const integrity = `${algo}-${Buffer.from(hex, 'hex').toString('base64')}`;
1794
+ if (referenced.has(integrity))
1795
+ continue;
1796
+ try {
1797
+ freed += fsSync.statSync(file).size;
1798
+ fsSync.rmSync(file, { force: true });
1799
+ }
1800
+ catch {
1801
+ // skip
1802
+ }
1803
+ }
1804
+ return freed;
1805
+ }
1806
+ /** Registry URLs compare equal ignoring trailing slashes (`.../npm/` === `.../npm`). */
1807
+ function sameRegistryUrl(a, b) {
1808
+ return a.replace(/\/+$/, '') === b.replace(/\/+$/, '');
1809
+ }
1810
+ /**
1811
+ * Registry-mismatch precheck for `ht init --offline-bundle`. npm's offline
1812
+ * cache is keyed by exact registry URL, so a bundle seeded under registry X
1813
+ * is guaranteed to fail with ENOTCACHED on a machine whose registry is Y —
1814
+ * even though every package is in the cache. Detect that here and abort with
1815
+ * the fix before npm prints its wall of ENOTCACHED errors. Silently skipped
1816
+ * when npm is unusable or the bundle predates the check (no npmRegistry in
1817
+ * the manifest). Returns an actionable error message, or null when the check
1818
+ * passes or cannot run.
1819
+ */
1820
+ function bundleNpmRegistryMismatch(bundle) {
1821
+ const seeded = bundle.manifest.npmRegistry;
1822
+ if (!seeded)
1823
+ return null;
1824
+ const current = npmConfigRegistry();
1825
+ if (!current)
1826
+ return null;
1827
+ if (sameRegistryUrl(current, seeded))
1828
+ return null;
1829
+ return [
1830
+ `npm registry mismatch — this bundle's npm-cache was seeded from ${seeded},`,
1831
+ `but this machine's npm resolves packages from ${current}. npm offline installs`,
1832
+ `look up the cache by exact registry URL, so running now would fail with ENOTCACHED.`,
1833
+ `Fix (pick one), then re-run ht init --offline-bundle:`,
1834
+ ` 1. Point npm at the bundle's registry on this machine (offline-safe: the URL is`,
1835
+ ` only a cache key, nothing is fetched): npm config set registry ${seeded}`,
1836
+ ` or for the current shell only: PowerShell: $env:npm_config_registry="${seeded}" bash: export npm_config_registry=${seeded}`,
1837
+ ` 2. Recreate the bundle on a machine whose npm registry is ${current}:`,
1838
+ ` ht offline-bundle <dir>`,
1839
+ ].join('\n');
1840
+ }
1841
+ /**
1842
+ * POSIX bootstrap script written into every bundle root as install.sh — the
1843
+ * ONE-COMMAND offline entry point. It auto-selects the hometrans tarball for
1844
+ * the machine it runs on: platform/arch is detected through the NODE BINARY
1845
+ * (`node -p process.platform/arch`), because that is what npm installs for —
1846
+ * a Rosetta or emulated shell would otherwise pick the wrong file. The
1847
+ * tarball filename comes from manifest.json's hometransTarballs map
1848
+ * (pretty-printed, one field per line, so a sed extracts it without jq).
1849
+ * One step by design: after the tarball install it execs `ht init
1850
+ * --offline-bundle` in the same process — the registry override below must
1851
+ * cover init too, and a separate manual `ht init` would run outside it
1852
+ * against the machine's own registry config.
1853
+ *
1854
+ * Registry override: npm's offline cache is keyed by exact registry URL, so
1855
+ * the script exports npm_config_registry from manifest.json's npmRegistry
1856
+ * for itself and its children (npm, ht) — an offline machine whose registry
1857
+ * points elsewhere (corporate mirror) installs from the cache without its
1858
+ * npm config being touched (the override dies with the script process).
1859
+ *
1860
+ * Text constraints: String.raw keeps the sed backslashes verbatim, so the
1861
+ * script must contain NO backticks and NO ${...} — both would terminate or
1862
+ * interpolate inside the enclosing template literal.
1863
+ */
1864
+ const OFFLINE_INSTALL_SH = String.raw `#!/bin/sh
1865
+ # HomeTrans offline bootstrap - generated by 'ht offline-bundle'.
1866
+ # Auto-selects the hometrans tarball for this machine (the os/arch of the
1867
+ # node binary npm installs for - not the shell, so Rosetta and emulated
1868
+ # terminals still pick the right file) and installs it fully offline from
1869
+ # the bundle's npm cache, then runs 'ht init --offline-bundle' in this same
1870
+ # process - one step, so the registry override below covers init too.
1871
+
1872
+ set -e
1873
+
1874
+ DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)
1875
+ MANIFEST="$DIR/manifest.json"
1876
+
1877
+ if ! command -v node >/dev/null 2>&1; then
1878
+ echo "error: node not found - install node (>= 22.18 recommended) first." >&2
1879
+ exit 1
1880
+ fi
1881
+ if ! command -v npm >/dev/null 2>&1; then
1882
+ echo "error: npm not found - it ships with node." >&2
1883
+ exit 1
1884
+ fi
1885
+
1886
+ OS=$(node -p process.platform)
1887
+ ARCH=$(node -p process.arch)
1888
+ KEY="$OS-$ARCH"
1889
+
1890
+ # manifest.json maps platform keys to tarball filenames, e.g.
1891
+ # "darwin-arm64": "buaa_smat-hometrans-<version>-darwin-arm64.tgz"
1892
+ TARBALL=""
1893
+ MATCH=$(sed -n 's/.*"'"$KEY"'"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$MANIFEST" 2>/dev/null | head -n 1)
1894
+ if [ -n "$MATCH" ] && [ -f "$DIR/$MATCH" ]; then
1895
+ TARBALL="$DIR/$MATCH"
1896
+ else
1897
+ for f in "$DIR"/*-"$KEY".tgz; do
1898
+ if [ -f "$f" ]; then
1899
+ TARBALL="$f"
1900
+ break
1901
+ fi
1902
+ done
1903
+ fi
1904
+ if [ -z "$TARBALL" ]; then
1905
+ echo "error: this bundle carries no hometrans tarball for $KEY." >&2
1906
+ ls -1 "$DIR"/*.tgz >&2 2>/dev/null || echo " (no *.tgz files in $DIR)" >&2
1907
+ echo " Recreate the bundle with a newer 'ht offline-bundle', or install" >&2
1908
+ echo " the matching tarball manually: npm install -g --offline --cache" >&2
1909
+ echo " <bundle>/npm-cache <bundle>/<tarball-for-your-platform>" >&2
1910
+ exit 1
1911
+ fi
1912
+
1913
+ echo "Detected platform : $KEY"
1914
+ echo "Tarball : $(basename "$TARBALL")"
1915
+
1916
+ # npm's offline cache is keyed by the exact registry URL each request would
1917
+ # hit. When this machine resolves packages from a different registry (a
1918
+ # corporate mirror, say), the cache would miss with ENOTCACHED even though
1919
+ # every package is inside it. Point npm at the registry the cache was seeded
1920
+ # from - the override is exported for THIS SCRIPT and its children only
1921
+ # (npm, ht): when the script exits, your npm config is exactly as before.
1922
+ BUNDLE_REGISTRY=$(sed -n 's/.*"npmRegistry"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$MANIFEST" 2>/dev/null | head -n 1)
1923
+ if [ -n "$BUNDLE_REGISTRY" ]; then
1924
+ echo "npm registry (cache key): $BUNDLE_REGISTRY - script-scoped, npm config untouched"
1925
+ export npm_config_registry="$BUNDLE_REGISTRY"
1926
+ fi
1927
+
1928
+ echo "Installing offline (no network needed) ..."
1929
+ npm install -g --offline --no-audit --no-fund --cache "$DIR/npm-cache" "$TARBALL"
1930
+
1931
+ echo ""
1932
+ echo "hometrans installed - initializing (ht init --offline-bundle) ..."
1933
+ exec ht init --offline-bundle "$DIR"
1934
+ `;
1935
+ /**
1936
+ * Windows counterpart of OFFLINE_INSTALL_SH, written as install.ps1.
1937
+ * PowerShell has ConvertFrom-Json built in, so the manifest lookup needs no
1938
+ * sed gymnastics. Same one-step flow (tarball install, then `ht init
1939
+ * --offline-bundle` in this same process), same registry override
1940
+ * (npm_config_registry from the manifest's npmRegistry, process-scoped, npm
1941
+ * config untouched), and same text rules as the sh script: no backticks,
1942
+ * no ${...}.
1943
+ */
1944
+ const OFFLINE_INSTALL_PS1 = String.raw `# HomeTrans offline bootstrap - generated by 'ht offline-bundle'.
1945
+ # Auto-selects the hometrans tarball for this machine (the os/arch of the
1946
+ # node binary npm installs for - not the shell) and installs it fully
1947
+ # offline from the bundle's npm cache, then runs 'ht init --offline-bundle'
1948
+ # in this same process - one step, so the registry override below covers
1949
+ # init too.
1950
+
1951
+ [CmdletBinding()]
1952
+ param()
1953
+ $ErrorActionPreference = 'Stop'
1954
+
1955
+ $Dir = $PSScriptRoot
1956
+ $ManifestPath = Join-Path $Dir 'manifest.json'
1957
+
1958
+ foreach ($cmd in @('node', 'npm')) {
1959
+ if (-not (Get-Command $cmd -ErrorAction SilentlyContinue)) {
1960
+ Write-Error ('{0} not found - install node (>= 22.18 recommended) first.' -f $cmd)
1961
+ }
1962
+ }
1963
+
1964
+ $os = (node -p process.platform).Trim()
1965
+ $arch = (node -p process.arch).Trim()
1966
+ $key = "$os-$arch"
1967
+
1968
+ $tgz = $null
1969
+ if (Test-Path $ManifestPath) {
1970
+ $manifest = Get-Content $ManifestPath -Raw | ConvertFrom-Json
1971
+ if ($manifest.hometransTarballs) {
1972
+ $tgz = $manifest.hometransTarballs.$key
1973
+ }
1974
+ }
1975
+ if (-not $tgz -or -not (Test-Path (Join-Path $Dir "$tgz"))) {
1976
+ $available = (Get-ChildItem -Path (Join-Path $Dir '*.tgz') -ErrorAction SilentlyContinue | ForEach-Object { $_.Name }) -join ', '
1977
+ Write-Error ('this bundle carries no hometrans tarball for {0} (available: {1}).' -f $key, $available)
1978
+ }
1979
+
1980
+ $Cache = Join-Path $Dir 'npm-cache'
1981
+ $Tarball = Join-Path $Dir "$tgz"
1982
+
1983
+ # npm's offline cache is keyed by the exact registry URL each request would
1984
+ # hit. When this machine resolves packages from a different registry (a
1985
+ # corporate mirror, say), the cache would miss with ENOTCACHED even though
1986
+ # every package is inside it. Point npm at the registry the cache was seeded
1987
+ # from - the override lives in THIS PROCESS only (npm and ht inherit it):
1988
+ # when the script exits, your npm config is exactly as before.
1989
+ if ($manifest -and $manifest.npmRegistry) {
1990
+ Write-Host ('npm registry (cache key): {0} - script-scoped, npm config untouched' -f $manifest.npmRegistry)
1991
+ $env:npm_config_registry = $manifest.npmRegistry
1992
+ }
1993
+
1994
+ Write-Host "Detected platform : $key"
1995
+ Write-Host "Tarball : $tgz"
1996
+ Write-Host 'Installing offline (no network needed) ...'
1997
+ npm install -g --offline --no-audit --no-fund --cache $Cache $Tarball
1998
+ if ($LASTEXITCODE -ne 0) {
1999
+ exit $LASTEXITCODE
2000
+ }
2001
+
2002
+ Write-Host ''
2003
+ Write-Host 'hometrans installed - initializing (ht init --offline-bundle) ...'
2004
+ & ht init --offline-bundle $Dir
2005
+ if ($LASTEXITCODE -ne 0) {
2006
+ exit $LASTEXITCODE
2007
+ }
2008
+ `;
2009
+ /**
2010
+ * Write the bootstrap scripts into a bundle root: install.sh with LF endings
2011
+ * (POSIX requirement) and the executable bit on non-Windows creators,
2012
+ * install.ps1 with CRLF endings. Exported so a bundle's scripts can be
2013
+ * regenerated in place (e.g. after a template fix) without re-running the
2014
+ * whole `ht offline-bundle` flow.
2015
+ */
2016
+ export function writeOfflineBootstrapScripts(bundleRoot) {
2017
+ fsSync.writeFileSync(path.join(bundleRoot, 'install.sh'), OFFLINE_INSTALL_SH.replace(/\r\n/g, '\n'), 'utf-8');
2018
+ fsSync.writeFileSync(path.join(bundleRoot, 'install.ps1'), OFFLINE_INSTALL_PS1.replace(/\r?\n/g, '\r\n'), 'utf-8');
2019
+ if (process.platform !== 'win32') {
2020
+ try {
2021
+ fsSync.chmodSync(path.join(bundleRoot, 'install.sh'), 0o755);
2022
+ }
2023
+ catch {
2024
+ // best effort — 'sh install.sh' works without the exec bit too
2025
+ }
2026
+ }
2027
+ }
2028
+ /**
2029
+ * Filename prefix of packed hometrans tarballs (e.g. 'buaa_smat-hometrans-'),
2030
+ * derived from the repo package name the same way packLocalHometransAll
2031
+ * derives its tarball stem — used to sweep stale tarballs from a previous
2032
+ * run of this command out of the bundle dir.
2033
+ */
2034
+ function hometransTarballPrefix() {
2035
+ try {
2036
+ const pkgPath = path.resolve(__dirname, '..', '..', 'package.json');
2037
+ const name = JSON.parse(fsSync.readFileSync(pkgPath, 'utf-8')).name ??
2038
+ '@buaa_smat/hometrans';
2039
+ return `${name.replace('@', '').replace('/', '-')}-`;
2040
+ }
2041
+ catch {
2042
+ return 'buaa_smat-hometrans-';
2043
+ }
2044
+ }
2045
+ /**
2046
+ * Create an offline bundle on this (networked) machine.
2047
+ *
2048
+ * npm only: a scratch project `npm install --cache <bundle>/npm-cache` pulls
2049
+ * the full transitive graph into a self-contained cache; the scratch
2050
+ * package-lock.json pins every top-level package to the exact resolved
2051
+ * version so the offline install is deterministic. hometrans itself ships as
2052
+ * a repacked LOCAL tarball (see packLocalHometransAll).
2053
+ *
2054
+ * There is no Python/pip half any more: every shipped skill and agent is
2055
+ * Node-only, so the bundle needs nothing but the npm cache and the
2056
+ * per-platform hometrans tarballs. Bundles created before that change may
2057
+ * still carry a pip-wheels/ directory; it is simply ignored.
2058
+ *
2059
+ * Never prompts; hard-fails only when the npm seeding fails.
2060
+ */
2061
+ export async function createOfflineBundle(dir) {
2062
+ const abs = path.resolve(dir);
2063
+ console.log(chalk.cyan(` Creating offline bundle: ${abs}`));
2064
+ const npmCacheDir = path.join(abs, 'npm-cache');
2065
+ await fs.mkdir(npmCacheDir, { recursive: true });
2066
+ // Sweep hometrans tarballs left by a previous run of this command in the
2067
+ // same dir — the packs below rewrite the current set, and stale versioned
2068
+ // files would otherwise linger and confuse the bootstrap scripts' lookup.
2069
+ const stalePrefix = hometransTarballPrefix();
2070
+ for (const entry of fsSync.readdirSync(abs)) {
2071
+ if (entry.startsWith(stalePrefix) && entry.endsWith('.tgz')) {
2072
+ fsSync.rmSync(path.join(abs, entry), { force: true });
2073
+ }
2074
+ }
2075
+ // --- hometrans itself: pack the LOCAL build into the bundle --------------
2076
+ // The offline machine bootstraps `ht` from one of these tarballs — one per
2077
+ // target platform, each fully self-contained (whole runtime closure + that
2078
+ // platform's native binaries) — so it gets the exact feature set that
2079
+ // created the bundle (registry versions may lag).
2080
+ const localVersion = hometransVersion();
2081
+ const tarballs = packLocalHometransAll(abs);
2082
+ let hometransSpec = null; // what the scratch install seeds
2083
+ if (tarballs) {
2084
+ const files = [...new Set(Object.values(tarballs))];
2085
+ console.log(chalk.gray(files.length === 1
2086
+ ? ` Packed local hometrans: ${files[0]} (one cross-platform tarball)`
2087
+ : ` Packed local hometrans for: ${Object.keys(tarballs).join(', ')}`));
2088
+ }
2089
+ else {
2090
+ console.log(chalk.yellow(' ! npm pack of the local hometrans failed — bundling the registry version instead.'));
2091
+ console.log(chalk.yellow(' The offline machine may lack this CLI\'s offline features. Prefer re-creating the bundle.'));
2092
+ hometransSpec = HOMETRANS_PACKAGE;
2093
+ }
2094
+ // --- npm: seed a self-contained cache via a scratch install -------------
2095
+ // Record the registry the cache is being seeded from: npm's cache is keyed
2096
+ // by exact registry URL, so offline machines must resolve from the same one
2097
+ // (init prechecks this against the manifest and aborts with a fix).
2098
+ const npmRegistry = npmConfigRegistry() ?? undefined;
2099
+ const scratch = path.join(await fs.mkdtemp(path.join(os.tmpdir(), 'hometrans-offline-seed-')));
2100
+ let npmPins = [];
2101
+ // Platform-native optional deps in the seed closure are the only thing a
2102
+ // second `npm install --os/--cpu` round can add to the cache, so capture
2103
+ // whether any exist while the scratch tree is still on disk.
2104
+ let seedNativeHosts = [];
2105
+ try {
2106
+ await fs.writeFile(path.join(scratch, 'package.json'), JSON.stringify({ name: 'hometrans-offline-seed', private: true, version: '0.0.0' }, null, 2), 'utf-8');
2107
+ console.log(chalk.gray(` Seeding npm cache for ${OFFLINE_NPM_SEED_SET.length} packages (full dependency graph) ...`));
2108
+ // The packed tarballs carry hometrans' whole runtime closure, so they need
2109
+ // nothing from the cache — only the registry fallback (pack failed) is
2110
+ // seeded through the scratch install like any other package.
2111
+ const r = spawnSync('npm', [
2112
+ 'install',
2113
+ '--cache',
2114
+ shellArg(npmCacheDir),
2115
+ '--no-audit',
2116
+ '--no-fund',
2117
+ ...(hometransSpec ? [shellArg(hometransSpec)] : []),
2118
+ ...OFFLINE_NPM_SEED_SET,
2119
+ ], { stdio: 'inherit', shell: process.platform === 'win32', timeout: 20 * 60 * 1000, cwd: scratch });
2120
+ if (r.status !== 0) {
2121
+ throw new Error('npm seeding install failed — check the network and registry reachability.');
2122
+ }
2123
+ // Pin each runtime package to the exact resolved version from the lockfile.
2124
+ const lock = JSON.parse(await fs.readFile(path.join(scratch, 'package-lock.json'), 'utf-8'));
2125
+ npmPins = OFFLINE_NPM_SEED_SET.map((spec) => {
2126
+ const name = spec.startsWith('@') ? spec.split('@').slice(0, 2).join('@') : spec.split('@')[0];
2127
+ const version = lock.packages?.[`node_modules/${name}`]?.version;
2128
+ return version ? `${name}@${version}` : spec;
2129
+ });
2130
+ seedNativeHosts = findNativeBinaryHosts(path.join(scratch, 'node_modules'));
2131
+ }
2132
+ finally {
2133
+ await fs.rm(scratch, { recursive: true, force: true }).catch(() => { });
2134
+ }
2135
+ // --- npm: cross-platform cache rounds --------------------------------------
2136
+ // The seed set's platform-specific optional dependencies (e.g. fsevents on
2137
+ // macOS, @img binaries) are only resolved when npm installs FOR that
2138
+ // platform — one scratch round per target combo. `--libc` is required on
2139
+ // non-linux creators: without a detected libc family npm rejects every
2140
+ // libc-gated linux binary. A failed round only warns (the bundle stays
2141
+ // usable on the other platforms).
2142
+ //
2143
+ // With no platform-native dependency in the seed closure the cache is
2144
+ // identical for every target (tarballs and packuments do not vary by os/cpu),
2145
+ // so the creating machine's round above already covers all platforms and the
2146
+ // four extra installs are pure waiting. They come back automatically if a
2147
+ // native-binary host ever enters the seed set.
2148
+ if (seedNativeHosts.length === 0) {
2149
+ console.log(chalk.gray(' npm cache: no platform-native dependencies in the seed set — one round covers every target platform.'));
2150
+ }
2151
+ else {
2152
+ console.log(chalk.gray(` npm cache: native hosts to resolve per platform — ${seedNativeHosts.map((h) => h.name).join(', ')}`));
2153
+ const creatingCombo = BUNDLED_NATIVE_PLATFORMS.find((c) => c.os === process.platform && c.cpu === process.arch && (!c.libc || c.libc === 'glibc'));
2154
+ for (const combo of BUNDLED_NATIVE_PLATFORMS) {
2155
+ if (combo === creatingCombo)
2156
+ continue; // covered by the main seed round above
2157
+ const key = platformComboKey(combo);
2158
+ const platScratch = path.join(await fs.mkdtemp(path.join(os.tmpdir(), `hometrans-offline-seed-${key}-`)));
2159
+ try {
2160
+ await fs.writeFile(path.join(platScratch, 'package.json'), JSON.stringify({ name: 'hometrans-offline-seed', private: true, version: '0.0.0' }, null, 2), 'utf-8');
2161
+ const r = spawnSync('npm', [
2162
+ 'install',
2163
+ '--cache',
2164
+ shellArg(npmCacheDir),
2165
+ '--no-audit',
2166
+ '--no-fund',
2167
+ '--os',
2168
+ combo.os,
2169
+ '--cpu',
2170
+ combo.cpu,
2171
+ ...(combo.libc ? ['--libc', combo.libc] : []),
2172
+ ...OFFLINE_NPM_SEED_SET,
2173
+ ], { stdio: 'inherit', shell: process.platform === 'win32', timeout: 20 * 60 * 1000, cwd: platScratch });
2174
+ if (r.status !== 0) {
2175
+ console.log(chalk.yellow(` ! npm cache round for ${key} failed — that platform's optional deps may be missing offline.`));
2176
+ }
2177
+ }
2178
+ finally {
2179
+ await fs.rm(platScratch, { recursive: true, force: true }).catch(() => { });
2180
+ }
2181
+ }
2182
+ }
2183
+ // --- npm: cross-npm-version cache hardening --------------------------------
2184
+ // Clone every packument's missing accept variant so the cache serves BOTH
2185
+ // npm generations (≤ 10.7 corgi / ≥ 10.8 full — see
2186
+ // clonePackumentAcceptVariants), then drop the cached copies of local
2187
+ // tarballs the scratch installs left behind (~0.5 GB each) plus content
2188
+ // files nothing references anymore.
2189
+ const clonedEntries = clonePackumentAcceptVariants(npmCacheDir, npmRegistry ?? 'https://registry.npmjs.org/');
2190
+ console.log(chalk.gray(` npm cache: ${clonedEntries} packument accept-variant entries cloned (npm ≤ 10.7 and ≥ 10.8 compatible).`));
2191
+ const freedBytes = pruneNpmCacheLocalTarballs(npmCacheDir);
2192
+ console.log(chalk.gray(` npm cache: pruned local-tarball copies — ${(freedBytes / 1048576).toFixed(1)} MB freed.`));
2193
+ // --- manifest -------------------------------------------------------------
2194
+ const manifest = {
2195
+ createdBy: `@buaa_smat/hometrans@${localVersion}`,
2196
+ createdAt: new Date().toISOString(),
2197
+ platform: `${process.platform}-${process.arch}`,
2198
+ npmPackages: npmPins,
2199
+ npmRegistry,
2200
+ hometransVersion: localVersion,
2201
+ // Back-compat single-tarball field (only loadOfflineBundle's existence
2202
+ // check reads it): the creating machine's tarball when its platform is
2203
+ // bundled — combos are packed creating-machine first — else the first
2204
+ // packed combo.
2205
+ hometransTarball: tarballs ? Object.values(tarballs)[0] : undefined,
2206
+ hometransTarballs: tarballs ?? undefined,
2207
+ };
2208
+ await fs.writeFile(path.join(abs, 'manifest.json'), JSON.stringify(manifest, null, 2), 'utf-8');
2209
+ // --- bootstrap scripts: one-command offline entry with platform auto-select
2210
+ if (tarballs) {
2211
+ writeOfflineBootstrapScripts(abs);
2212
+ console.log(chalk.gray(' Bootstrap scripts: install.sh (macOS/Linux) / install.ps1 (Windows) — auto-select the tarball, install offline, then run ht init in the same process (one step).'));
2213
+ }
2214
+ // --- project README: readable copy at the bundle root ----------------------
2215
+ // The tarball embeds it under package/, but a top-level copy documents the
2216
+ // bundle (install flow, migration steps) without unpacking anything. Always
2217
+ // refreshed so the bundle documents the exact build it was created from.
2218
+ try {
2219
+ await fs.copyFile(path.resolve(__dirname, '..', '..', 'README.md'), path.join(abs, 'README.md'));
2220
+ console.log(chalk.gray(' README: copied from the project to the bundle root.'));
2221
+ }
2222
+ catch {
2223
+ console.log(chalk.yellow(' ! README.md not found in the project — bundle-root copy skipped.'));
2224
+ }
2225
+ console.log(chalk.green(' + Offline bundle created.'));
2226
+ // One cross-platform tarball lists every platform key against the same
2227
+ // file; collapse repeated filenames into one readable entry.
2228
+ const byFile = new Map();
2229
+ for (const [key, file] of Object.entries(tarballs ?? {})) {
2230
+ byFile.set(file, [...(byFile.get(file) ?? []), key]);
2231
+ }
2232
+ const forAllPlatforms = (keys) => keys.length === BUNDLED_NATIVE_PLATFORMS.length;
2233
+ const manual = [...byFile]
2234
+ .map(([file, keys]) => forAllPlatforms(keys) ? `${file} → every platform` : keys.map((key) => `${key} → ${file}`).join(' | '))
2235
+ .join(' | ');
2236
+ if (tarballs) {
2237
+ const listed = [...byFile]
2238
+ .map(([file, keys]) => forAllPlatforms(keys)
2239
+ ? `${file} (one cross-platform tarball)`
2240
+ : `${file} (${keys.join(', ')})`)
2241
+ .join(', ');
2242
+ console.log(chalk.gray(` ht: local build v${localVersion} — ${listed}`));
2243
+ }
2244
+ else {
2245
+ console.log(chalk.gray(` ht: registry version (pack failed!)`));
2246
+ }
2247
+ console.log(chalk.gray(` npm: ${manifest.npmPackages.join(', ')}`));
2248
+ if (manifest.npmRegistry) {
2249
+ console.log(chalk.gray(` npm registry: ${manifest.npmRegistry} — offline machines must resolve from the same one (the cache is keyed by registry URL)`));
2250
+ }
2251
+ console.log(chalk.gray(` platform: ${manifest.platform}`));
2252
+ console.log('');
2253
+ console.log(chalk.gray(' On the offline machine (adjust the bundle path to where you copy it):'));
2254
+ if (tarballs) {
2255
+ console.log(chalk.gray(` macOS / Linux: sh "${path.join(abs, 'install.sh')}"`));
2256
+ console.log(chalk.gray(` Windows: powershell -ExecutionPolicy Bypass -File "${path.join(abs, 'install.ps1')}"`));
2257
+ console.log(chalk.gray(' — one step: auto-detects the machine platform, installs the matching tarball offline, then runs'));
2258
+ console.log(chalk.gray(' ht init --offline-bundle in the same process (registry override included)'));
2259
+ console.log(chalk.gray(` manual equivalent: npm install -g --offline --cache "${path.join(abs, 'npm-cache')}" <tarball> — ${manual} — then ht init --offline-bundle "${abs}"`));
2260
+ }
2261
+ else {
2262
+ console.log(chalk.gray(` 1. npm install -g --offline --cache "${path.join(abs, 'npm-cache')}" ${HOMETRANS_PACKAGE}`));
2263
+ console.log(chalk.gray(` 2. ht init --offline-bundle "${abs}"`));
2264
+ }
2265
+ }
2266
+ /**
2267
+ * The running hometrans version (for manifest provenance). Resolved from the
2268
+ * package.json two levels above dist/cli — the same file the CLI --version uses.
2269
+ */
2270
+ function hometransVersion() {
2271
+ try {
2272
+ const pkgPath = path.resolve(__dirname, '..', '..', 'package.json');
2273
+ return JSON.parse(fsSync.readFileSync(pkgPath, 'utf-8')).version ?? 'unknown';
2274
+ }
2275
+ catch {
2276
+ return 'unknown';
2277
+ }
2278
+ }
2279
+ /**
2280
+ * Quote a single argv value for `spawnSync(..., { shell: true })` on Windows —
2281
+ * with a shell, Node joins the args array with spaces, so any value containing
2282
+ * spaces (e.g. bundle paths) must carry its own quotes. Non-Windows platforms
2283
+ * run without a shell and need no quoting.
2284
+ */
2285
+ function shellArg(v) {
2286
+ return process.platform === 'win32' && /\s/.test(v) ? `"${v}"` : v;
2287
+ }
2288
+ export async function initCommand(options = {}) {
2289
+ ensureChalkColor();
2290
+ // Resolve the offline bundle (if any) up front — invalid bundles abort with
2291
+ // an actionable message before anything is installed.
2292
+ let bundle;
2293
+ if (options.offlineBundle) {
2294
+ try {
2295
+ bundle = await loadOfflineBundle(options.offlineBundle);
2296
+ }
2297
+ catch (err) {
2298
+ console.error(chalk.red(` ! ${err.message}`));
2299
+ process.exitCode = 1;
2300
+ return;
2301
+ }
2302
+ console.log(chalk.blue(` Offline mode: using bundle ${bundle.dir}`));
2303
+ console.log(chalk.gray(` created by ${bundle.manifest.createdBy} on ${bundle.manifest.platform}` +
2304
+ ` at ${bundle.manifest.createdAt}` +
2305
+ (bundle.manifest.npmRegistry ? `, npm-cache seeded from ${bundle.manifest.npmRegistry}` : '')));
2306
+ const registryMismatch = bundleNpmRegistryMismatch(bundle);
2307
+ if (registryMismatch) {
2308
+ console.error(chalk.red(` ! ${registryMismatch}`));
2309
+ process.exitCode = 1;
2310
+ return;
2311
+ }
2312
+ if (bundle.manifest.hometransTarballs) {
2313
+ const current = `${process.platform}-${process.arch}`;
2314
+ if (!bundle.manifest.hometransTarballs[current]) {
2315
+ console.log(chalk.yellow(` ! this bundle has no hometrans tarball for ${current} (carries: ${Object.keys(bundle.manifest.hometransTarballs).join(', ')}).`));
2316
+ console.log(chalk.gray(' Fine if `ht` is already installed from another source; otherwise bootstrap it from a matching tarball.'));
2317
+ }
2318
+ }
2319
+ console.log('');
2320
+ }
2321
+ const banner = figlet.textSync('HomeTrans', { font: 'Standard' });
2322
+ console.log(chalk.cyan(`\n${banner.trimEnd()}`));
2323
+ console.log(chalk.gray('\n Android-to-HarmonyOS skill & agent installer for AI editors\n'));
2324
+ const skillsRoot = resolveSkillsRoot();
2325
+ const agentsRoot = resolveAgentsRoot();
2326
+ const commandsRoot = resolveCommandsRoot();
2327
+ const hasSkills = await dirExists(skillsRoot);
2328
+ const hasAgents = await dirExists(agentsRoot);
2329
+ if (!hasSkills && !hasAgents) {
2330
+ console.error(chalk.red(` ! Neither skills/ nor agents/ found at package root.`));
2331
+ console.error(chalk.gray(` Looked in: ${skillsRoot}`));
2332
+ console.error(chalk.gray(` ${agentsRoot}`));
2333
+ console.error(chalk.gray(' Reinstall hometrans or run `npm run build` from the package root.'));
2334
+ process.exitCode = 1;
2335
+ return;
2336
+ }
2337
+ const language = await chooseInstallLanguage(options);
2338
+ // Check the overlay now: finding it broken only after the dependency install
2339
+ // would waste the whole run.
2340
+ if (language === 'en') {
2341
+ try {
2342
+ await loadLanguageOverlay(resolveI18nRoot());
2343
+ }
2344
+ catch (err) {
2345
+ console.error(chalk.red(` ! ${err.message}`));
2346
+ process.exitCode = 1;
2347
+ return;
2348
+ }
2349
+ }
2350
+ // No config file: the editor list is the bundled editors.json table (same as
2351
+ // `devecocli plugin install`), and the SDK paths start from what the OS
2352
+ // environment already has. A ~/.hometrans/config.json left by an older
2353
+ // release is not read.
2354
+ const editors = defaultEditors();
2355
+ const env = envFromProcess();
2356
+ const detected = await detectInstalledEditors(editors);
2357
+ const installedStatus = detected.status;
2358
+ // Entries detectInstalledEditors could not resolve (no editors.json row) have
2359
+ // no install target: keep them out of the selection list. Their message is
2360
+ // reported under Errors at the end.
2361
+ const configurableEditors = editors.filter((e) => installedStatus.has(e.name));
2362
+ let selectedEditors;
2363
+ if (options.all) {
2364
+ selectedEditors = configurableEditors.map((e) => e.name);
2365
+ console.log(chalk.blue(' --all: selecting all editors.\n'));
2366
+ }
2367
+ else {
2368
+ const choices = configurableEditors.map((editor) => {
2369
+ const installed = installedStatus.get(editor.name);
2370
+ // Show the editors.json displayName (`Claude Code`); the value stays the
2371
+ // canonical id so the selection logic is unaffected.
2372
+ const title = editorDisplayName(editor.name);
2373
+ const label = installed
2374
+ ? `${title} ${chalk.green('(detected)')}`
2375
+ : `${title} ${chalk.gray('(not detected)')}`;
2376
+ return {
2377
+ name: label,
2378
+ value: editor.name,
2379
+ checked: installed,
2380
+ };
2381
+ });
2382
+ try {
2383
+ const answers = await inquirer.prompt([
2384
+ {
2385
+ type: 'checkbox',
2386
+ name: 'selectedEditors',
2387
+ message: 'Select editors to configure:',
2388
+ choices,
2389
+ // Do not wrap around at the ends: without this @inquirer/checkbox
2390
+ // (loop defaults to true) jumps from the last editor back to the
2391
+ // first, which looks like endless downward scrolling.
2392
+ loop: false,
2393
+ // Append a "ctrl-c cancel" entry to the built-in key help line, reusing
2394
+ // @inquirer/checkbox's default formatting (bold key · dim action · dim
2395
+ // " • " separator):
2396
+ // ↑↓ navigate • space select • a all • i invert • ⏎ submit • ctrl-c cancel
2397
+ theme: {
2398
+ style: {
2399
+ keysHelpTip: (keys) => [...keys, ['ctrl-c', 'cancel']]
2400
+ .map(([key, action]) => `${chalk.bold(key)} ${chalk.dim(action)}`)
2401
+ .join(chalk.dim(' • ')),
2402
+ },
2403
+ },
2404
+ },
2405
+ ]);
2406
+ selectedEditors = answers.selectedEditors;
2407
+ }
2408
+ catch (err) {
2409
+ if (isPromptAbort(err))
2410
+ abortInit();
2411
+ console.log(chalk.yellow('\n Interactive selection failed. Auto-selecting all detected editors.'));
2412
+ console.log(chalk.gray(' Tip: use --all to skip interactive selection.\n'));
2413
+ selectedEditors = configurableEditors
2414
+ .filter((e) => installedStatus.get(e.name))
2415
+ .map((e) => e.name);
2416
+ }
2417
+ }
2418
+ // No editors selected — do NOT abort. Every remaining init step still runs
2419
+ // (SDK / model configuration, dependency installation, environment check,
2420
+ // tools copy, machine env vars); only the install target changes: skills
2421
+ // and agents go to the shared ~/.agents location instead of editor dirs.
2422
+ const noEditorsSelected = selectedEditors.length === 0;
2423
+ if (noEditorsSelected) {
2424
+ console.log(chalk.yellow('\n No editors selected.'));
2425
+ console.log(chalk.gray(' Skills & agents will be installed into the shared ~/.agents location\n' +
2426
+ ' (~/.agents/skills + ~/.agents/agents). Re-run `ht init` later to install into an editor.'));
2427
+ }
2428
+ // --- User parameters (SDK paths) ---
2429
+ console.log('');
2430
+ console.log(chalk.blue(' Harmony SDK Configuration'));
2431
+ try {
2432
+ const answers = await inquirer.prompt([
2433
+ {
2434
+ type: 'input',
2435
+ name: 'DEVECO_SDK_HOME',
2436
+ message: 'DEVECO_SDK_HOME (DevEco Studio SDK dir):',
2437
+ default: env.DEVECO_SDK_HOME || undefined,
2438
+ },
2439
+ ]);
2440
+ const sdk = deriveSdkPaths(answers.DEVECO_SDK_HOME);
2441
+ Object.assign(env, sdk);
2442
+ // Echo the derived paths and validate each exists on disk; missing ones are
2443
+ // a strong signal of a typo'd DEVECO_SDK_HOME or a broken DevEco install.
2444
+ if (sdk.DEVECO_SDK_HOME) {
2445
+ const checks = [
2446
+ ['DEVECO_SDK_HOME', sdk.DEVECO_SDK_HOME],
2447
+ ['DEVECO_HOME', sdk.DEVECO_HOME],
2448
+ ['OHOS_SDK_PATH', sdk.OHOS_SDK_PATH],
2449
+ ['HMS_SDK_PATH', sdk.HMS_SDK_PATH],
2450
+ ];
2451
+ // Validate the derived paths on disk silently — the listing itself is not
2452
+ // printed; only a warning surfaces when one or more paths fail to resolve.
2453
+ let missingCount = 0;
2454
+ for (const [, p] of checks) {
2455
+ if (!(await dirExists(p)))
2456
+ missingCount++;
2457
+ }
2458
+ if (missingCount > 0) {
2459
+ console.log('');
2460
+ console.log(chalk.yellow(' ! Check DEVECO_SDK_HOME (it should be the "sdk" folder inside your DevEco Studio install)'));
2461
+ console.log(chalk.yellow(' and re-run `ht init` after fixing it. Skills that build or'));
2462
+ console.log(chalk.yellow(' review code will not work until these paths resolve.'));
2463
+ }
2464
+ }
2465
+ }
2466
+ catch (err) {
2467
+ if (isPromptAbort(err))
2468
+ abortInit();
2469
+ console.log(chalk.yellow(' Parameter prompts skipped (non-interactive mode).'));
2470
+ }
2471
+ // No model configuration: no shipped skill reads a multimodal model key (the
2472
+ // AutoGLM crawler that did is gone), so init neither asks for nor exports one.
2473
+ // Dependency Installation — `ht init` is the single provisioning point; no
2474
+ // skill ever self-installs. Provisioned here: git (diff-based agent
2475
+ // precheck) and the global npm packages (homegraph + arkanalyzer,
2476
+ // homecheck, a2h-resource, @deveco/deveco-cli, and the reqgen runtime libraries).
2477
+ // Every shipped skill is Node-only, so there is no Python/pip step.
2478
+ // Runs before the Environment Check so the check reflects fresh installs.
2479
+ console.log('');
2480
+ console.log(chalk.cyan(' Dependency Installation'));
2481
+ // git first — required by the diff-based agent precheck and by some npm-install-g flows.
2482
+ try {
2483
+ await installGit(Boolean(bundle));
2484
+ }
2485
+ catch (err) {
2486
+ if (isPromptAbort(err))
2487
+ abortInit();
2488
+ console.log(chalk.yellow(` ! git install skipped: ${err.message}`));
2489
+ }
2490
+ // Global npm CLIs + libraries used by the skills.
2491
+ try {
2492
+ await installGlobalNpmClis(bundle);
2493
+ }
2494
+ catch (err) {
2495
+ if (isPromptAbort(err))
2496
+ abortInit();
2497
+ console.log(chalk.yellow(` ! npm global install skipped: ${err.message}`));
2498
+ }
2499
+ // Detect external tools (adb / hdc / java + DevEco) and report
2500
+ // which skills/agents are impacted by anything missing.
2501
+ try {
2502
+ await runEnvironmentCheck(env);
2503
+ }
2504
+ catch (err) {
2505
+ console.log(chalk.yellow(` ! environment check skipped: ${err.message}`));
2506
+ }
2507
+ // Persist the SDK paths as real OS environment variables (Windows: setx;
2508
+ // macOS/Linux: shell rc block) — the only place they are kept, and where every
2509
+ // skill reads them. Shows what will be written and asks Y/N first.
2510
+ try {
2511
+ await maybePersistMachineEnv(env);
2512
+ }
2513
+ catch (err) {
2514
+ if (isPromptAbort(err))
2515
+ abortInit();
2516
+ console.log(chalk.red(` ! environment variables: ${err.message}`));
2517
+ }
2518
+ console.log('');
2519
+ // Empty selection → install into the shared ~/.agents location instead of
2520
+ // aborting, so the skills/agents are still available on this machine.
2521
+ const editorsToSetup = noEditorsSelected
2522
+ ? [SHARED_AGENTS_FALLBACK]
2523
+ : configurableEditors.filter((e) => selectedEditors.includes(e.name));
2524
+ const result = {
2525
+ configured: [],
2526
+ skipped: [],
2527
+ errors: [...detected.errors],
2528
+ };
2529
+ // English installs read from a staged copy with the i18n/ overlay applied.
2530
+ let contentRoots = { skillsRoot, agentsRoot, commandsRoot };
2531
+ let stagingDir;
2532
+ if (language === 'en') {
2533
+ try {
2534
+ stagingDir = await fs.mkdtemp(path.join(os.tmpdir(), 'hometrans-lang-'));
2535
+ contentRoots = await stageEnglishRoots({ skillsRoot, agentsRoot, commandsRoot, platformsRoot: null }, resolveI18nRoot(), stagingDir);
2536
+ }
2537
+ catch (err) {
2538
+ if (stagingDir)
2539
+ await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => { });
2540
+ console.error(chalk.red(` ! English content could not be prepared: ${err.message}`));
2541
+ process.exitCode = 1;
2542
+ return;
2543
+ }
2544
+ }
2545
+ try {
2546
+ for (const editor of editorsToSetup) {
2547
+ console.log(chalk.cyan(` Configuring ${editorDisplayName(editor.name)}...`));
2548
+ // One broken target must not abort the whole init (e.g. a hand-edited config
2549
+ // entry with no editors.json row): record it and keep going.
2550
+ try {
2551
+ await installForEditor(editor, contentRoots.skillsRoot, contentRoots.agentsRoot, contentRoots.commandsRoot, result, { force: options.force });
2552
+ // reqgen resolves its npm runtime deps from the global install via
2553
+ // per-copy node_modules links (skills never self-install).
2554
+ const installedSkillsDir = platformForEditor(editor).skillsDir;
2555
+ if (!installedSkillsDir)
2556
+ continue;
2557
+ try {
2558
+ await linkReqgenGlobalDeps(installedSkillsDir, editorDisplayName(editor.name));
2559
+ }
2560
+ catch (err) {
2561
+ console.log(chalk.yellow(` ! reqgen dependency link: ${err.message}`));
2562
+ }
2563
+ }
2564
+ catch (err) {
2565
+ result.errors.push(`${editorDisplayName(editor.name)}: ${err.message}`);
2566
+ }
2567
+ }
2568
+ }
2569
+ finally {
2570
+ if (stagingDir)
2571
+ await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => { });
2572
+ }
2573
+ console.log('');
2574
+ if (result.configured.length > 0) {
2575
+ console.log(chalk.green(' Configured:'));
2576
+ for (const name of result.configured)
2577
+ console.log(chalk.green(` + ${name}`));
2578
+ }
2579
+ if (result.skipped.length > 0) {
2580
+ console.log('');
2581
+ console.log(chalk.yellow(' Skipped:'));
2582
+ for (const name of result.skipped)
2583
+ console.log(chalk.yellow(` - ${name}`));
2584
+ }
2585
+ if (result.errors.length > 0) {
2586
+ console.log('');
2587
+ console.log(chalk.red(' Errors:'));
2588
+ for (const err of result.errors)
2589
+ console.log(chalk.red(` ! ${err}`));
2590
+ }
2591
+ console.log('');
2592
+ console.log(chalk.gray(` Source skills: ${skillsRoot}`));
2593
+ console.log(chalk.gray(` Source agents: ${agentsRoot}`));
2594
+ console.log(chalk.gray(` Language: ${language}`));
2595
+ console.log('');
2596
+ if (result.errors.length > 0) {
2597
+ console.log(chalk.yellow(' Finished with errors — see the list above.'));
2598
+ if (noEditorsSelected) {
2599
+ console.log(chalk.yellow(' The shared ~/.agents install may be incomplete; re-run `ht init`.'));
2600
+ }
2601
+ }
2602
+ else if (noEditorsSelected) {
2603
+ console.log(chalk.green(' Done. Skills, agents & commands installed into the shared ~/.agents location.'));
2604
+ }
2605
+ else if (result.configured.length === 0) {
2606
+ console.log(chalk.yellow(' No editors were configured. Make sure the selected editors are installed,'));
2607
+ console.log(chalk.yellow(' then re-run `ht init`.'));
2608
+ }
2609
+ else {
2610
+ console.log(chalk.green(' Done. Re-open your editor for the new skills/agents to be picked up.'));
2611
+ }
2612
+ // Errors were collected instead of thrown, so the exit code is the only
2613
+ // signal scripts and CI get. A run where every selected target was skipped
2614
+ // (nothing deployed) is a failure too.
2615
+ if (initFailed(result, noEditorsSelected))
2616
+ process.exitCode = 1;
2617
+ console.log('');
2618
+ }