@animastor/installer 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +66 -0
  3. package/ai/install-manifests/audio/qwen-tts.json +445 -0
  4. package/ai/install-manifests/image/qwen-image.json +465 -0
  5. package/ai/install-manifests/video/ltx-2.3.json +892 -0
  6. package/package.json +42 -0
  7. package/src/installer/cli.js +1067 -0
  8. package/src/installer/compatibility-resolver.js +1287 -0
  9. package/src/installer/download-planner.js +172 -0
  10. package/src/installer/engine/comfyui.js +508 -0
  11. package/src/installer/engine/downloader.js +514 -0
  12. package/src/installer/engine/engine.js +1180 -0
  13. package/src/installer/engine/io.js +437 -0
  14. package/src/installer/engine/logger.js +75 -0
  15. package/src/installer/engine/nodes.js +146 -0
  16. package/src/installer/engine/prereq.js +399 -0
  17. package/src/installer/engine/probe.js +349 -0
  18. package/src/installer/engine/progress.js +350 -0
  19. package/src/installer/engine/state.js +170 -0
  20. package/src/installer/engine/term.js +298 -0
  21. package/src/installer/engine/worker.js +430 -0
  22. package/src/installer/engine/workflows.js +153 -0
  23. package/src/installer/index.js +40 -0
  24. package/src/installer/install-manifest.js +376 -0
  25. package/src/installer/install-plan.js +741 -0
  26. package/src/installer/management.js +489 -0
  27. package/src/installer/platform/deployment/docker.js +78 -0
  28. package/src/installer/platform/deployment/native.js +36 -0
  29. package/src/installer/platform/index.js +165 -0
  30. package/src/installer/platform/linux.js +341 -0
  31. package/src/installer/platform/windows.js +360 -0
  32. package/src/installer/safety-rules.js +156 -0
  33. package/src/installer/setup-contract.js +1401 -0
  34. package/src/installer/uninstaller.js +572 -0
  35. package/src/installer/verification-report.js +220 -0
  36. package/src/installer/worker-bundle-source.js +64 -0
  37. package/src/installer/workflow-artifacts.js +152 -0
