odant-work 1.0.25 → 1.0.27

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.
@@ -36,6 +36,14 @@ import crypto from 'node:crypto';
36
36
  import { spawn } from 'node:child_process';
37
37
  import { startHuggingFaceDownload, listHuggingFaceDownloads, registerLocalModelNode } from './huggingface.js';
38
38
  import { loadTrainerNetworkSettings, createNetworkFetch, downloadFileMultipart } from './downloader.js';
39
+ import {
40
+ localRuntimeDir,
41
+ localCacheDir,
42
+ modelWeightsDir,
43
+ modelClassFile,
44
+ migrateLocalModelsLayoutSync,
45
+ WEIGHT_FILE_EXT_RE,
46
+ } from './paths.js';
39
47
 
40
48
  export const HALOGEN_DEFAULT_PORT = Number(process.env.HALOGEN_API_PORT) || 8731;
41
49
  export const HALOGEN_DEFAULT_BASE_URL = process.env.HALOGEN_BASE_URL || `http://127.0.0.1:${HALOGEN_DEFAULT_PORT}/v1/chat/completions`;
@@ -467,16 +475,16 @@ export function computeHalogenMemoryPlan({
467
475
  ` --served-model-name halogen-qwen3.8-flash-next ^`,
468
476
  ` --profile ${kvSlots > 1 ? 'subagents' : 'default'} --context ${contextTokens} ^`,
469
477
  ` --npu-prefill on ^`,
470
- ` --cache-disk "MODELS\\Local\\#cache\\disk"`,
478
+ ` --cache-disk "MODELS\\Local\\$provider\\#cache\\disk"`,
471
479
  ].join('\n');
472
480
 
473
481
  const windowsGufoServicesCommand = [
474
- `gufo.exe serve --host 127.0.0.1 --port ${HALOGEN_DEFAULT_PORT} llm --model "MODELS\\Local\\Qwen3.8-Flash-Next\\#weights\\Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf" --served-model-name halogen-qwen3.8-flash-next --speculative mtp`,
475
- `gufo.exe serve asr --model "MODELS\\Local\\Qwen3-ASR-NPU\\#weights"`,
476
- `gufo.exe serve tts --model "MODELS\\Local\\Qwen3-TTS-NPU\\#weights"`,
477
- `gufo.exe serve embedding --model "MODELS\\Local\\Qwen3-Embedding-NPU\\#weights"`,
478
- `gufo.exe serve image --model "MODELS\\Local\\Flux2-Klein-NPU\\#weights"`,
479
- `gufo.exe serve decision --model "MODELS\\Local\\Decider-NPU\\#weights"`,
482
+ `gufo.exe serve --host 127.0.0.1 --port ${HALOGEN_DEFAULT_PORT} llm --model "MODELS\\Local\\Qwen3.8-Flash-Next\\$ai\\#weights\\Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf" --served-model-name halogen-qwen3.8-flash-next --speculative mtp`,
483
+ `gufo.exe serve asr --model "MODELS\\Local\\Qwen3-ASR-NPU\\$ai\\#weights"`,
484
+ `gufo.exe serve tts --model "MODELS\\Local\\Qwen3-TTS-NPU\\$ai\\#weights"`,
485
+ `gufo.exe serve embedding --model "MODELS\\Local\\Qwen3-Embedding-NPU\\$ai\\#weights"`,
486
+ `gufo.exe serve image --model "MODELS\\Local\\Flux2-Klein-NPU\\$ai\\#weights"`,
487
+ `gufo.exe serve decision --model "MODELS\\Local\\Decider-NPU\\$ai\\#weights"`,
480
488
  ].join('\n');
481
489
 
482
490
  const windowsStrataCommand = `strata launch --family qwen --model iq3_s --port ${HALOGEN_DEFAULT_PORT}`;
@@ -530,8 +538,11 @@ export function computeHalogenMemoryPlan({
530
538
  export function inspectWindowsHalogenEnvironment({ rootDir = process.cwd() } = {}) {
531
539
  const localAppData = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
532
540
  const systemRoot = process.env.SystemRoot || 'C:\\Windows';
541
+ const rtBase = localRuntimeDir(rootDir);
533
542
 
534
543
  const buboCandidates = [
544
+ path.join(rtBase, 'bubo', 'bin', 'bubo.exe'),
545
+ path.join(rtBase, 'bubo', 'bubo.exe'),
535
546
  path.join(rootDir, 'MODELS', 'Local', '#runtime', 'bubo', 'bin', 'bubo.exe'),
536
547
  path.join(rootDir, 'MODELS', 'Local', '#runtime', 'bubo', 'bubo.exe'),
537
548
  path.join(rootDir, 'MODELS', 'Halogen', '#runtime', 'bubo', 'bin', 'bubo.exe'),
@@ -544,10 +555,11 @@ export function inspectWindowsHalogenEnvironment({ rootDir = process.cwd() } = {
544
555
  ? (path.basename(path.dirname(buboExePath)).toLowerCase() === 'bin'
545
556
  ? path.dirname(path.dirname(buboExePath))
546
557
  : path.dirname(buboExePath))
547
- : path.join(rootDir, 'MODELS', 'Local', '#runtime', 'bubo');
558
+ : path.join(rtBase, 'bubo');
548
559
 
549
560
  const rocmCandidates = [
550
561
  process.env.BUBO_RUNTIME_DIR || '',
562
+ path.join(rtBase, 'bubo', 'runtime', 'rocm-10.0.0-gfx1151'),
551
563
  path.join(rootDir, 'MODELS', 'Local', '#runtime', 'bubo', 'runtime', 'rocm-10.0.0-gfx1151'),
552
564
  path.join(rootDir, 'MODELS', 'Halogen', '#runtime', 'bubo', 'runtime', 'rocm-10.0.0-gfx1151'),
553
565
  path.join(localAppData, 'Bubo', 'runtime', 'rocm-10.0.0-gfx1151'),
@@ -556,6 +568,7 @@ export function inspectWindowsHalogenEnvironment({ rootDir = process.cwd() } = {
556
568
 
557
569
  const manifestCandidates = [
558
570
  process.env.BUBO_MANIFEST || '',
571
+ path.join(modelWeightsDir(rootDir, 'Qwen3.8-Flash-Next', 'Local'), 'bubo-package.json'),
559
572
  path.join(rootDir, 'MODELS', 'Local', 'models', 'qwen38-flash-next-base-ud-q4-k-xl-v1', 'bubo-package.json'),
560
573
  path.join(rootDir, 'MODELS', 'Local', 'models', 'huihui-qwen38-flash-next-ud-q4-k-xl-v1', 'bubo-package.json'),
561
574
  path.join(rootDir, 'MODELS', 'Local', 'Qwen3.8-Flash-Next', '#weights', 'bubo-package.json'),
@@ -568,6 +581,8 @@ export function inspectWindowsHalogenEnvironment({ rootDir = process.cwd() } = {
568
581
  const buboManifestPath = manifestCandidates.find(p => fs.existsSync(p)) || null;
569
582
 
570
583
  const gufoCandidates = [
584
+ path.join(rtBase, 'gufo', 'gufo.exe'),
585
+ path.join(rtBase, 'bubo', 'bin', 'gufo.exe'),
571
586
  path.join(rootDir, 'MODELS', 'Local', '#runtime', 'gufo', 'gufo.exe'),
572
587
  path.join(rootDir, 'MODELS', 'Local', '#runtime', 'bubo', 'bin', 'gufo.exe'),
573
588
  path.join(rootDir, 'MODELS', 'Halogen', '#runtime', 'gufo', 'gufo.exe'),
@@ -579,6 +594,7 @@ export function inspectWindowsHalogenEnvironment({ rootDir = process.cwd() } = {
579
594
  const strataCandidates = [
580
595
  path.join(localAppData, 'Programs', 'Strata', 'strata.exe'),
581
596
  path.join(localAppData, 'Strata', 'strata.exe'),
597
+ path.join(rtBase, 'strata', 'strata.exe'),
582
598
  path.join(rootDir, 'MODELS', 'Local', '#runtime', 'strata', 'strata.exe'),
583
599
  path.join(rootDir, 'MODELS', 'Halogen', '#runtime', 'strata', 'strata.exe'),
584
600
  ];
@@ -789,6 +805,7 @@ function findLocalGgufModel(rootDir = process.cwd()) {
789
805
  if (!entry.isDirectory() || entry.name.startsWith('$') || entry.name.startsWith('#'))
790
806
  continue;
791
807
  const candidates = [
808
+ path.join(base, entry.name, '$ai', '#weights'),
792
809
  path.join(base, entry.name, '#weights'),
793
810
  path.join(base, entry.name),
794
811
  ];
@@ -819,7 +836,8 @@ export async function prepareWindowsBuboRuntime({
819
836
  fetchImpl = globalThis.fetch,
820
837
  spawnImpl = spawn,
821
838
  } = {}) {
822
- const runtimeRoot = path.join(rootDir, 'MODELS', 'Local', '#runtime');
839
+ migrateLocalModelsLayoutSync(rootDir);
840
+ const runtimeRoot = localRuntimeDir(rootDir);
823
841
  const buboDir = path.join(runtimeRoot, 'bubo');
824
842
  const rocmDir = path.join(buboDir, 'runtime', 'rocm-10.0.0-gfx1151');
825
843
  const modelsOutDir = path.join(rootDir, 'MODELS', 'Local');
@@ -1010,7 +1028,7 @@ export async function startHalogenBackend({
1010
1028
  }
1011
1029
 
1012
1030
  const winEnv = inspectWindowsHalogenEnvironment({ rootDir });
1013
- const cacheDir = path.join(rootDir, 'MODELS', 'Local', '#cache');
1031
+ const cacheDir = localCacheDir(rootDir);
1014
1032
  fs.mkdirSync(path.join(cacheDir, 'disk'), { recursive: true });
1015
1033
  fs.mkdirSync(path.join(cacheDir, 'slots'), { recursive: true });
1016
1034
 
@@ -1363,12 +1381,12 @@ export async function ensureHalogenModelNodes(rootDir = process.cwd(), { models
1363
1381
 
1364
1382
  const registered = [];
1365
1383
  for (const spec of targets) {
1366
- const weightsDir = path.join(rootDir, 'MODELS', 'Local', spec.nodeName, '#weights');
1384
+ const weightsDir = modelWeightsDir(rootDir, spec.nodeName, 'Local');
1367
1385
  if (onlyWithWeights) {
1368
1386
  let hasFiles = false;
1369
1387
  try {
1370
1388
  if (fs.existsSync(weightsDir)) {
1371
- hasFiles = fs.readdirSync(weightsDir).some(f => !f.endsWith('.part') && f !== 'hf-manifest.json');
1389
+ hasFiles = fs.readdirSync(weightsDir).some(f => !f.endsWith('.part') && f !== 'hf-manifest.json' && f !== 'download-state.json');
1372
1390
  }
1373
1391
  }
1374
1392
  catch { /* ignore */ }
@@ -1405,30 +1423,37 @@ export async function ensureHalogenModelNodes(rootDir = process.cwd(), { models
1405
1423
  * Проверить наличие скачанных весов и узлов `$ai` для каждой модели из `HALOGEN_MODELS_CATALOG` в `MODELS/Local/<nodeName>/#weights`.
1406
1424
  */
1407
1425
  export function inspectHalogenCatalogWithStatus(rootDir = process.cwd()) {
1408
- const activeDownloads = listHuggingFaceDownloads();
1426
+ migrateLocalModelsLayoutSync(rootDir);
1427
+ const activeDownloads = listHuggingFaceDownloads(rootDir);
1409
1428
  return HALOGEN_MODELS_CATALOG.map(spec => {
1410
- const localWeightsDir = path.join(rootDir, 'MODELS', 'Local', spec.nodeName, '#weights');
1411
- const legacyWeightsDir = path.join(rootDir, 'MODELS', 'Halogen', spec.nodeName, '#weights');
1412
- const weightsDir = fs.existsSync(localWeightsDir) || !fs.existsSync(legacyWeightsDir) ? localWeightsDir : legacyWeightsDir;
1429
+ const localWeightsDir = modelWeightsDir(rootDir, spec.nodeName, 'Local');
1430
+ const legacyLocalDir = path.join(rootDir, 'MODELS', 'Local', spec.nodeName, '#weights');
1431
+ const legacyHalogenDir = path.join(rootDir, 'MODELS', 'Halogen', spec.nodeName, '#weights');
1432
+ const weightsDir = fs.existsSync(localWeightsDir) ? localWeightsDir
1433
+ : (fs.existsSync(legacyLocalDir) ? legacyLocalDir
1434
+ : (fs.existsSync(legacyHalogenDir) ? legacyHalogenDir : localWeightsDir));
1413
1435
  let downloadedFiles = [];
1436
+ let hasPendingDownload = false;
1414
1437
  if (fs.existsSync(weightsDir)) {
1415
1438
  try {
1416
- downloadedFiles = fs.readdirSync(weightsDir)
1417
- .filter(f => !f.endsWith('.part') && f !== 'hf-manifest.json');
1439
+ const rawEntries = fs.readdirSync(weightsDir);
1440
+ hasPendingDownload = rawEntries.some(f => f.endsWith('.part') || f === 'download-state.json');
1441
+ downloadedFiles = rawEntries
1442
+ .filter(f => !f.endsWith('.part') && f !== 'hf-manifest.json' && f !== 'download-state.json' && !f.endsWith('.tmp'));
1418
1443
  }
1419
1444
  catch { /* ignore */ }
1420
1445
  }
1421
- const nodeConfigured = fs.existsSync(path.join(rootDir, 'MODELS', 'Local', spec.nodeName, '$ai', 'class.js'));
1446
+ const nodeConfigured = fs.existsSync(modelClassFile(rootDir, spec.nodeName, 'Local'));
1422
1447
  const activeJob = activeDownloads.find(d =>
1423
- d.status === 'downloading'
1448
+ (d.status === 'downloading' || d.status === 'paused' || d.status === 'failed')
1424
1449
  && (d.repoId === spec.hfRepo || d.folderName === spec.nodeName || d.modelPath === spec.path)
1425
1450
  ) || null;
1426
- const hasRealWeightFile = downloadedFiles.some(f => /\.(gguf|safetensors|hgn|hnpw|bin|onnx|pt|pth)$/i.test(f));
1451
+ const hasRealWeightFile = downloadedFiles.some(f => WEIGHT_FILE_EXT_RE.test(f));
1427
1452
  return {
1428
1453
  ...spec,
1429
1454
  nodeConfigured,
1430
1455
  weightsDir: path.relative(rootDir, weightsDir).replace(/\\/g, '/'),
1431
- weightsDownloaded: !activeJob && hasRealWeightFile,
1456
+ weightsDownloaded: !activeJob && !hasPendingDownload && hasRealWeightFile,
1432
1457
  downloadedFiles,
1433
1458
  activeDownload: activeJob,
1434
1459
  };
@@ -1461,7 +1486,7 @@ export async function downloadHalogenBundle({
1461
1486
  )
1462
1487
  : [...HALOGEN_MODELS_CATALOG];
1463
1488
 
1464
- const existingDownloads = listHuggingFaceDownloads();
1489
+ const existingDownloads = listHuggingFaceDownloads(rootDir);
1465
1490
  const jobs = [];
1466
1491
  let startedCount = 0;
1467
1492
  let alreadyActiveCount = 0;
@@ -21,6 +21,13 @@ import {
21
21
  mergeRanges,
22
22
  sumRangesBytes,
23
23
  } from './downloader.js';
24
+ import {
25
+ localRootDir,
26
+ modelDir as getModelDir,
27
+ modelWeightsDir as getModelWeightsDir,
28
+ migrateLocalModelsLayoutSync,
29
+ hasReadyWeightFilesSync,
30
+ } from './paths.js';
24
31
 
25
32
  const HF_ORIGIN = DEFAULT_HF_ORIGIN;
26
33
  const REPO_ID_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
@@ -1076,6 +1083,11 @@ async function writeDownloadStateSafe(stagingDir, job, extra = {}) {
1076
1083
  })),
1077
1084
  totalBytes: Number(job.totalBytes) || 0,
1078
1085
  downloadedBytes: Number(job.downloadedBytes) || 0,
1086
+ avgSpeedMBs: Number(job.avgSpeedMBs) || 0,
1087
+ stats: {
1088
+ baseBytes: Math.max(0, Number(job.statsBaseBytes) || 0),
1089
+ activeMs: Math.max(0, Math.round(Number(job.statsActiveMs) || 0)),
1090
+ },
1079
1091
  status: job.status,
1080
1092
  error: job.error || null,
1081
1093
  updatedAt: Date.now(),
@@ -1111,6 +1123,23 @@ function waitAbortable(ms, signal) {
1111
1123
  * Запустить прямую загрузку модели с Hugging Face в `MODELS/Local/<Имя>/#weights/`
1112
1124
  * с поддержкой докачки (`Range`), авто-ретраев при обрывах, паузы без потери скачанного и авто-созданием узла `$ai`.
1113
1125
  */
1126
+ /**
1127
+ * Время до конца загрузки. Базой служит устойчивая средняя скорость за всё время
1128
+ * скачивания, а не мгновенный 5-секундный замер: при просадке канала мгновенная
1129
+ * скорость занижает ETA в десятки раз (например, «осталось 318 ч» при 16 % за 3 ч).
1130
+ */
1131
+ export function computeDownloadEta({ remainingBytes = 0, avgBytesPerSec = 0, shortBytesPerSec = 0 } = {}) {
1132
+ const remaining = Math.max(0, Number(remainingBytes) || 0);
1133
+ const avg = Number(avgBytesPerSec) || 0;
1134
+ const short = Number(shortBytesPerSec) || 0;
1135
+ if (remaining <= 0)
1136
+ return 0;
1137
+ const basis = avg >= 1024 ? avg : short;
1138
+ if (basis <= 1024)
1139
+ return null;
1140
+ return Math.round(remaining / basis);
1141
+ }
1142
+
1114
1143
  export async function startHuggingFaceDownload({
1115
1144
  repoId,
1116
1145
  files = null,
@@ -1125,6 +1154,7 @@ export async function startHuggingFaceDownload({
1125
1154
  waitForCompletion = false,
1126
1155
  maxRetries = 20,
1127
1156
  retryBaseDelayMs = 3000,
1157
+ idleTimeoutMs,
1128
1158
  endpointUrl,
1129
1159
  proxyUrl,
1130
1160
  threads,
@@ -1168,9 +1198,12 @@ export async function startHuggingFaceDownload({
1168
1198
  const folderName = targetNodeName
1169
1199
  ? String(targetNodeName).replace(/[<>:"/\\|?*]/g, '-')
1170
1200
  : safeModelFolderName(cleanId, quant && selected.some(f => f.kind === 'gguf') ? quant : '');
1171
- const modelDir = path.join(rootDir, 'MODELS', safeProvider, folderName);
1172
- const weightsDir = path.join(modelDir, '#weights');
1173
- const stagingDir = path.join(rootDir, 'MODELS', safeProvider, '#downloads', folderName);
1201
+
1202
+ migrateLocalModelsLayoutSync(rootDir, { skipModels: new Set([folderName]) });
1203
+
1204
+ const modelDir = getModelDir(rootDir, folderName, safeProvider);
1205
+ const weightsDir = getModelWeightsDir(rootDir, folderName, safeProvider);
1206
+ const stagingDir = weightsDir;
1174
1207
  const primary = selected.find(f => f.name.endsWith('.gguf'))?.name
1175
1208
  || selected.find(f => f.name.endsWith('.safetensors') || f.name.endsWith('.hgn') || f.name.endsWith('.hnpw'))?.name
1176
1209
  || selected[0]?.name || '';
@@ -1178,7 +1211,33 @@ export async function startHuggingFaceDownload({
1178
1211
  const displayLabel = nodeMeta?.label
1179
1212
  || `${cleanId.split('/')[1] || cleanId}${quant && primary.endsWith('.gguf') ? ' (' + quant + ')' : ''}`;
1180
1213
 
1181
- await fsp.mkdir(stagingDir, { recursive: true });
1214
+ await fsp.mkdir(weightsDir, { recursive: true });
1215
+
1216
+ // Если осталась недокачанная старая папка в #downloads/<folderName>, аккуратно перенесём её в $ai/#weights
1217
+ const legacyStaging = path.join(rootDir, 'MODELS', safeProvider, '#downloads', folderName);
1218
+ if (fs.existsSync(legacyStaging))
1219
+ migrateLocalModelsLayoutSync(rootDir);
1220
+
1221
+ // Создаём узел $ai/class.js сразу внутри папки модели (неактивен, пока веса не докачаны)
1222
+ if (registerInWork && safeProvider === 'Local') {
1223
+ await registerLocalModelNode({
1224
+ rootDir,
1225
+ folderName,
1226
+ label: displayLabel,
1227
+ repoId: cleanId,
1228
+ model: nodeMeta?.model || '',
1229
+ protocol: nodeMeta?.protocol || '',
1230
+ icon: nodeMeta?.icon || '',
1231
+ modality: nodeMeta?.modality || repoMeta.modality || 'llm',
1232
+ capabilities: nodeMeta?.capabilities || repoMeta.capabilities || ['chat'],
1233
+ efforts: nodeMeta?.efforts || null,
1234
+ maxTokens: nodeMeta?.maxTokens,
1235
+ maxOutput: nodeMeta?.maxOutput,
1236
+ baseUrl: nodeMeta?.baseUrl,
1237
+ weightsDir,
1238
+ primaryFile: path.basename(primary),
1239
+ });
1240
+ }
1182
1241
 
1183
1242
  // Читаем предыдущий download-state.json (если был), чтобы не потерять карту диапазонов при докачке
1184
1243
  let prevState = {};
@@ -1240,6 +1299,14 @@ export async function startHuggingFaceDownload({
1240
1299
  const controller = new AbortController();
1241
1300
  let keepFilesOnAbort = true;
1242
1301
 
1302
+ // Статистика для честного ETA: база (уже скачано до старта) и накопленное «активное» время.
1303
+ // Переживает паузы и перезапуски сервера — хранится в download-state.json.
1304
+ const prevStats = (prevState && typeof prevState.stats === 'object' && prevState.stats) || null;
1305
+ const statsBaseBytes = prevStats && Number.isFinite(Number(prevStats.baseBytes))
1306
+ ? Number(prevStats.baseBytes)
1307
+ : initialDownloaded;
1308
+ const statsActiveMs = Math.max(0, Number(prevStats?.activeMs) || 0);
1309
+
1243
1310
  const job = {
1244
1311
  id: jobId,
1245
1312
  repoId: cleanId,
@@ -1264,7 +1331,11 @@ export async function startHuggingFaceDownload({
1264
1331
  totalBytes,
1265
1332
  progress: initialProgress,
1266
1333
  speedMBs: 0,
1334
+ avgSpeedMBs: 0,
1267
1335
  etaSeconds: null,
1336
+ lastDataAt: Date.now(),
1337
+ statsBaseBytes,
1338
+ statsActiveMs,
1268
1339
  retryAttempt: 0,
1269
1340
  retryError: '',
1270
1341
  startedAt: Date.now(),
@@ -1289,12 +1360,32 @@ export async function startHuggingFaceDownload({
1289
1360
  const runPromise = (async () => {
1290
1361
  const t0 = Date.now();
1291
1362
  const speedSamples = [];
1292
- let lastStateSave = 0;
1363
+ let lastStateSave = Date.now();
1364
+ let lastDataAt = Date.now();
1365
+ let downloadFinished = false;
1366
+ let stateWriteChain = Promise.resolve();
1367
+
1368
+ const scheduleStateSave = () => {
1369
+ if (downloadFinished)
1370
+ return;
1371
+ stateWriteChain = stateWriteChain.then(() => {
1372
+ if (downloadFinished)
1373
+ return;
1374
+ return writeDownloadStateSafe(weightsDir, job, { nodeMeta, registerInWork });
1375
+ }).catch(() => {});
1376
+ };
1293
1377
 
1294
1378
  const updateMetrics = (deltaBytes = 0) => {
1295
1379
  const now = Date.now();
1296
- if (deltaBytes > 0)
1380
+ if (deltaBytes > 0) {
1297
1381
  speedSamples.push([now, deltaBytes]);
1382
+ // Копим «активное» время передачи данных (простои ограничиваем минутой),
1383
+ // чтобы средняя скорость отражала реальный темп, а не 5-секундный всплеск.
1384
+ const gap = lastDataAt ? now - lastDataAt : 0;
1385
+ job.statsActiveMs = (Number(job.statsActiveMs) || 0) + Math.min(60000, Math.max(0, gap));
1386
+ lastDataAt = now;
1387
+ job.lastDataAt = now;
1388
+ }
1298
1389
  const cutoff = now - 5000;
1299
1390
  while (speedSamples.length && speedSamples[0][0] < cutoff)
1300
1391
  speedSamples.shift();
@@ -1313,16 +1404,25 @@ export async function startHuggingFaceDownload({
1313
1404
  const bytesPerSec = windowBytes / spanSec;
1314
1405
  job.speedMBs = +(bytesPerSec / (1024 * 1024)).toFixed(2);
1315
1406
 
1316
- if (job.totalBytes > 0 && bytesPerSec > 1024) {
1317
- const remaining = Math.max(0, job.totalBytes - job.downloadedBytes);
1318
- job.etaSeconds = Math.round(remaining / bytesPerSec);
1319
- }
1407
+ // Устойчивая средняя скорость с начала загрузки (переживает паузы и рестарты)
1408
+ const newBytes = Math.max(0, job.downloadedBytes - (Number(job.statsBaseBytes) || 0));
1409
+ const activeMs = Number(job.statsActiveMs) || 0;
1410
+ const avgBytesPerSec = activeMs >= 3000 ? newBytes / (activeMs / 1000) : 0;
1411
+ job.avgSpeedMBs = +(avgBytesPerSec / (1024 * 1024)).toFixed(2);
1412
+
1413
+ job.etaSeconds = computeDownloadEta({
1414
+ remainingBytes: job.totalBytes - job.downloadedBytes,
1415
+ avgBytesPerSec,
1416
+ shortBytesPerSec: bytesPerSec,
1417
+ });
1418
+
1320
1419
  const activeSec = (now - t0) / 1000;
1321
- job.lowSpeedWarning = activeSec >= 15 && job.speedMBs > 0 && job.speedMBs < 2 && !job.retryAttempt;
1420
+ const effectiveMBs = job.avgSpeedMBs > 0 ? job.avgSpeedMBs : job.speedMBs;
1421
+ job.lowSpeedWarning = activeSec >= 15 && effectiveMBs > 0 && effectiveMBs < 2 && !job.retryAttempt;
1322
1422
 
1323
1423
  if (now - lastStateSave >= 1500) {
1324
1424
  lastStateSave = now;
1325
- writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
1425
+ scheduleStateSave();
1326
1426
  }
1327
1427
  };
1328
1428
 
@@ -1356,6 +1456,7 @@ export async function startHuggingFaceDownload({
1356
1456
  signal: controller.signal,
1357
1457
  maxRetries,
1358
1458
  retryBaseDelayMs,
1459
+ idleTimeoutMs,
1359
1460
  fetchImpl: netFetch,
1360
1461
  onProgress: ({ downloadedBytes, totalBytes: fTotal, deltaBytes, ranges }) => {
1361
1462
  if (fTotal > 0 && !fileEntry.size)
@@ -1369,7 +1470,7 @@ export async function startHuggingFaceDownload({
1369
1470
  onRetry: ({ attempt, error }) => {
1370
1471
  job.retryAttempt = attempt;
1371
1472
  job.retryError = error;
1372
- writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
1473
+ scheduleStateSave();
1373
1474
  },
1374
1475
  });
1375
1476
 
@@ -1403,20 +1504,11 @@ export async function startHuggingFaceDownload({
1403
1504
  if (controller.signal.aborted)
1404
1505
  throw new Error('Загрузка приостановлена пользователем');
1405
1506
 
1406
- // Переносим готовые файлы из скрытой папки #downloads в целевую папку модели #weights
1407
- await fsp.mkdir(weightsDir, { recursive: true });
1408
- for (const fileEntry of job.files) {
1409
- const stagedFile = path.join(stagingDir, path.basename(fileEntry.name));
1410
- const destFile = path.join(weightsDir, path.basename(fileEntry.name));
1411
- try {
1412
- await fsp.rename(stagedFile, destFile);
1413
- }
1414
- catch {
1415
- await fsp.copyFile(stagedFile, destFile);
1416
- await fsp.unlink(stagedFile).catch(() => {});
1417
- }
1418
- }
1419
- await fsp.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
1507
+ // Скачивание шло сразу в `$ai/#weights/` — перенос между папками не требуется;
1508
+ // дожидаемся завершения фоновых записей состояния, удаляем служебный файл и пишем итоговый манифест.
1509
+ downloadFinished = true;
1510
+ await stateWriteChain;
1511
+ await fsp.rm(path.join(weightsDir, DOWNLOAD_STATE_FILE), { force: true }).catch(() => {});
1420
1512
 
1421
1513
  const manifestFile = path.join(weightsDir, 'hf-manifest.json');
1422
1514
  await fsp.writeFile(manifestFile, JSON.stringify({
@@ -1428,7 +1520,6 @@ export async function startHuggingFaceDownload({
1428
1520
  files: job.files,
1429
1521
  }, null, 2), 'utf-8');
1430
1522
 
1431
- // Регистрируем узел $ai/class.js только после полного завершения скачивания весов
1432
1523
  if (registerInWork && safeProvider === 'Local') {
1433
1524
  await registerLocalModelNode({
1434
1525
  rootDir,
@@ -1462,6 +1553,8 @@ export async function startHuggingFaceDownload({
1462
1553
  catch { /* ignore */ }
1463
1554
  }
1464
1555
  catch (err) {
1556
+ downloadFinished = true;
1557
+ await stateWriteChain;
1465
1558
  if (controller.signal.aborted) {
1466
1559
  job.status = keepFilesOnAbort ? 'paused' : 'cancelled';
1467
1560
  job.error = keepFilesOnAbort ? null : String(err?.message || err);
@@ -1473,10 +1566,14 @@ export async function startHuggingFaceDownload({
1473
1566
  job.etaSeconds = null;
1474
1567
  job.finishedAt = Date.now();
1475
1568
  if (controller.signal.aborted && !keepFilesOnAbort) {
1476
- await fsp.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
1569
+ await fsp.rm(path.join(weightsDir, DOWNLOAD_STATE_FILE), { force: true }).catch(() => {});
1570
+ for (const fileEntry of job.files)
1571
+ await fsp.rm(path.join(weightsDir, path.basename(fileEntry.name) + '.part'), { force: true }).catch(() => {});
1572
+ if (!hasReadyWeightFilesSync(weightsDir))
1573
+ await fsp.rm(modelDir, { recursive: true, force: true }).catch(() => {});
1477
1574
  }
1478
1575
  else {
1479
- await writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
1576
+ await writeDownloadStateSafe(weightsDir, job, { nodeMeta, registerInWork });
1480
1577
  }
1481
1578
  }
1482
1579
  })();
@@ -1494,32 +1591,58 @@ export function getHuggingFaceDownload(jobId) {
1494
1591
  }
1495
1592
 
1496
1593
  export function listHuggingFaceDownloads(rootDir = process.cwd()) {
1497
- const inMemory = [..._downloads.values()].map(e => ({ ...e.job }));
1594
+ const resolvedRoot = path.resolve(rootDir);
1595
+ const now = Date.now();
1596
+ const inMemory = [..._downloads.values()]
1597
+ .filter(e => path.resolve(e.job.rootDir || process.cwd()) === resolvedRoot)
1598
+ .map(e => {
1599
+ const snapshot = { ...e.job };
1600
+ const idleSec = Math.max(0, Math.round((now - Number(e.job.lastDataAt || e.job.startedAt || now)) / 1000));
1601
+ snapshot.idleSec = idleSec;
1602
+ snapshot.stalled = e.job.status === 'downloading' && idleSec >= 20;
1603
+ if (snapshot.stalled) {
1604
+ snapshot.speedMBs = 0;
1605
+ snapshot.lowSpeedWarning = false;
1606
+ }
1607
+ return snapshot;
1608
+ });
1609
+ const activeNames = new Set(inMemory.filter(j => j.status === 'downloading').map(j => j.folderName));
1610
+ migrateLocalModelsLayoutSync(rootDir, { skipModels: activeNames });
1611
+
1498
1612
  const seenFolders = new Set(inMemory.map(j => `${j.providerFolder}:${j.folderName}`));
1499
1613
 
1500
- // Подхватываем недокачанные папки из MODELS/Local/#downloads/* (включая оставшиеся после рестарта)
1501
- const downloadsRoot = path.join(rootDir, 'MODELS', 'Local', '#downloads');
1502
- if (fs.existsSync(downloadsRoot)) {
1614
+ // Подхватываем незавершённые загрузки из метапапок моделей: MODELS/Local/<Модель>/$ai/#weights/
1615
+ const localRoot = localRootDir(rootDir);
1616
+ if (fs.existsSync(localRoot)) {
1503
1617
  try {
1504
- const entries = fs.readdirSync(downloadsRoot, { withFileTypes: true });
1618
+ const entries = fs.readdirSync(localRoot, { withFileTypes: true });
1505
1619
  for (const e of entries) {
1506
- if (!e.isDirectory() || e.name.startsWith('.') || e.name.startsWith('_import_') || e.name.startsWith('_tar_import_'))
1620
+ if (!e.isDirectory() || e.name.startsWith('$') || e.name.startsWith('#') || e.name === 'models')
1507
1621
  continue;
1508
1622
  if (seenFolders.has(`Local:${e.name}`))
1509
1623
  continue;
1510
- const folderDir = path.join(downloadsRoot, e.name);
1624
+ const folderDir = getModelWeightsDir(rootDir, e.name, 'Local');
1625
+ if (!fs.existsSync(folderDir))
1626
+ continue;
1511
1627
  const stateFile = path.join(folderDir, DOWNLOAD_STATE_FILE);
1628
+ const hasStateFile = fs.existsSync(stateFile);
1512
1629
  let state = {};
1513
- if (fs.existsSync(stateFile)) {
1630
+ if (hasStateFile) {
1514
1631
  try { state = JSON.parse(fs.readFileSync(stateFile, 'utf-8')); }
1515
1632
  catch { /* ignore */ }
1516
1633
  }
1517
1634
  const dirFiles = fs.readdirSync(folderDir, { withFileTypes: true });
1635
+ const hasParts = dirFiles.some(f => f.isFile() && f.name.endsWith('.part'));
1636
+ if (!hasStateFile && !hasParts)
1637
+ continue;
1638
+ if (state.status === 'completed' && !hasParts)
1639
+ continue;
1640
+
1518
1641
  const stateFilesMap = new Map((Array.isArray(state.files) ? state.files : []).map(sf => [sf.name, sf]));
1519
1642
  let diskBytes = 0;
1520
1643
  const parsedFiles = [];
1521
1644
  for (const f of dirFiles) {
1522
- if (!f.isFile() || f.name === DOWNLOAD_STATE_FILE || f.name.endsWith('.tmp'))
1645
+ if (!f.isFile() || f.name === DOWNLOAD_STATE_FILE || f.name === 'hf-manifest.json' || f.name.endsWith('.tmp'))
1523
1646
  continue;
1524
1647
  try {
1525
1648
  const st = fs.statSync(path.join(folderDir, f.name));
@@ -1567,7 +1690,10 @@ export function listHuggingFaceDownloads(rootDir = process.cwd()) {
1567
1690
  totalBytes,
1568
1691
  progress,
1569
1692
  speedMBs: 0,
1693
+ avgSpeedMBs: Number(state.avgSpeedMBs) || 0,
1570
1694
  etaSeconds: null,
1695
+ idleSec: 0,
1696
+ stalled: false,
1571
1697
  startedAt: state.updatedAt || Date.now(),
1572
1698
  finishedAt: state.updatedAt || Date.now(),
1573
1699
  modelPath: `/MODELS/Local/${e.name}`,
@@ -1611,8 +1737,19 @@ export async function discardHuggingFaceDownload({ jobId = '', folderName = '',
1611
1737
  if (!targetFolder && key.startsWith('disk_'))
1612
1738
  targetFolder = key.slice(5);
1613
1739
  if (targetFolder) {
1614
- const stagingDir = path.join(rootDir, 'MODELS', 'Local', '#downloads', targetFolder);
1615
- await fsp.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
1740
+ const weightsDir = getModelWeightsDir(rootDir, targetFolder, 'Local');
1741
+ if (fs.existsSync(weightsDir)) {
1742
+ await fsp.rm(path.join(weightsDir, DOWNLOAD_STATE_FILE), { force: true }).catch(() => {});
1743
+ const files = await fsp.readdir(weightsDir).catch(() => []);
1744
+ for (const f of files) {
1745
+ if (f.endsWith('.part') || f.endsWith('.tmp'))
1746
+ await fsp.rm(path.join(weightsDir, f), { force: true }).catch(() => {});
1747
+ }
1748
+ if (!hasReadyWeightFilesSync(weightsDir))
1749
+ await fsp.rm(getModelDir(rootDir, targetFolder, 'Local'), { recursive: true, force: true }).catch(() => {});
1750
+ }
1751
+ const legacyDir = path.join(rootDir, 'MODELS', 'Local', '#downloads', targetFolder);
1752
+ await fsp.rm(legacyDir, { recursive: true, force: true }).catch(() => {});
1616
1753
  }
1617
1754
  return { ok: true, discarded: targetFolder || key };
1618
1755
  }
@@ -1635,9 +1772,12 @@ export async function resumeHuggingFaceDownload({
1635
1772
  const key = String(jobId || '');
1636
1773
  const entry = key ? _downloads.get(key) : null;
1637
1774
  const cleanFolder = String(folderName || entry?.job?.folderName || (key.startsWith('disk_') ? key.slice(5) : '')).trim();
1775
+ if (cleanFolder)
1776
+ migrateLocalModelsLayoutSync(rootDir, { skipModels: new Set() });
1777
+
1638
1778
  let state = {};
1639
1779
  if (cleanFolder) {
1640
- const stateFile = path.join(rootDir, 'MODELS', 'Local', '#downloads', cleanFolder, DOWNLOAD_STATE_FILE);
1780
+ const stateFile = path.join(getModelWeightsDir(rootDir, cleanFolder, 'Local'), DOWNLOAD_STATE_FILE);
1641
1781
  if (fs.existsSync(stateFile)) {
1642
1782
  try { state = JSON.parse(await fsp.readFile(stateFile, 'utf-8')); }
1643
1783
  catch { /* ignore */ }
@@ -11,6 +11,7 @@ import {
11
11
  searchHuggingFaceModels,
12
12
  inspectHuggingFaceRepo,
13
13
  startHuggingFaceDownload,
14
+ computeDownloadEta,
14
15
  getHuggingFaceDownload,
15
16
  listHuggingFaceDownloads,
16
17
  pauseHuggingFaceDownload,
@@ -176,6 +177,7 @@ export {
176
177
  searchHuggingFaceModels,
177
178
  inspectHuggingFaceRepo,
178
179
  startHuggingFaceDownload,
180
+ computeDownloadEta,
179
181
  getHuggingFaceDownload,
180
182
  listHuggingFaceDownloads,
181
183
  pauseHuggingFaceDownload,
@@ -90,13 +90,19 @@ export function releaseLocalEngineMemory() {
90
90
 
91
91
  function resolveWeightsDir(ai, rootDir = process.cwd()) {
92
92
  const modelId = String(ai?.id || ai?.label || ai?.model || 'Local-Model').split('/').pop();
93
- const weightsRel = ai?.weightsDir || ai?.DATA?.weightsDir || `MODELS/Local/${modelId}/#weights`;
93
+ const weightsRel = ai?.weightsDir || ai?.DATA?.weightsDir || `MODELS/Local/${modelId}/$ai/#weights`;
94
94
  const primary = path.resolve(rootDir, weightsRel);
95
95
  if (fs.existsSync(primary))
96
96
  return primary;
97
+ const canonical = path.resolve(rootDir, `MODELS/Local/${modelId}/$ai/#weights`);
98
+ if (fs.existsSync(canonical))
99
+ return canonical;
100
+ const legacy = path.resolve(rootDir, `MODELS/Local/${modelId}/#weights`);
101
+ if (fs.existsSync(legacy))
102
+ return legacy;
97
103
  const isHalogen = ai?.protocol === 'halogen' || String(ai?.path || ai?.short || '').startsWith('/MODELS/Halogen/');
98
104
  if (isHalogen) {
99
- const fallback06 = path.resolve(rootDir, 'MODELS/Local/Qwen3-0.6B/#weights');
105
+ const fallback06 = path.resolve(rootDir, 'MODELS/Local/Qwen3-0.6B/$ai/#weights');
100
106
  if (fs.existsSync(fallback06))
101
107
  return fallback06;
102
108
  }