@@ -0,0 +1,349 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Environment probe — Private Worker Installer Phase 2.
5
+ *
6
+ * Detects the real installed state of a machine and produces the
7
+ * environment object consumed by the compatibility resolver:
8
+ *
9
+ * GPU / ComfyUI / Python / Torch / Node.js / custom nodes / models /
10
+ * workflows / worker bundle+.env
11
+ *
12
+ * Read-only: probing never mutates anything.
13
+ *
14
+ * .env handling is keys-only: the probe records WHICH keys are set, never
15
+ * their values (Worker Key safety).
16
+ */
17
+
18
+ const path = require('path');
19
+ const platforms = require('../platform');
20
+
21
+ const MODEL_DIRS = [
22
+ 'models/unet', 'models/clip', 'models/vae', 'models/loras',
23
+ 'models/text_encoders', 'models/checkpoints', 'models/upscale_models',
24
+ 'models/latent_upscale_models', 'models/TTS',
25
+ ];
26
+
27
+ const WORKFLOW_SCAN_ROOT = 'user/default/workflows';
28
+
29
+ /**
30
+ * Device kinds for env.device:
31
+ * cuda — NVIDIA GPU verified through the driver runtime (nvidia-smi query);
32
+ * cpu — no supported GPU: CPU-only mode (ComfyUI --cpu, CPU PyTorch).
33
+ * An AMD GPU is detected and reported, but the installer provides no ROCm
34
+ * runtime branch yet — such machines fall back to cpu with an explicit note
35
+ * (never a silent degradation).
36
+ */
37
+ const DEVICE_KINDS = Object.freeze(['cuda', 'cpu']);
38
+
39
+ function firstLine(s) {
40
+ return String(s || '').split('\n').map((x) => x.trim()).find(Boolean) || '';
41
+ }
42
+
43
+ /**
44
+ * NVIDIA GPU detection — runtime check, not just command presence:
45
+ * nvidia-smi must succeed AND report at least one GPU row.
46
+ */
47
+ function probeNvidiaGpu(io) {
48
+ const r = io.exec('nvidia-smi', [
49
+ '--query-gpu=name,memory.total,driver_version', '--format=csv,noheader,nounits',
50
+ ]);
51
+ if (r.code !== 0) return null;
52
+ const line = firstLine(r.stdout);
53
+ if (!line || /^\[?n?a$/i.test(line)) return null;
54
+ const [name, mib, driver] = line.split(',').map((x) => x.trim());
55
+ if (!name) return null;
56
+ return {
57
+ vendor: 'nvidia',
58
+ name,
59
+ vram_mib: mib ? Number(mib) : null,
60
+ driver_version: driver || null,
61
+ };
62
+ }
63
+
64
+ /**
65
+ * AMD GPU detection with positive evidence only. The detection mechanism is
66
+ * a platform concern (Linux: rocm-smi/drm sysfs/lspci; Windows: wmic) —
67
+ * delegated to the platform adapter. Empty/unknown output is treated as
68
+ * "not detected" — never guessed.
69
+ */
70
+ function probeAmdGpu(io, platformAdapter = null) {
71
+ return (platformAdapter || platforms.getPlatformAdapter()).probeAmdGpu(io);
72
+ }
73
+
74
+ function probeGpu(io) {
75
+ const nvidia = probeNvidiaGpu(io);
76
+ if (nvidia) return nvidia;
77
+ const amd = probeAmdGpu(io);
78
+ if (amd) return amd;
79
+ return null;
80
+ }
81
+
82
+ function probeCuda(io) {
83
+ const r = io.exec('nvidia-smi', []);
84
+ if (r.code !== 0) return null;
85
+ const m = /CUDA Version:\s*([0-9.]+)/.exec(r.stdout);
86
+ return m ? m[1] : null;
87
+ }
88
+
89
+ function gitInfo(io, dir) {
90
+ if (!io.fs.isDirectory(path.join(dir, '.git'))) return null;
91
+ const remote = io.exec('git', ['-C', dir, 'remote', 'get-url', 'origin']);
92
+ const head = io.exec('git', ['-C', dir, 'rev-parse', 'HEAD']);
93
+ const tag = io.exec('git', ['-C', dir, 'describe', '--tags', '--exact-match']);
94
+ return {
95
+ repository: remote.code === 0 ? firstLine(remote.stdout) : null,
96
+ commit: head.code === 0 ? firstLine(head.stdout) : null,
97
+ tag: tag.code === 0 ? firstLine(tag.stdout) : null,
98
+ };
99
+ }
100
+
101
+ function probeComfyui(io, root) {
102
+ if (!root || !io.fs.isDirectory(root)) return null;
103
+ const mainPy = io.fs.existsSync(path.join(root, 'main.py'));
104
+ if (!mainPy) return null;
105
+ const git = gitInfo(io, root);
106
+ return {
107
+ present: true,
108
+ repository: git ? git.repository : null,
109
+ commit: git ? git.commit : null,
110
+ tag: git ? git.tag : null,
111
+ version: git && git.tag ? git.tag.replace(/^v/, '') : null,
112
+ };
113
+ }
114
+
115
+ function pythonBin(io, root, platformAdapter = null) {
116
+ // prefer a venv next to ComfyUI, then python3 (venv layout is a
117
+ // platform concern: bin/python on Linux, Scripts/python.exe on Windows)
118
+ if (root) {
119
+ const venvPy = (platformAdapter || platforms.getPlatformAdapter()).venvPythonBin(path.join(root, 'venv'));
120
+ if (io.fs.existsSync(venvPy)) return venvPy;
121
+ }
122
+ return 'python3';
123
+ }
124
+
125
+ function probePython(io, root) {
126
+ const py = pythonBin(io, root);
127
+ const r = io.exec(py, ['--version']);
128
+ if (r.code !== 0) return null;
129
+ const m = /Python\s+([0-9][0-9.]*)/.exec(r.stdout + r.stderr);
130
+ return m ? { version: m[1], binary: py } : null;
131
+ }
132
+
133
+ function probeTorch(io, root) {
134
+ const py = pythonBin(io, root);
135
+ const r = io.exec(py, ['-c', 'import torch; print(torch.__version__)']);
136
+ if (r.code !== 0) return null;
137
+ const v = firstLine(r.stdout);
138
+ return v ? { version: v } : null;
139
+ }
140
+
141
+ function probeNodejs(io) {
142
+ const r = io.exec('node', ['--version']);
143
+ if (r.code !== 0) return null;
144
+ const v = firstLine(r.stdout).replace(/^v/, '');
145
+ return v ? { version: v } : null;
146
+ }
147
+
148
+ function probeCustomNodes(io, root) {
149
+ const dir = path.join(root, 'custom_nodes');
150
+ if (!io.fs.isDirectory(dir)) return [];
151
+ const out = [];
152
+ for (const name of io.fs.readdirSync(dir)) {
153
+ if (!io.fs.isDirectory(path.join(dir, name))) continue;
154
+ const git = gitInfo(io, path.join(dir, name));
155
+ out.push({
156
+ directory: name,
157
+ repository: git ? git.repository : null,
158
+ commit: git ? git.commit : null,
159
+ is_git: git !== null,
160
+ });
161
+ }
162
+ return out;
163
+ }
164
+
165
+ function walkModels(io, root, relDir, out, depth = 0) {
166
+ const abs = path.join(root, relDir);
167
+ if (!io.fs.isDirectory(abs)) return;
168
+ for (const name of io.fs.readdirSync(abs)) {
169
+ const rel = `${relDir}/${name}`;
170
+ const st = io.fs.statSync(path.join(abs, name));
171
+ if (st.isDirectory) {
172
+ if (depth < 3) walkModels(io, root, rel, out, depth + 1);
173
+ } else if (st.isFile) {
174
+ out.push({ path: rel, size_bytes: st.size });
175
+ }
176
+ }
177
+ }
178
+
179
+ function probeModels(io, root) {
180
+ const out = [];
181
+ for (const dir of MODEL_DIRS) walkModels(io, root, dir, out);
182
+ return out;
183
+ }
184
+
185
+ function sha256OfFile(io, crypto, absPath) {
186
+ const data = io.fs.readFileSync(absPath); // workflows are small; fine
187
+ return crypto.createHash('sha256').update(Buffer.from(data)).digest('hex');
188
+ }
189
+
190
+ function walkWorkflows(io, crypto, root, relDir, out) {
191
+ const abs = path.join(root, relDir);
192
+ if (!io.fs.isDirectory(abs)) return;
193
+ for (const name of io.fs.readdirSync(abs)) {
194
+ const rel = `${relDir}/${name}`;
195
+ const st = io.fs.statSync(path.join(abs, name));
196
+ if (st.isDirectory) {
197
+ walkWorkflows(io, crypto, root, rel, out);
198
+ } else if (name.endsWith('.json')) {
199
+ let hash = null;
200
+ try { hash = sha256OfFile(io, crypto, path.join(abs, name)); } catch (_) { /* unreadable */ }
201
+ out.push({ path: rel, sha256: hash });
202
+ }
203
+ }
204
+ }
205
+
206
+ function probeWorkflows(io, crypto, root) {
207
+ const out = [];
208
+ walkWorkflows(io, crypto, root, WORKFLOW_SCAN_ROOT, out);
209
+ return out;
210
+ }
211
+
212
+ /** Parse KEY=value lines; record key NAMES only — never values. */
213
+ function parseEnvKeys(text) {
214
+ const keys = [];
215
+ for (const raw of String(text || '').split('\n')) {
216
+ const line = raw.trim();
217
+ if (!line || line.startsWith('#')) continue;
218
+ const m = /^([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line);
219
+ if (m) keys.push(m[1]);
220
+ }
221
+ return keys;
222
+ }
223
+
224
+ function probeWorker(io, workerDir) {
225
+ if (!workerDir || !io.fs.isDirectory(workerDir)) return null;
226
+ // '.env' is excluded on purpose (secret values are never probed); other
227
+ // dotfiles (e.g. '.env.example' from the bundle manifest) are visible.
228
+ let files = [];
229
+ try { files = io.fs.readdirSync(workerDir).filter((f) => f !== '.env'); } catch (_) { files = []; }
230
+ const envPath = path.join(workerDir, '.env');
231
+ let env = null;
232
+ if (io.fs.existsSync(envPath)) {
233
+ env = { present: true, set_keys: parseEnvKeys(io.fs.readFileSync(envPath, 'utf8')) };
234
+ }
235
+ return {
236
+ worker_type: null, // resolved by the engine against the manifest worker_type
237
+ bundle: { present: files.includes('worker.cjs'), dir: workerDir, files },
238
+ env,
239
+ };
240
+ }
241
+
242
+ /**
243
+ * Probe the full environment.
244
+ * @param {object} io
245
+ * @param {object} opts { root: ComfyUI root, workerDir, crypto }
246
+ * @returns resolver-compatible environment object
247
+ */
248
+ function probeEnvironment(io, { root = null, workerDir = null, crypto = null, workerType = null } = {}) {
249
+ const env = {
250
+ root,
251
+ comfyui: undefined,
252
+ python: undefined,
253
+ torch: undefined,
254
+ nodejs: undefined,
255
+ gpu: undefined,
256
+ device: undefined,
257
+ custom_nodes: undefined,
258
+ models: undefined,
259
+ python_packages: undefined,
260
+ workflows: undefined,
261
+ worker: undefined,
262
+ };
263
+
264
+ env.gpu = probeGpu(io);
265
+ env.cuda = probeCuda(io);
266
+ env.device = env.gpu && env.gpu.vendor === 'nvidia' ? 'cuda' : 'cpu';
267
+ env.nodejs = probeNodejs(io);
268
+ env.comfyui = probeComfyui(io, root);
269
+ env.python = probePython(io, root);
270
+ env.torch = probeTorch(io, root);
271
+
272
+ if (env.comfyui) {
273
+ env.custom_nodes = probeCustomNodes(io, root);
274
+ env.models = probeModels(io, root);
275
+ env.python_packages = [];
276
+ if (crypto) env.workflows = probeWorkflows(io, crypto, root);
277
+ } else {
278
+ env.custom_nodes = [];
279
+ env.models = [];
280
+ env.python_packages = [];
281
+ env.workflows = [];
282
+ }
283
+
284
+ const worker = probeWorker(io, workerDir);
285
+ if (worker) {
286
+ worker.worker_type = workerType;
287
+ env.worker = worker;
288
+ } else {
289
+ env.worker = null;
290
+ }
291
+
292
+ return env;
293
+ }
294
+
295
+ /** Human-readable detection summary (for `detect` / existing-mode display). */
296
+ function renderDetection(env) {
297
+ const lines = [];
298
+ if (env.gpu && env.gpu.name) {
299
+ lines.push(`GPU: ${env.gpu.name}${env.gpu.vram_mib ? ` (${Math.round(env.gpu.vram_mib / 1024)} GB VRAM)` : ''} [${env.gpu.vendor}]`);
300
+ } else {
301
+ lines.push('GPU: not detected');
302
+ }
303
+ if (env.device === 'cpu') {
304
+ lines.push('Device: CPU-only mode');
305
+ if (env.gpu && env.gpu.vendor === 'amd') {
306
+ lines.push(' Note: an AMD GPU was detected, but the installer provides no ROCm/accelerated runtime branch yet — CPU mode will be used.');
307
+ }
308
+ lines.push(' Warning: performance will be SIGNIFICANTLY lower than GPU. Suitable for the TTS/audio profile test, not for image/video generation.');
309
+ } else {
310
+ lines.push('Device: CUDA (NVIDIA GPU acceleration)');
311
+ }
312
+ if (env.cuda) lines.push(`CUDA: ${env.cuda}`);
313
+ if (env.comfyui && env.comfyui.present) {
314
+ lines.push(`ComfyUI: detected at ${env.root}`);
315
+ lines.push(` Version: ${env.comfyui.version || env.comfyui.tag || env.comfyui.commit || 'unknown'}`);
316
+ } else {
317
+ lines.push('ComfyUI: not detected');
318
+ }
319
+ lines.push(`Python: ${env.python ? env.python.version : 'not detected'}`);
320
+ lines.push(`Torch: ${env.torch ? env.torch.version : 'not detected'}`);
321
+ lines.push(`Node.js: ${env.nodejs ? env.nodejs.version : 'not detected'}`);
322
+ if (env.custom_nodes && env.custom_nodes.length > 0) {
323
+ lines.push(`Custom nodes: ${env.custom_nodes.length} found`);
324
+ }
325
+ if (env.models && env.models.length > 0) {
326
+ lines.push(`Models: ${env.models.length} files found`);
327
+ }
328
+ if (env.workflows && env.workflows.length > 0) {
329
+ lines.push(`Workflows: ${env.workflows.length} user workflow files found`);
330
+ }
331
+ if (env.worker && env.worker.bundle && env.worker.bundle.present) {
332
+ lines.push(`Worker: bundle present at ${env.worker.bundle.dir}`);
333
+ }
334
+ return lines.join('\n');
335
+ }
336
+
337
+ module.exports = {
338
+ MODEL_DIRS,
339
+ DEVICE_KINDS,
340
+ probeEnvironment,
341
+ probeGpu,
342
+ probeNvidiaGpu,
343
+ probeAmdGpu,
344
+ probeComfyui,
345
+ probeWorker,
346
+ parseEnvKeys,
347
+ renderDetection,
348
+ pythonBin,
349
+ };
@@ -0,0 +1,350 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Download progress — user-visible status for long downloads (ModelScope
5
+ * repos, single artifacts).
6
+ *
7
+ * Requirements:
8
+ * - the user must SEE that the download is running, which file, how much
9
+ * was downloaded, the speed and the ETA;
10
+ * - batch (repo) downloads also show aggregate progress;
11
+ * - DO NOT spam the log: on a TTY the active download occupies ONE
12
+ * in-place line, redrawn only when time/percent/file changed (never
13
+ * once per network chunk); in non-TTY environments throttled plain
14
+ * lines (time AND byte-delta based), no ANSI escapes;
15
+ * - a completed download collapses into ONE final "[✓]" line (deduped);
16
+ * - indeterminate downloads (no Content-Length) get a spinner + bytes;
17
+ * - terminal output goes through the shared term renderer when provided,
18
+ * so installer status lines and the progress line never overwrite each
19
+ * other, and everything shares ONE stream;
20
+ * - fully injectable (isTTY/write/log/term/now) for deterministic tests.
21
+ */
22
+
23
+ const { createTermRenderer } = require('./term');
24
+
25
+ /**
26
+ * "12", "1.2 GB", "512 MB", "800 KB"
27
+ */
28
+ function formatBytes(n) {
29
+ if (!Number.isFinite(n) || n < 0) return '?';
30
+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];
31
+ let v = n;
32
+ let i = 0;
33
+ while (v >= 1024 && i < units.length - 1) { v /= 1024; i += 1; }
34
+ if (i === 0) return `${Math.round(v)} ${units[i]}`;
35
+ return `${v >= 100 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;
36
+ }
37
+
38
+ /** 75 → "01:15", 3725 → "1:02:05" */
39
+ function formatEta(seconds) {
40
+ if (!Number.isFinite(seconds) || seconds < 0) return '--:--';
41
+ const s = Math.round(seconds);
42
+ const h = Math.floor(s / 3600);
43
+ const m = Math.floor((s % 3600) / 60);
44
+ const sec = s % 60;
45
+ const mm = String(m).padStart(2, '0');
46
+ const ss = String(sec).padStart(2, '0');
47
+ return h > 0 ? `${h}:${mm}:${ss}` : `${mm}:${ss}`;
48
+ }
49
+
50
+ /**
51
+ * "Downloading Qwen/.../file.safetensors 1.2 GB / 4.8 GB (25%) 12.3 MB/s ETA 05:12"
52
+ */
53
+ function renderProgressLine({ prefix = 'Downloading', label, received, total, rateBps = null, etaSeconds = null }) {
54
+ const parts = [`${prefix} ${label}`];
55
+ if (Number.isFinite(total) && total > 0) {
56
+ const pct = Math.min(100, Math.floor((received / total) * 100));
57
+ parts.push(`${formatBytes(received)} / ${formatBytes(total)} (${pct}%)`);
58
+ } else {
59
+ parts.push(formatBytes(received));
60
+ }
61
+ if (Number.isFinite(rateBps) && rateBps > 0) parts.push(`${formatBytes(rateBps)}/s`);
62
+ if (Number.isFinite(etaSeconds) && etaSeconds > 0) parts.push(`ETA ${formatEta(etaSeconds)}`);
63
+ return parts.join(' ');
64
+ }
65
+
66
+ const BAR_WIDTH = 20;
67
+
68
+ /** 0.68 → "[█████████████░░░░░░░]" (null when total unknown) */
69
+ function renderBar(received, total, width = BAR_WIDTH) {
70
+ if (!Number.isFinite(total) || total <= 0) return null;
71
+ const frac = Math.max(0, Math.min(1, received / total));
72
+ const filled = Math.min(width, Math.round(frac * width));
73
+ return `[${'█'.repeat(filled)}${'░'.repeat(width - filled)}]`;
74
+ }
75
+
76
+ /** Status markers: in-progress / done / failed. */
77
+ const MARK_OK = '[✓]';
78
+ const MARK_RUN = '[→]';
79
+ const MARK_FAIL = '[✗]';
80
+
81
+ function finalMarker(status) {
82
+ return status === 'failed' ? MARK_FAIL : MARK_OK;
83
+ }
84
+
85
+ function finalVerb(status) {
86
+ return status === 'skipped' ? 'Skipped'
87
+ : status === 'resumed' ? 'Resumed'
88
+ : status === 'failed' ? 'FAILED'
89
+ : 'Downloaded';
90
+ }
91
+
92
+ /**
93
+ * Create a progress reporter for one download step (single file or repo).
94
+ *
95
+ * @param {object} opts { isTTY, write, log, term, now, minIntervalMs, minDeltaBytes, minRedrawMs }
96
+ * - term: shared createTermRenderer() instance (preferred — one stream with
97
+ * installer status). When absent, a private renderer is built from
98
+ * isTTY/write, and permanent lines fall back to `log`.
99
+ * @returns reporter with beginRepo/fileSkipped/beginFile/onChunk/endFile/endRepo
100
+ */
101
+ function createProgressReporter(opts = {}) {
102
+ const {
103
+ isTTY = false,
104
+ write = null,
105
+ log = null,
106
+ term = null,
107
+ now = () => Date.now(),
108
+ minIntervalMs = 2000,
109
+ minDeltaBytes = 1 * 1024 * 1024,
110
+ minRedrawMs = 120,
111
+ } = opts;
112
+
113
+ const tty = term ? term.isTTY : !!isTTY;
114
+
115
+ const sinkWrite = write || (tty && typeof process !== 'undefined' && process.stdout && process.stdout.write
116
+ ? (s) => { try { process.stdout.write(s); } catch (_) { /* gone */ } }
117
+ : null);
118
+ const sinkLog = log && typeof log.info === 'function' ? (msg) => log.info(msg) : null;
119
+
120
+ const screen = term || (tty && sinkWrite
121
+ ? createTermRenderer({ isTTY: true, write: sinkWrite, now, minRedrawMs })
122
+ : null);
123
+
124
+ const state = {
125
+ repo: null, // { repository, filesTotal, filesDone, bytesTotal, bytesDone }
126
+ file: null, // { label, received, total, lastSampleAt, lastSampleBytes, rateBps, etaSeconds }
127
+ lastEmitAt: -Infinity,
128
+ lastEmitBytes: 0,
129
+ lastRedrawAt: -Infinity,
130
+ lastRedrawPct: null,
131
+ lastRedrawLabel: null,
132
+ };
133
+
134
+ // --- rendering ---------------------------------------------------------
135
+
136
+ const repoNote = () => (state.repo
137
+ ? ` ${state.repo.filesDone}/${state.repo.filesTotal} files`
138
+ : '');
139
+
140
+ /** The live status line (marker + bar + bytes + speed + ETA), or null. */
141
+ const renderActive = () => {
142
+ if (state.file) {
143
+ const f = state.file;
144
+ const note = repoNote();
145
+ if (Number.isFinite(f.total) && f.total > 0) {
146
+ const pct = Math.min(100, Math.floor((f.received / f.total) * 100));
147
+ const parts = [
148
+ `${MARK_RUN} Downloading ${f.label}`,
149
+ renderBar(f.received, f.total),
150
+ `${pct}%`,
151
+ `${formatBytes(f.received)} / ${formatBytes(f.total)}`,
152
+ ];
153
+ if (Number.isFinite(f.rateBps) && f.rateBps > 0) parts.push(`${formatBytes(f.rateBps)}/s`);
154
+ if (Number.isFinite(f.etaSeconds) && f.etaSeconds > 0) parts.push(`ETA ${formatEta(f.etaSeconds)}`);
155
+ return parts.join(' ') + note;
156
+ }
157
+ // indeterminate: spinner + current file + bytes so far
158
+ return `${MARK_RUN} Downloading ${f.label} ${screen ? screen.spinnerFrame() : '·'} ${formatBytes(f.received)}${note}`;
159
+ }
160
+ if (state.repo) {
161
+ return renderProgressLine({
162
+ prefix: `${MARK_RUN} Repo`,
163
+ label: `${state.repo.repository} (${state.repo.filesDone}/${state.repo.filesTotal} files)`,
164
+ received: state.repo.bytesDone,
165
+ total: state.repo.bytesTotal,
166
+ });
167
+ }
168
+ return null;
169
+ };
170
+
171
+ /** One final, permanent line per finished file/repo. */
172
+ const renderFinal = (marker, prefix, label, received, total) => renderProgressLine({
173
+ prefix: `${marker} ${prefix}`,
174
+ label,
175
+ received,
176
+ total,
177
+ });
178
+
179
+ // --- sinks -------------------------------------------------------------
180
+
181
+ /** Permanent line: via logger when available (archive + redaction),
182
+ * otherwise directly through the renderer (private-sink mode). */
183
+ const emitFinal = (line) => {
184
+ if (sinkLog) sinkLog(line);
185
+ else if (screen) screen.print(line);
186
+ };
187
+
188
+ const clearLive = () => {
189
+ if (screen) screen.clear();
190
+ state.lastRedrawAt = -Infinity;
191
+ state.lastRedrawPct = null;
192
+ state.lastRedrawLabel = null;
193
+ };
194
+
195
+ /** Throttle decision for non-TTY environments. */
196
+ const shouldEmit = (t, bytes) => {
197
+ if (state.lastEmitAt === -Infinity) return true;
198
+ if (t - state.lastEmitAt >= minIntervalMs && bytes - state.lastEmitBytes >= minDeltaBytes) return true;
199
+ return false;
200
+ };
201
+
202
+ /** TTY redraw decision: on meaningful change (percent/file) or time tick. */
203
+ const shouldRedraw = (t, pct, label) => {
204
+ if (state.lastRedrawAt === -Infinity) return true;
205
+ if (label !== state.lastRedrawLabel) return true;
206
+ if (pct !== null && pct !== state.lastRedrawPct) return true;
207
+ if (t - state.lastRedrawAt >= minRedrawMs) return true;
208
+ return false;
209
+ };
210
+
211
+ return {
212
+ /** Start a repo (batch) download: aggregate progress over its files. */
213
+ beginRepo({ repository, filesTotal, bytesTotal = null }) {
214
+ clearLive();
215
+ state.repo = {
216
+ repository: repository || 'repo',
217
+ filesTotal: filesTotal || 0,
218
+ filesDone: 0,
219
+ bytesTotal: Number.isFinite(bytesTotal) && bytesTotal > 0 ? bytesTotal : null,
220
+ bytesDone: 0,
221
+ };
222
+ state.file = null;
223
+ state.lastEmitAt = -Infinity;
224
+ state.lastEmitBytes = 0;
225
+ if (tty && screen) {
226
+ const line = renderActive();
227
+ if (line) screen.status(line, { force: true });
228
+ }
229
+ },
230
+
231
+ /** A file that did not need downloading: one "[✓]" line, aggregate count. */
232
+ fileSkipped(filePath, size = null) {
233
+ if (!state.repo) return;
234
+ state.repo.filesDone += 1;
235
+ if (Number.isFinite(size) && size > 0) state.repo.bytesDone += size;
236
+ state.lastEmitAt = -Infinity;
237
+ state.lastEmitBytes = 0;
238
+ emitFinal(renderProgressLine({
239
+ prefix: `${MARK_OK} Skipped`,
240
+ label: `${filePath} (already present)`,
241
+ received: Number.isFinite(size) && size > 0 ? size : 0,
242
+ total: Number.isFinite(size) && size > 0 ? size : null,
243
+ }));
244
+ },
245
+
246
+ /** Start tracking one file. */
247
+ beginFile(label, total = null) {
248
+ clearLive();
249
+ state.file = {
250
+ label,
251
+ received: 0,
252
+ total: Number.isFinite(total) && total > 0 ? total : null,
253
+ lastSampleAt: now(),
254
+ lastSampleBytes: 0,
255
+ rateBps: null,
256
+ etaSeconds: null,
257
+ };
258
+ state.lastEmitAt = now();
259
+ state.lastEmitBytes = 0;
260
+ if (tty && screen) {
261
+ const line = renderActive();
262
+ if (line) screen.status(line, { force: true });
263
+ }
264
+ },
265
+
266
+ /** Progress callback shape from io.http.download: { received, total }. */
267
+ onChunk({ received, total } = {}) {
268
+ const f = state.file;
269
+ if (!f) return;
270
+ if (Number.isFinite(received)) f.received = received;
271
+ if (Number.isFinite(total) && total > 0 && f.total === null) f.total = total;
272
+ const t = now();
273
+ const dt = t - f.lastSampleAt;
274
+ if (dt >= 400) {
275
+ const instant = (f.received - f.lastSampleBytes) / (dt / 1000);
276
+ // smoothed rate (EMA) so short stalls don't whipsaw the ETA
277
+ f.rateBps = f.rateBps === null ? instant : (f.rateBps * 0.6 + instant * 0.4);
278
+ if (Number.isFinite(f.rateBps) && f.rateBps > 0 && f.total) {
279
+ f.etaSeconds = (f.total - f.received) / f.rateBps;
280
+ }
281
+ f.lastSampleAt = t;
282
+ f.lastSampleBytes = f.received;
283
+ }
284
+ const line = renderActive();
285
+ if (!line) return;
286
+ if (tty && screen) {
287
+ // ONE in-place line; redraw on meaningful change or time tick —
288
+ // never once per network chunk.
289
+ const pct = Number.isFinite(f.total) && f.total > 0
290
+ ? Math.min(100, Math.floor((f.received / f.total) * 100))
291
+ : null;
292
+ if (shouldRedraw(t, pct, f.label)) {
293
+ state.lastRedrawAt = t;
294
+ state.lastRedrawPct = pct;
295
+ state.lastRedrawLabel = f.label;
296
+ if (pct === null) screen.nextSpinnerFrame();
297
+ screen.status(renderActive());
298
+ }
299
+ } else if (shouldEmit(t, f.received)) {
300
+ state.lastEmitAt = t;
301
+ state.lastEmitBytes = f.received;
302
+ if (sinkLog) sinkLog(line);
303
+ }
304
+ },
305
+
306
+ /** Finish the current file. Always emits ONE final (throttle-free) line. */
307
+ endFile({ status = 'downloaded', bytes = null } = {}) {
308
+ const f = state.file;
309
+ if (!f) return;
310
+ clearLive();
311
+ if (state.repo) {
312
+ state.repo.filesDone += 1;
313
+ const b = Number.isFinite(bytes) && bytes > 0 ? bytes : f.received;
314
+ if (b > 0) state.repo.bytesDone += b;
315
+ }
316
+ emitFinal(renderProgressLine({
317
+ prefix: `${finalMarker(status)} ${finalVerb(status)}`,
318
+ label: f.label,
319
+ received: f.received,
320
+ total: f.total,
321
+ }));
322
+ state.file = null;
323
+ state.lastEmitAt = -Infinity;
324
+ state.lastEmitBytes = 0;
325
+ },
326
+
327
+ /** Finish the repo download. */
328
+ endRepo({ status = 'downloaded' } = {}) {
329
+ clearLive();
330
+ if (state.repo) {
331
+ emitFinal(renderProgressLine({
332
+ prefix: `${finalMarker(status)} Repo ${status === 'failed' ? 'FAILED' : 'complete'}`,
333
+ label: `${state.repo.repository} (${state.repo.filesDone}/${state.repo.filesTotal} files)`,
334
+ received: state.repo.bytesDone,
335
+ total: state.repo.bytesTotal,
336
+ }));
337
+ }
338
+ state.repo = null;
339
+ state.file = null;
340
+ },
341
+ };
342
+ }
343
+
344
+ module.exports = {
345
+ formatBytes,
346
+ formatEta,
347
+ renderProgressLine,
348
+ renderBar,
349
+ createProgressReporter,
350
+ };