odant-work 1.0.44 → 1.0.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "packageName": "odant-work",
3
- "version": "1.0.44",
3
+ "version": "1.0.45",
4
4
  "createdAt": 1794916599757,
5
- "updatedAt": 1794996008501,
5
+ "updatedAt": 1795000110204,
6
6
  "files": {
7
7
  "run.mjs": "f8918c612e8641e9beee06221be6680aa6fd21f25468451f2ac857fd51772266",
8
- "package.json": "22cdae1cef1c79fd4310b2b731135ba87cc65057a23b7e344819d0d923379aa6",
9
- "package-lock.json": "2d3c7fd629cdc802c83d8dd728206a96db9f247f10f95c0704c6ade8f48294cc",
8
+ "package.json": "5a4980630412d3cdf8ec03c7dbae1012e157700b95dd5788efaaba379514c838",
9
+ "package-lock.json": "40527abe8821ecce7daf6e6971d1782b9c9cd40874e79e7d4c835e60e2b4742f",
10
10
  "sources/client/class.js": "c3fb8f143fc83aaa2df1ddeddd412d2d4dfe88656578095babe2df34fb3b3922",
11
11
  "sources/client/field.js": "ffdd50fa8b6ec515cc42da5fca96658ff2b20e274601a1f926e0031372467a19",
12
12
  "sources/client/file.js": "667101d75fa30840370d5be232e518aaac7c1fd52ca05a12da560eef6c0848b0",
@@ -26,7 +26,7 @@
26
26
  "sources/data/objects.js": "23f51d5b00cd766fe27879b874738bc9bd9056bd6e27285fb7a52926c0dbc6a8",
27
27
  "sources/data/posting.js": "6595bb9ec632539ae7629504db327d25a491e61c1cdc598bb43d08ea0d45548d",
28
28
  "sources/data/print.js": "704f0f2fc80c6466a4196e4650d763150cf9b592eab14ea67ece85d51100107c",
29
- "sources/data/progress.md": "32deced42a54e6845a797b95245891bc0ee1c951c8b00493078931920ef54f1c",
29
+ "sources/data/progress.md": "9f99946a5379e7bb00013de00d7557a0071ab3d57761510a6395ec76fbc29be9",
30
30
  "sources/data/readme.md": "593fa2ae07aa91bc26d7542275da6953a9cd419240a9a49e00cb62fb9d5d8e36",
31
31
  "sources/data/reports.js": "0330f404860fe2589a7d46a2f0fe690ca23249bd841a062a26718742d4fd11d6",
32
32
  "sources/data/schema.js": "1c994f9adb76c156dc86601dd6b1046376b66549b041e1a58aa1727b5476bdbe",
@@ -177,15 +177,15 @@
177
177
  "sources/modules/trainer/dataset.js": "e631e1feda2958cf93436cb48a331958d7b029aa52bd42247865e87504b642f7",
178
178
  "sources/modules/trainer/downloader.js": "d9e96cb07e7bf64386558be8c2265c482af35a513f42954250add6d5fc87bdc4",
179
179
  "sources/modules/trainer/halogen.js": "f908f16f8481cdf22d3baff4890bc446c9791325123ee471359c9847b3bac899",
180
- "sources/modules/trainer/huggingface.js": "07619a97526076a66f97bf4aee5b541f8ebb57ecefb23c8992822bfb3260afbb",
181
- "sources/modules/trainer/index.js": "9068ff4b4b2d5458718623a46bc3b77d55ff5aa2b7d59bb745681615ba1615fe",
182
- "sources/modules/trainer/local-engine.js": "de5c1ec158d6c8775588b61752b6074f746b66746176d6b8b4194f89a463498a",
183
- "sources/modules/trainer/paths.js": "86d12a1f3a79127c2284a5e0eaf4f523fbf0f3aa8e13b92d8889ebf4fa5400f4",
180
+ "sources/modules/trainer/huggingface.js": "078026b38471378943f42fd43f119709187c80706606f152ff5b3a07c6dc7744",
181
+ "sources/modules/trainer/index.js": "0b73a81d4a56b15e0e40d27b6ed63b4494bc786c28e17353f88c4532b1aff6b3",
182
+ "sources/modules/trainer/local-engine.js": "b6831131a87a558165219c1005136e192690b2fdbaf14439b6ebabbf10b299bb",
183
+ "sources/modules/trainer/paths.js": "23b9764f451d50b4e5fb7197f4ac0970355919f83cb6dfca2501cec06be8dcc9",
184
184
  "sources/modules/trainer/providers.js": "56ffd2de03449ecaa13751a7e82c615cf5f84e6f02bb0b34c4432c3d85db28da",
185
185
  "sources/modules/trainer/runner.js": "328843672fe0c1bd7e8c35c2e25285c31a9f749e04814e64c32e8cae74086024",
186
186
  "sources/modules/trainer/tar-stream.js": "52f1739579a01818b53d04a93fd05a91c49a0716019f309a6fca951ba112794f",
187
187
  "sources/modules/trainer/transfer.js": "2c603d538e0f85e1794e2f304081fac136f0ff72f85d8b00c2141c7402b3a1fb",
188
- "sources/modules/trainer/worker/local_infer_worker.py": "59fe9812afb4cdadfdce7e9b5dba8b0eeee1305fc4b54572bd743207f8117432",
188
+ "sources/modules/trainer/worker/local_infer_worker.py": "b1778f413441bebe3dbe562a419a809b224eefa2e03d7fe9b7c0e8565de14145",
189
189
  "sources/modules/trainer/worker/unsloth_train.py": "7774d94ffa6f60eed20c57a8dfdc12621d5d9f74d594c605dff32ff70e321e33",
190
190
  "sources/modules/user-profile/user-profile.js": "5c8fd002809848b204aee83a44161375e8144bffcc048fde748f4f778162bbef",
191
191
  "sources/modules/user-profile/user-token.js": "3797685232684e9e80261a2e63f70cbff4ef1bcc3ded6f755800804e9848d7d9",
@@ -974,9 +974,9 @@
974
974
  "MODULES/Register/STRUCTS/Банковский счёт/$struct/class.js": "166ffafd1c7d1609b174ae7766e77842e6294c6902baabe787225a2eeb026cce",
975
975
  "MODULES/Register/STRUCTS/Единица измерения/$struct/class.js": "dd0982281ed782d23afd80d5985b79aa65c6acbe58dc080f943840ea798000b0",
976
976
  "MODULES/Register/STRUCTS/Паспорт/$struct/class.js": "4a50808e4db7741b0384a775177545d71686a680ccda7ef0ec68bf81f9c988b5",
977
- "MODELS/$ai/$folder/$class/$ai/class.js": "a10f16fa7695bb373cc236e039c1e82816ee12cc108420dfbf27995071afedd5",
977
+ "MODELS/$ai/$folder/$class/$ai/class.js": "fd9214a926ad7466d1ae17cec095ca46144d4db75112ec6b893140ca05f21fd2",
978
978
  "MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/class.js": "fe5ba834156495c28a34acd4b70a6b6b3bdfccb67ec7bf99e92a292afbb66d19",
979
- "MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js": "406746e8183345088859dbeecb737238249e57fb9d31f123862d06ff0b8439cf",
979
+ "MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js": "63647f1ace73d9e18d1bde8090f7ca90eca16228261f833d665b8c9c058f1723",
980
980
  "MODELS/$ai/$folder/$class/$ai/methods/chat/$method/class.js": "02fbb40d8ce93fbf568a6a8036c199e2af815be3d63d81f815aeb1da999db717",
981
981
  "MODELS/$ai/$folder/$class/$provider/class.js": "069073501b93a95bb9d77e59ce71e53c7a8bcab2564c391b551f68a2453ac486",
982
982
  "MODELS/$ai/$folder/$class/$provider/handlers/pages/form/provider/$handler/class.js": "8d327820cefd696d351ac4fa7998994039e4d57ef7a9f8ae297209e4dd1b0a9e",
@@ -20,6 +20,10 @@ const JSON_BODY_MAX = 16 * 1024 * 1024; // F28: JSON-ответ (картинк
20
20
 
21
21
  const REMOTE_BODY_MAX = 32 * 1024 * 1024; // R7 (8.35): бинарный ответ провайдера (WAV речи/распознавания)
22
22
 
23
+ // Один раз на процесс проверяем сигнатуру запущенного движка Halogen (:8731) —
24
+ // если висит старый bubo.exe с прежними флагами, он будет перезапущен с актуальными.
25
+ const _engineEnsurePromises = new Map();
26
+
23
27
  export default {
24
28
  icon: 'carbon:machine-learning-model',
25
29
  form: 'trainer',
@@ -229,6 +233,18 @@ export default {
229
233
  headers['X-Halogen-Guard'] = typeof options.halogenGuard === 'string' ? options.halogenGuard : 'watch';
230
234
  const url = new URL(isAnthropic ? anthropicUrl(ai.baseUrl) : ai.baseUrl);
231
235
  const transport = transportFor(url);
236
+ // Перед первым обращением к локальному движку сверяем сигнатуру запуска:
237
+ // старый bubo.exe (профиль subagents / latin-словарь) иначе тихо тормозит кириллицу.
238
+ if (isHalogenNode && typeof WORK?.ensureHalogenBackendRunning === 'function'
239
+ && /^(https?:\/\/)?(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/i.test(String(ai.baseUrl || ''))) {
240
+ const key = url.origin + '::' + String(ai?.model || '');
241
+ if (!_engineEnsurePromises.has(key)) {
242
+ _engineEnsurePromises.set(key, Promise.resolve()
243
+ .then(() => WORK.ensureHalogenBackendRunning({ baseUrl: ai.baseUrl, ai }))
244
+ .catch(() => null));
245
+ }
246
+ await _engineEnsurePromises.get(key);
247
+ }
232
248
  // Явный Content-Length (без Transfer-Encoding: chunked) — нативные локальные серверы вроде bubo.exe отклоняют chunked POST с 400 malformed request
233
249
  const payload = JSON.stringify(body);
234
250
  const reqHeaders = { ...headers, 'Content-Length': Buffer.byteLength(payload) };
@@ -224,6 +224,7 @@ export default {
224
224
  <div class="msg ok" ~if="notice">{{notice}}</div>
225
225
  <div class="msg err" ~if="error">{{error}}</div>
226
226
  <div class="msg info" ~if="provisionBanner">{{provisionBanner}}</div>
227
+ <div class="msg warn" ~if="weightsRepairLine">{{weightsRepairLine}}</div>
227
228
 
228
229
  <div class="grid-2" ~if="info">
229
230
  <div class="card">
@@ -312,6 +313,7 @@ export default {
312
313
  modelEnabled: true,
313
314
  testNoThinking: true,
314
315
  provisionBanner: '',
316
+ weightsRepair: null,
315
317
  testPrompt: 'Привет! Коротко в 3–4 предложениях расскажи, чем ты умеешь помогать в работе с документами, таблицами и кодом.',
316
318
  testTtsText: 'Привет! Локальный синтез речи платформы WORK работает.',
317
319
  testImagePrompt: 'Минималистичная светлая 3D-иконка офисного здания в стиле современного UI',
@@ -402,12 +404,32 @@ export default {
402
404
  return `Запущен (профиль ${prof}${npu})`;
403
405
  return `Автозапуск по первому запросу (профиль ${prof}${npu})`;
404
406
  },
407
+ get weightsRepairLine() {
408
+ const r = this.weightsRepair || this.info?.weightsRepair;
409
+ if (!r)
410
+ return '';
411
+ const reasons = Array.isArray(r.reasons) && r.reasons.length ? ` (${r.reasons.join('; ')})` : '';
412
+ if (r.active)
413
+ return `Автоматическая докачка недостающих файлов модели: ${Number(r.progress) || 0}%${reasons}`;
414
+ if (r.broken && r.status !== 'repaired')
415
+ return `Нарушена структура файлов модели${reasons}. Починка выполняется автоматически при первом обращении.`;
416
+ return '';
417
+ },
405
418
  get halogenSpeculationLine() {
406
419
  const setup = this.info?.engineSetup;
407
- const plan = setup?.plan || this.info?.speculation;
420
+ const plan = setup?.plan || setup?.running?.speculation || this.info?.speculation;
408
421
  if (!plan)
409
422
  return '';
410
- return plan.summary || (plan.enabled ? 'Активна (MTP + Draft Head)' : 'Отключена');
423
+ if (plan.summary)
424
+ return plan.summary;
425
+ if (plan.enabled || plan.mode === 'explicit' || plan.mode === 'weights-only') {
426
+ const parts = [
427
+ plan.mode === 'explicit' ? 'MTP включён' : 'MTP (по весам)',
428
+ plan.promptLookup ? 'Prompt Lookup вкл.' : 'Prompt Lookup выкл.',
429
+ ];
430
+ return parts.filter(Boolean).join(' · ');
431
+ }
432
+ return 'Отключена';
411
433
  },
412
434
  async attached() {
413
435
  await this.reload();
@@ -424,6 +446,8 @@ export default {
424
446
  inf = await this.$item.fetch('info');
425
447
  }
426
448
  this.info = inf;
449
+ if (inf?.weightsRepair)
450
+ this.weightsRepair = inf.weightsRepair;
427
451
  this.modelEnabled = inf?.enabled !== false && inf?.DATA?.enabled !== false;
428
452
  if (inf?.pythonProvision?.active && inf.pythonProvision.stage) {
429
453
  this.provisionBanner = inf.pythonProvision.stage + ' (выполняется один раз автоматически)';
@@ -540,6 +564,8 @@ export default {
540
564
  else if (st?.buboPrepare?.status === 'running' && st.buboPrepare.message) {
541
565
  this.provisionBanner = st.buboPrepare.message;
542
566
  }
567
+ if (st?.weightsRepair)
568
+ this.weightsRepair = st.weightsRepair;
543
569
  }
544
570
  catch { /* ignore */ }
545
571
  }, 1200);
@@ -571,8 +597,10 @@ export default {
571
597
  return;
572
598
  }
573
599
  const parts = [];
600
+ if (res.engineStartMs > 500)
601
+ parts.push(`Старт движка: ${(res.engineStartMs / 1000).toFixed(1)} с`);
574
602
  if (res.durationMs)
575
- parts.push(`Время: ${(res.durationMs / 1000).toFixed(2)} с`);
603
+ parts.push(`${res.engineStartMs > 500 ? 'Генерация' : 'Время'}: ${(res.durationMs / 1000).toFixed(2)} с`);
576
604
  if (res.ttftMs)
577
605
  parts.push(`TTFT: ${(res.ttftMs / 1000).toFixed(2)} с`);
578
606
  if (res.tokPerSec)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.44",
3
+ "version": "1.0.45",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -1,6 +1,13 @@
1
1
  # Прогресс: sources/data
2
2
 
3
3
  ## Последние изменения
4
+ - [~14:10, 18.11] Скорость и надёжность всех локальных моделей на Halo (GPU + NPU): сохранение структуры репозитория HF, ONNX-пара для embed/rerank, автопочинка уже скачанных весов и честные ошибки STT/TTS (`sources/modules/trainer/{huggingface,paths,index,local-engine}.js`, `sources/modules/trainer/worker/local_infer_worker.py`, `MODELS/$ai/$folder/$class/$ai/{class.js,handlers/pages/form/trainer/$handler/trainer.js}`, `tests/trainer-weights-layout.test.js`, `tests/halogen-speculation.test.js`, `odant-work@1.0.45`):
5
+ - **Репозиторий сохраняется как есть — с подпапками (`huggingface.js`):** вместо `path.basename(f.name)` загрузчик пишет файл по относительному пути репозитория (`speech_tokenizer/`, `transformer/`, `vae/`, `text_encoder/`, `tokenizer/`, `onnx/`, `mtp/`), из-за чего одноимённые `config.json` / `model.safetensors` из подпапок больше не затирают корневые файлы. Новая классификация `classifyRepoFileKind` считает **все** `.json` (`model_index.json`, `*.safetensors.index.json`, `preprocessor_config.json`, `scheduler_config.json`) конфигами, а `.onnx_data` — весами; служебные `README`/лицензии/картинки отсеиваются (`isUsefulRepoFile`), выход за пределы каталога блокируется (`safeRepoDestRel`).
6
+ - **Embed/Rerank идут на GPU/NPU через ONNX, с прозрачным фоллбэком (`huggingface.js`, `local-engine.js`, `local_infer_worker.py`):** при наличии пары `model.onnx` + `model.onnx_data` скачивается именно она (исполнение через `onnxruntime-directml` на iGPU/NPU), а `*.safetensors` остаются резервом для torch; дублирующие `pytorch_model.bin` не качаются. `packagesForModality` добавляет `torch` + `safetensors` к ONNX-набору, если torch-веса есть рядом, так что отказ DML-сессии не требует переустановки. Воркер больше не берёт «обрезанный» ONNX-граф без внешних данных (`_find_onnx_file`), а `_has_torch_weights` учитывает `.bin/.pt/.pth`.
7
+ - **Самопочинка уже скачанных моделей (`huggingface.js`, `index.js`, карточка модели):** дешёвая локальная эвристика `detectBrokenWeightsLayout` находит последствия старого «сплющивания» (перезаписанный конфигом токенизатора/Diffusers корневой `config.json`, шарды без `*.safetensors.index.json`, ONNX без `*.onnx_data`, компоненты Diffusers без `model_index.json`). При открытии карточки и при запуске теста модели недостающие файлы докачиваются в фоне строго по своим относительным путям (кулдаун 10 минут на модель, отключается `WORK_DISABLE_AUTO_REPAIR=1`), прогресс показывается строкой в карточке и в `trainer_provision_status`; `trainer_model_info` больше не падает на занятых файлах (`EBUSY`).
8
+ - **Честные ошибки речи и корректный замер холодного старта:** в `handle_stt`/`handle_tts` ошибка установленного пакета (`qwen-asr`, `qwen-tts`) больше не маскируется под «нет пакетов» — отдаётся реальный текст причины, из-за которого раньше запускался бесконечный переустанов; у Halogen-модели движок прогревается **до** замера, поэтому в карточке отдельно видно `Старт движка` и `Генерация` (а не «медленную генерацию» на 116 ГБ весов). Плюс одноразовая на процесс проверка сигнатуры запуска `bubo.exe` перед первым запросом (только `localhost`) — старый процесс с профилем `subagents` перезапускается с `--profile default --mtp-draft-vocab auto`.
9
+ - **Формат весов виден всегда (`paths.js`):** инспекция `$ai/#weights` сканирует компонентные подпапки (Diffusers, `onnx/`, `speech_tokenizer/`), поэтому у моделей с весами не в корне в карточке показывается реальный «Формат весов», а не пусто.
10
+ - **Тесты:** новый `tests/trainer-weights-layout.test.js` (7 проверок: классификация файлов, сохранение подпапок, выбор формата для TTS/embed/LLM, детектор поломок, реальная загрузка без затирания `config.json`); в `tests/halogen-speculation.test.js` добавлена проверка №11 (ONNX без `*.onnx_data` не считается рабочим). Тренерские наборы — 63/63, `npm run check:secrets` — чисто.
4
11
  - [~15:30, 18.11] Исправление запуска всех вспомогательных локальных моделей без предустановленного `torch` (`sources/modules/trainer/worker/local_infer_worker.py`, `sources/modules/trainer/local-engine.js`, `tests/halogen-speculation.test.js`):
5
12
  - **Защита импорта воркера от `torch = None`:** декораторы `@torch.inference_mode()` на методах `LocalCausalLM` заменены на безопасный `@_inference_mode_dec()` — раньше при наличии системного Python без `torch` воркер падал на строке 161 (`AttributeError: 'NoneType' object has no attribute 'inference_mode'`) до выхода в цикл JSON-протокола, из-за чего не срабатывало авторазвёртывание среды и падали все доп. сети (`Qwen3-0.6B`, `bge-reranker-v2-m3`, `bge-m3`, `Z-Image-Turbo`, `Qwen3-TTS`, `Qwen3-ASR`).
6
13
  - **Гарантированный автоподъём Python 3.11 + пакетов и UTF-8 на Windows:** `_best_device_and_dtype()`, `_load_embed_model()` и `_load_rerank_model()` при отсутствии `torch`/`onnxruntime` корректно отдают `missingDeps`; в `ensureLocalPythonRuntime()` для `uv` всегда используется изолированный управляемый Python 3.11 (без конфликта с `py.exe` или системным Python 3.13/3.14); воркеру передаются `PYTHONUTF8=1` и `PYTHONIOENCODING=utf-8` (без кракозябр в кириллических путях), добавлен `accelerate` в `packagesForModality('tts'/'stt')`, а таймауты холодного старта `embed`/`rerank`/`tts`/`stt`/`image` увеличены до 3–6 минут.
@@ -906,21 +906,17 @@ export async function inspectHuggingFaceRepo(repoId, {
906
906
  .map(s => {
907
907
  const name = String(s.rfilename || s.path || '');
908
908
  const size = Number(s.size ?? s.lfs?.size ?? 0);
909
- const ext = path.extname(name).toLowerCase();
910
909
  const quant = extractQuantTag(name);
911
910
  return {
912
911
  name,
913
912
  size,
914
913
  sizeGb: +(size / (1024 ** 3)).toFixed(2),
915
914
  sizeFormatted: formatBytes(size),
916
- kind: ext === '.gguf' ? 'gguf'
917
- : ext === '.safetensors' || ext === '.bin' || ext === '.hgn' || ext === '.hnpw' || ext === '.onnx' ? 'safetensors'
918
- : /\b(config|tokenizer|adapter|special_tokens|generation_config|merges|vocab|preprocessor)\b/i.test(name) ? 'config'
919
- : 'other',
915
+ kind: classifyRepoFileKind(name),
920
916
  quant,
921
917
  };
922
918
  })
923
- .filter(f => f.name && !/^\.git/i.test(f.name) && !/^README|^LICENSE/i.test(f.name));
919
+ .filter(f => isUsefulRepoFile(f.name));
924
920
 
925
921
  const quants = [...new Set(files.filter(f => f.kind === 'gguf' && f.quant).map(f => f.quant))];
926
922
  const totalWeightBytes = files
@@ -990,10 +986,54 @@ export async function inspectHuggingFaceRepo(repoId, {
990
986
  };
991
987
  }
992
988
 
989
+ const CONFIG_FILE_EXTENSIONS = ['.json', '.txt', '.model', '.tiktoken', '.jinja', '.yaml', '.yml', '.py'];
990
+
991
+ /**
992
+ * Классификация файла репозитория HF по расширению (без `\b`-ловушек):
993
+ * - `safetensors` включает `.onnx_data` (внешние тензоры ONNX), `.bin`, `.pt`, `.pth`, `.hgn`, `.hnpw`;
994
+ * - `config` — ВСЕ `.json` (`model_index.json`, `*.index.json`, `preprocessor_config.json`,
995
+ * `scheduler_config.json`, …), `.txt`, `.model`, `.tiktoken`, `.jinja` — в том числе в подпапках
996
+ * Diffusers (`transformer/`, `vae/`, `text_encoder/`, `tokenizer/`, `scheduler/`) и токенизаторов.
997
+ */
998
+ export function classifyRepoFileKind(name) {
999
+ const ext = path.extname(String(name || '')).toLowerCase();
1000
+ if (ext === '.gguf')
1001
+ return 'gguf';
1002
+ if (['.safetensors', '.bin', '.hgn', '.hnpw', '.onnx', '.onnx_data', '.pt', '.pth'].includes(ext))
1003
+ return 'safetensors';
1004
+ if (CONFIG_FILE_EXTENSIONS.includes(ext))
1005
+ return 'config';
1006
+ return 'other';
1007
+ }
1008
+
1009
+ /** Отсеять служебный мусор репозитория (README, лицензии, картинки, git-служебное). */
1010
+ export function isUsefulRepoFile(name) {
1011
+ const n = String(name || '');
1012
+ if (!n)
1013
+ return false;
1014
+ if (/^\.git/i.test(n) || /^\.gitattributes$/i.test(n))
1015
+ return false;
1016
+ if (/(^|\/)(README|LICENSE|NOTICE|CHANGELOG|CODE_OF_CONDUCT)(\.|$)/i.test(n))
1017
+ return false;
1018
+ if (/\.(md|png|jpg|jpeg|gif|svg|webp|bmp|mp4|webm|lock|ipynb)$/i.test(n))
1019
+ return false;
1020
+ return true;
1021
+ }
1022
+
1023
+ /** Безопасный относительный путь файла репозитория (сохраняет подпапки `speech_tokenizer/`, `transformer/`, `onnx/`, …). */
1024
+ export function safeRepoDestRel(name) {
1025
+ return String(name || '')
1026
+ .replace(/\\/g, '/')
1027
+ .split('/')
1028
+ .filter(p => p && p !== '.' && p !== '..')
1029
+ .join('/');
1030
+ }
1031
+
993
1032
  /**
994
- * Выбрать список файлов репозитория для скачивания (либо явно переданные `files`, либо подходящий `.gguf` по `quant`, либо `config` + `.safetensors`).
1033
+ * Выбрать список файлов репозитория для скачивания (либо явно переданные `files`,
1034
+ * либо подходящий `.gguf` по `quant`, либо `config` + веса).
995
1035
  */
996
- export function selectFilesToDownload(repoMeta, { files = null, quant = '' } = {}) {
1036
+ export function selectFilesToDownload(repoMeta, { files = null, quant = '', modality = '' } = {}) {
997
1037
  const all = Array.isArray(repoMeta?.files) ? repoMeta.files : [];
998
1038
  if (Array.isArray(files) && files.length) {
999
1039
  const wanted = new Set(files.map(String));
@@ -1023,7 +1063,49 @@ export function selectFilesToDownload(repoMeta, { files = null, quant = '' } = {
1023
1063
  });
1024
1064
  }
1025
1065
  }
1026
- return all.filter(f => f.kind === 'config' || f.kind === 'safetensors');
1066
+
1067
+ // Прочие Halogen-репозитории с весами Linux (.hgn/.hnpw) без «v2»: берём их целиком + конфиги.
1068
+ const halogenWeights = all.filter(f => /\.(hgn|hnpw)$/i.test(f.name));
1069
+ if (halogenWeights.length) {
1070
+ return all.filter(f =>
1071
+ /\.(hgn|hnpw)$/i.test(f.name)
1072
+ || f.kind === 'config'
1073
+ || /tokenizer|vocab|merges|\.jinja/i.test(f.name));
1074
+ }
1075
+
1076
+ const configs = all.filter(f => f.kind === 'config');
1077
+ const safetensors = all.filter(f => /\.safetensors$/i.test(f.name));
1078
+ const torchBins = all.filter(f => /\.(bin|pt|pth)$/i.test(f.name));
1079
+ const onnxModels = all.filter(f => /\.onnx$/i.test(f.name));
1080
+ const onnxData = all.filter(f => /\.onnx_data$/i.test(f.name));
1081
+ const mod = String(modality || repoMeta?.modality || '').toLowerCase();
1082
+ const onnxWithData = onnxModels.filter(m => onnxData.some(d => d.name === `${m.name}_data`));
1083
+
1084
+ // Embed/Rerank: ONNX-пара (model.onnx + model.onnx_data) исполняется на iGPU/NPU через
1085
+ // onnxruntime-directml, поэтому предпочитаем её. PyTorch-веса оставляем как прозрачный
1086
+ // фоллбэк, если ONNX-сессия не поднимется.
1087
+ if (onnxWithData.length && (mod === 'embed' || mod === 'rerank')) {
1088
+ const picked = new Set(onnxWithData.map(m => m.name));
1089
+ for (const d of onnxData) {
1090
+ if ([...picked].some(n => `${n}_data` === d.name))
1091
+ picked.add(d.name);
1092
+ }
1093
+ const hasStFallback = safetensors.length > 0;
1094
+ return all.filter(f =>
1095
+ picked.has(f.name)
1096
+ || f.kind === 'config'
1097
+ || /\.safetensors$/i.test(f.name)
1098
+ || (!hasStFallback && /\.(bin|pt|pth)$/i.test(f.name)));
1099
+ }
1100
+ // Шардированные и обычные чекпоинты: только safetensors (индексы шардов — в configs).
1101
+ if (safetensors.length)
1102
+ return all.filter(f => f.kind === 'config' || /\.safetensors$/i.test(f.name));
1103
+ if (torchBins.length)
1104
+ return all.filter(f => f.kind === 'config' || /\.(bin|pt|pth)$/i.test(f.name));
1105
+ // Self-contained ONNX без внешних данных.
1106
+ if (onnxModels.length)
1107
+ return all.filter(f => f.kind === 'config' || /\.onnx(_data)?$/i.test(f.name));
1108
+ return configs;
1027
1109
  }
1028
1110
 
1029
1111
  /**
@@ -1289,7 +1371,7 @@ export async function startHuggingFaceDownload({
1289
1371
  proxyUrl: effProxy,
1290
1372
  fetchImpl,
1291
1373
  });
1292
- selected = selectFilesToDownload(repoMeta, { files, quant });
1374
+ selected = selectFilesToDownload(repoMeta, { files, quant, modality: nodeMeta?.modality || repoMeta.modality });
1293
1375
  }
1294
1376
  if (!selected.length)
1295
1377
  throw new Error(`В репозитории ${cleanId} не найдено подходящих файлов весов (.gguf / .safetensors)`);
@@ -1366,7 +1448,9 @@ export async function startHuggingFaceDownload({
1366
1448
  const jobFiles = [];
1367
1449
  for (const f of selected) {
1368
1450
  const size = Number(f.size) || 0;
1369
- const destRelPath = f.destRelPath || path.basename(f.name);
1451
+ // Сохраняем структуру репозитория (`speech_tokenizer/`, `transformer/`, `vae/`, `onnx/`, …),
1452
+ // иначе одноимённые config.json/model.safetensors из подпапок затирают корневые файлы.
1453
+ const destRelPath = f.destRelPath || safeRepoDestRel(f.name);
1370
1454
  const stagedFile = path.join(filesRootDir, destRelPath);
1371
1455
  const partFile = stagedFile + '.part';
1372
1456
  let downloaded = 0;
@@ -1402,7 +1486,7 @@ export async function startHuggingFaceDownload({
1402
1486
  jobFiles.push({
1403
1487
  name: f.name,
1404
1488
  ...(f.url ? { url: f.url } : {}),
1405
- ...(f.destRelPath ? { destRelPath: f.destRelPath } : {}),
1489
+ destRelPath,
1406
1490
  size: size || (done ? downloaded : 0),
1407
1491
  downloaded,
1408
1492
  done,
@@ -1723,7 +1807,7 @@ export async function startHuggingFaceDownload({
1723
1807
  if (controller.signal.aborted && !keepFilesOnAbort) {
1724
1808
  await fsp.rm(path.join(weightsDir, DOWNLOAD_STATE_FILE), { force: true }).catch(() => {});
1725
1809
  for (const fileEntry of job.files)
1726
- await fsp.rm(path.join(weightsDir, path.basename(fileEntry.name) + '.part'), { force: true }).catch(() => {});
1810
+ await fsp.rm(path.join(filesRootDir, fileEntry.destRelPath || path.basename(fileEntry.name)) + '.part', { force: true }).catch(() => {});
1727
1811
  if (!hasReadyWeightFilesSync(weightsDir))
1728
1812
  await fsp.rm(modelDir, { recursive: true, force: true }).catch(() => {});
1729
1813
  }
@@ -2104,3 +2188,316 @@ export function cancelHuggingFaceDownload(jobId, { keepFiles = false } = {}) {
2104
2188
  entry.job.finishedAt = Date.now();
2105
2189
  return { ...entry.job };
2106
2190
  }
2191
+
2192
+ /** Прочитать метаданные локальной модели из `MODELS/<Провайдер>/<Модель>/$ai/class.js`. */
2193
+ export function readLocalModelMetaSync(rootDir = process.cwd(), folderName = '', providerFolder = 'Local') {
2194
+ const safeName = String(folderName || '').trim();
2195
+ if (!safeName)
2196
+ return null;
2197
+ const aiDir = path.join(rootDir, 'MODELS', String(providerFolder || 'Local'), safeName, '$ai');
2198
+ const classFile = path.join(aiDir, 'class.js');
2199
+ if (!fs.existsSync(classFile))
2200
+ return null;
2201
+ try {
2202
+ const raw = fs.readFileSync(classFile, 'utf-8');
2203
+ const m = raw.match(/export\s+default\s+(\{[\s\S]*\})\s*;?\s*$/);
2204
+ const meta = JSON.parse(m ? m[1] : raw) || {};
2205
+ return {
2206
+ ...meta,
2207
+ aiDir,
2208
+ classFile,
2209
+ weightsDir: path.join(aiDir, '#weights'),
2210
+ };
2211
+ }
2212
+ catch {
2213
+ return null;
2214
+ }
2215
+ }
2216
+
2217
+ function listFilesRecursiveSync(dir, maxDepth = 5, base = dir, depth = 0, acc = []) {
2218
+ if (depth > maxDepth || !dir || !fs.existsSync(dir))
2219
+ return acc;
2220
+ let entries = [];
2221
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); }
2222
+ catch { return acc; }
2223
+ for (const ent of entries) {
2224
+ const abs = path.join(dir, ent.name);
2225
+ if (ent.isDirectory()) {
2226
+ listFilesRecursiveSync(abs, maxDepth, base, depth + 1, acc);
2227
+ }
2228
+ else if (ent.isFile() && !/\.(part|tmp)$/i.test(ent.name)) {
2229
+ acc.push(path.relative(base, abs).replace(/\\/g, '/'));
2230
+ }
2231
+ }
2232
+ return acc;
2233
+ }
2234
+
2235
+ /**
2236
+ * Быстрая (без сети) проверка целостности раскладки `$ai/#weights`.
2237
+ * Ловит типовые последствия старого сплющивания подпапок и пропущенных файлов:
2238
+ * перезаписанный `config.json` токенизатором, отсутствие `model_index.json` (Diffusers),
2239
+ * отсутствие индекса шардов и внешних данных ONNX (`*.onnx_data`).
2240
+ */
2241
+ export function detectBrokenWeightsLayout(weightsDir) {
2242
+ const reasons = [];
2243
+ if (!weightsDir || !fs.existsSync(weightsDir))
2244
+ return { broken: false, reasons, files: [] };
2245
+ const files = listFilesRecursiveSync(weightsDir);
2246
+ const hasRel = (rel) => files.includes(rel);
2247
+ const rootConfig = path.join(weightsDir, 'config.json');
2248
+ if (fs.existsSync(rootConfig)) {
2249
+ try {
2250
+ const cfg = JSON.parse(fs.readFileSync(rootConfig, 'utf-8')) || {};
2251
+ const mt = String(cfg.model_type || '');
2252
+ if (/_tokenizer|speech_tokenizer/i.test(mt) && !fs.existsSync(path.join(weightsDir, 'speech_tokenizer')))
2253
+ reasons.push(`config.json содержит конфиг токенизатора (model_type: ${mt}) вместо основной модели`);
2254
+ else if (cfg._class_name || cfg._diffusers_version)
2255
+ reasons.push('config.json содержит конфиг компонента Diffusers вместо model_index.json');
2256
+ }
2257
+ catch {
2258
+ reasons.push('config.json повреждён (некорректный JSON)');
2259
+ }
2260
+ }
2261
+ const hasShards = files.some(f => /(^|\/)[\w.-]+-\d{5}-of-\d{5}\.safetensors$/i.test(f));
2262
+ if (hasShards && !files.some(f => /\.safetensors\.index\.json$/i.test(f)))
2263
+ reasons.push('есть шарды весов, но нет индекса *.safetensors.index.json');
2264
+ const onnxFiles = files.filter(f => /\.onnx$/i.test(f));
2265
+ if (onnxFiles.length && !files.some(f => /\.onnx_data$/i.test(f))) {
2266
+ let graphSmall = false;
2267
+ for (const rel of onnxFiles) {
2268
+ try {
2269
+ const st = fs.statSync(path.join(weightsDir, rel));
2270
+ if (st.size > 0 && st.size < 512 * 1024 * 1024)
2271
+ graphSmall = true;
2272
+ }
2273
+ catch { /* ignore */ }
2274
+ }
2275
+ if (graphSmall)
2276
+ reasons.push('ONNX-граф без внешних данных *.onnx_data');
2277
+ }
2278
+ const componentDirs = ['transformer', 'vae', 'text_encoder', 'tokenizer', 'scheduler', 'unet']
2279
+ .filter(d => fs.existsSync(path.join(weightsDir, d)));
2280
+ if (componentDirs.length >= 2 && !hasRel('model_index.json'))
2281
+ reasons.push('нет model_index.json при наличии компонентов Diffusers');
2282
+ return { broken: reasons.length > 0, reasons, files };
2283
+ }
2284
+
2285
+ const _weightsRepairs = new Map();
2286
+ const _weightsRepairCooldown = new Map();
2287
+ const WEIGHTS_REPAIR_COOLDOWN_MS = 10 * 60 * 1000;
2288
+
2289
+ /** Текущее состояние автопочинки раскладки весов конкретной модели (для карточки/теста). */
2290
+ export function getWeightsRepairState(folderName) {
2291
+ const entry = _weightsRepairs.get(String(folderName || ''));
2292
+ if (!entry)
2293
+ return null;
2294
+ return {
2295
+ active: entry.active,
2296
+ reasons: entry.reasons,
2297
+ jobId: entry.jobId || '',
2298
+ status: entry.status,
2299
+ progress: entry.progress,
2300
+ error: entry.error || '',
2301
+ };
2302
+ }
2303
+
2304
+ /**
2305
+ * Автоматическая самопочинка уже скачанной папки `$ai/#weights`:
2306
+ * докачивает недостающие файлы строго по их относительным путям репозитория
2307
+ * (`speech_tokenizer/`, `transformer/`, `vae/`, `onnx/`, индексы шардов, `*.onnx_data`)
2308
+ * и убирает сплющенные в корень дубликаты, если их место — в подпапке.
2309
+ * Запускается фоново, один раз на модель, с кулдауном — без блокировки UI.
2310
+ */
2311
+ export async function repairLocalModelWeightsIfNeeded({
2312
+ rootDir = process.cwd(),
2313
+ folderName = '',
2314
+ providerFolder = 'Local',
2315
+ fetchImpl = globalThis.fetch,
2316
+ force = false,
2317
+ waitForCompletion = false,
2318
+ usableMemoryGb = 192,
2319
+ } = {}) {
2320
+ const safeName = String(folderName || '').trim();
2321
+ if (!safeName)
2322
+ return { repaired: false, reason: 'no_folder' };
2323
+ const existing = _weightsRepairs.get(safeName);
2324
+ if (existing?.active)
2325
+ return { repaired: false, reason: 'in_progress', state: getWeightsRepairState(safeName) };
2326
+ const last = _weightsRepairCooldown.get(safeName) || 0;
2327
+ if (!force && Date.now() - last < WEIGHTS_REPAIR_COOLDOWN_MS)
2328
+ return { repaired: false, reason: 'cooldown' };
2329
+
2330
+ const meta = readLocalModelMetaSync(rootDir, safeName, providerFolder);
2331
+ if (!meta?.hfRepo)
2332
+ return { repaired: false, reason: 'no_repo' };
2333
+ const weightsDir = meta.weightsDir;
2334
+ const quick = detectBrokenWeightsLayout(weightsDir);
2335
+ if (!quick.broken && !force)
2336
+ return { repaired: false, reason: 'layout_ok' };
2337
+
2338
+ // Не мешаем активной загрузке этой же модели.
2339
+ for (const [, entry] of _downloads.entries()) {
2340
+ if (entry.job?.folderName === safeName && entry.job.status === 'downloading')
2341
+ return { repaired: false, reason: 'download_active' };
2342
+ }
2343
+
2344
+ const state = {
2345
+ active: true,
2346
+ reasons: quick.reasons,
2347
+ jobId: '',
2348
+ status: 'checking',
2349
+ progress: 0,
2350
+ error: '',
2351
+ };
2352
+ _weightsRepairs.set(safeName, state);
2353
+
2354
+ const run = (async () => {
2355
+ try {
2356
+ const repoMeta = await inspectHuggingFaceRepo(meta.hfRepo, {
2357
+ rootDir,
2358
+ fetchImpl,
2359
+ usableMemoryGb,
2360
+ token: meta.hfToken || '',
2361
+ });
2362
+ const selected = selectFilesToDownload(repoMeta, { modality: meta.modality || repoMeta.modality });
2363
+ if (!selected.length)
2364
+ throw new Error(`Не удалось определить список файлов ${meta.hfRepo}`);
2365
+
2366
+ const repoPaths = new Set(selected.map(f => safeRepoDestRel(f.name)));
2367
+ const repoByBasename = new Map();
2368
+ for (const rel of repoPaths) {
2369
+ const base = path.basename(rel);
2370
+ if (!repoByBasename.has(base))
2371
+ repoByBasename.set(base, []);
2372
+ repoByBasename.get(base).push(rel);
2373
+ }
2374
+ const sizeOf = (rel) => {
2375
+ try { return fs.statSync(path.join(weightsDir, rel)).size; }
2376
+ catch { return -1; }
2377
+ };
2378
+ const wanted = [];
2379
+ for (const f of selected) {
2380
+ const rel = safeRepoDestRel(f.name);
2381
+ const localSize = sizeOf(rel);
2382
+ if (localSize < 0) {
2383
+ wanted.push(f.name);
2384
+ continue;
2385
+ }
2386
+ if (Number(f.size) > 0 && localSize !== Number(f.size)) {
2387
+ wanted.push(f.name);
2388
+ continue;
2389
+ }
2390
+ // Уже существующий, но «чужой» конфиг в корне (перезаписан токенизатором/Diffusers).
2391
+ if (/\.json$/i.test(rel) && rel === 'config.json') {
2392
+ const cfg = JSON.parse(fs.readFileSync(path.join(weightsDir, rel), 'utf-8') || '{}');
2393
+ const mt = String(cfg?.model_type || '');
2394
+ if (/_tokenizer|speech_tokenizer/i.test(mt) || cfg?._class_name || cfg?._diffusers_version)
2395
+ wanted.push(f.name);
2396
+ }
2397
+ }
2398
+
2399
+ // Убираем сплющенные дубликаты: корневой файл, которого нет в репозитории в корне,
2400
+ // но такой же по имени и размеру файл лежит в подпапке.
2401
+ const removed = [];
2402
+ for (const [base, rels] of repoByBasename) {
2403
+ if (rels.length < 2 || rels.includes(base))
2404
+ continue;
2405
+ const localSize = sizeOf(base);
2406
+ if (localSize < 0)
2407
+ continue;
2408
+ const nestedMatch = rels.find(rel => rel !== base && sizeOf(rel) === localSize);
2409
+ if (!nestedMatch)
2410
+ continue;
2411
+ try {
2412
+ fs.rmSync(path.join(weightsDir, base), { force: true });
2413
+ removed.push(base);
2414
+ }
2415
+ catch { /* ignore */ }
2416
+ }
2417
+
2418
+ if (!wanted.length && !removed.length) {
2419
+ state.active = false;
2420
+ state.status = 'ok';
2421
+ state.progress = 100;
2422
+ _weightsRepairCooldown.set(safeName, Date.now());
2423
+ return { repaired: false, reason: 'nothing_to_do' };
2424
+ }
2425
+
2426
+ state.status = 'downloading';
2427
+ state.reasons = [...new Set([...quick.reasons, ...(wanted.length ? [`докачка ${wanted.length} файл(ов)`] : [])])];
2428
+ const job = await startHuggingFaceDownload({
2429
+ repoId: meta.hfRepo,
2430
+ files: wanted,
2431
+ quant: meta.quant || '',
2432
+ rootDir,
2433
+ providerFolder,
2434
+ targetNodeName: safeName,
2435
+ nodeMeta: {
2436
+ modality: meta.modality || repoMeta.modality || 'llm',
2437
+ capabilities: meta.capabilities || repoMeta.capabilities || ['chat'],
2438
+ label: meta.label || safeName,
2439
+ },
2440
+ registerInWork: false,
2441
+ waitForCompletion,
2442
+ fetchImpl,
2443
+ token: meta.hfToken || '',
2444
+ });
2445
+ state.jobId = job?.id || '';
2446
+ const finalize = (finalJob) => {
2447
+ state.active = false;
2448
+ state.status = finalJob?.status === 'completed' ? 'repaired' : 'failed';
2449
+ state.progress = finalJob?.status === 'completed' ? 100 : (Number(finalJob?.progress) || 0);
2450
+ state.error = finalJob?.error ? String(finalJob.error) : '';
2451
+ _weightsRepairCooldown.set(safeName, Date.now());
2452
+ try {
2453
+ Promise.resolve(globalThis.WORK?.get_item?.(`/MODELS/${providerFolder}/${safeName}`))
2454
+ .then(node => node?.reset?.())
2455
+ .catch(() => {});
2456
+ }
2457
+ catch { /* ignore */ }
2458
+ };
2459
+ if (waitForCompletion) {
2460
+ finalize(job);
2461
+ try {
2462
+ const localNode = await globalThis.WORK?.get_item?.(`/MODELS/${providerFolder}/${safeName}`);
2463
+ localNode?.reset?.();
2464
+ }
2465
+ catch { /* ignore */ }
2466
+ }
2467
+ else if (state.jobId) {
2468
+ const timer = setInterval(() => {
2469
+ const cur = getHuggingFaceDownload(state.jobId);
2470
+ if (!cur) {
2471
+ clearInterval(timer);
2472
+ state.active = false;
2473
+ state.status = 'failed';
2474
+ state.error = 'загрузка потеряна';
2475
+ return;
2476
+ }
2477
+ state.progress = Number(cur.progress) || 0;
2478
+ if (cur.status !== 'downloading') {
2479
+ clearInterval(timer);
2480
+ finalize(cur);
2481
+ }
2482
+ }, 1500);
2483
+ timer.unref?.();
2484
+ }
2485
+ return { repaired: Boolean(wanted.length || removed.length), job, removed, reasons: state.reasons };
2486
+ }
2487
+ catch (err) {
2488
+ state.active = false;
2489
+ state.status = 'failed';
2490
+ state.error = String(err?.message || err);
2491
+ _weightsRepairCooldown.set(safeName, Date.now());
2492
+ return { repaired: false, reason: 'error', error: state.error };
2493
+ }
2494
+ })();
2495
+
2496
+ // Фоновый режим: не держим HTTP-запрос карточки, докачка видна в общем списке загрузок.
2497
+ if (!waitForCompletion)
2498
+ run.catch(() => {});
2499
+ const result = waitForCompletion ? await run : { started: true };
2500
+ return { ...result, state: getWeightsRepairState(safeName) };
2501
+ }
2502
+
2503
+
@@ -24,6 +24,10 @@ import {
24
24
  resumeInterruptedDownloads,
25
25
  cancelHuggingFaceDownload,
26
26
  registerLocalModelNode,
27
+ detectBrokenWeightsLayout,
28
+ repairLocalModelWeightsIfNeeded,
29
+ getWeightsRepairState,
30
+ readLocalModelMetaSync,
27
31
  } from './huggingface.js';
28
32
  import {
29
33
  buildWorkDataset,
@@ -247,6 +251,10 @@ export {
247
251
  resumeInterruptedDownloads,
248
252
  cancelHuggingFaceDownload,
249
253
  registerLocalModelNode,
254
+ detectBrokenWeightsLayout,
255
+ repairLocalModelWeightsIfNeeded,
256
+ getWeightsRepairState,
257
+ readLocalModelMetaSync,
250
258
  buildWorkDataset,
251
259
  listWorkDatasets,
252
260
  verifyCompletion,
@@ -378,6 +386,43 @@ function inferTestModality(ai) {
378
386
  async function runSingleModelSmokeTest(ai, p = {}) {
379
387
  await ai?.init?.catch?.(() => {});
380
388
  const modality = String(p.modality || inferTestModality(ai));
389
+ const modelFolder = String(ai?.id || '').trim();
390
+ if (modelFolder) {
391
+ // Раскладка весов могла быть сплющена старым загрузчиком (Qwen3-TTS, Z-Image-Turbo,
392
+ // Qwen3-ASR, BGE-M3): сначала автоматически докачиваем недостающие конфиги/индексы
393
+ // и внешние данные ONNX, и только потом запускаем тест.
394
+ try {
395
+ const layout = detectBrokenWeightsLayout(modelWeightsDir(process.cwd(), modelFolder, 'Local'));
396
+ if (layout.broken && process.env.WORK_DISABLE_AUTO_REPAIR !== '1') {
397
+ await repairLocalModelWeightsIfNeeded({ rootDir: process.cwd(), folderName: modelFolder, waitForCompletion: false });
398
+ const deadline = Date.now() + 90000;
399
+ while (Date.now() < deadline) {
400
+ const st = getWeightsRepairState(modelFolder);
401
+ if (!st?.active)
402
+ break;
403
+ await new Promise(r => setTimeout(r, 1000));
404
+ }
405
+ const st = getWeightsRepairState(modelFolder);
406
+ if (st?.active) {
407
+ return {
408
+ ok: false,
409
+ modality,
410
+ error: `Идёт автоматическая докачка файлов модели (${Number(st.progress) || 0}%). Повторите проверку через минуту — недостающие файлы скачаются сами.`,
411
+ weightsRepair: st,
412
+ };
413
+ }
414
+ if (st?.status === 'failed') {
415
+ return {
416
+ ok: false,
417
+ modality,
418
+ error: `Не удалось автоматически починить файлы модели: ${st.error || 'неизвестная ошибка'}`,
419
+ weightsRepair: st,
420
+ };
421
+ }
422
+ }
423
+ }
424
+ catch { /* тест не должен падать из-за проверки раскладки */ }
425
+ }
381
426
  const t0 = Date.now();
382
427
  try {
383
428
  if (modality === 'tts') {
@@ -460,7 +505,19 @@ async function runSingleModelSmokeTest(ai, p = {}) {
460
505
  : [{ role: 'user', content: String(p.prompt || 'Привет! Представься коротко в одном предложении.') }];
461
506
  const isHalo = ai?.protocol === 'halogen' || ai?.DATA?.protocol === 'halogen';
462
507
  const haloUrl = ai?.baseUrl || ai?.DATA?.baseUrl || HALOGEN_DEFAULT_BASE_URL;
508
+ // Холодный запуск bubo.exe (загрузка 116 ГБ весов) не должен выглядеть как медленная генерация:
509
+ // поднимаем движок заранее и замеряем это отдельно.
510
+ let engineStartMs = 0;
511
+ if (isHalo) {
512
+ const pre = await probeHalogenServer(haloUrl).catch(() => null);
513
+ if (!pre?.online) {
514
+ const startedAt = Date.now();
515
+ await ensureHalogenBackendRunning({ rootDir: process.cwd(), baseUrl: haloUrl, ai }).catch(() => null);
516
+ engineStartMs = Date.now() - startedAt;
517
+ }
518
+ }
463
519
  const metricsBefore = isHalo ? await readHalogenMetrics(haloUrl).catch(() => null) : null;
520
+ const genT0 = Date.now();
464
521
  const maxOut = Number(p.maxOutput || p.maxTokens) || 256;
465
522
  const chatOpts = {
466
523
  messages,
@@ -476,7 +533,7 @@ async function runSingleModelSmokeTest(ai, p = {}) {
476
533
  else if (chunk?.type === 'usage')
477
534
  usage = chunk;
478
535
  }
479
- const durationMs = Math.max(1, Date.now() - t0);
536
+ const durationMs = Math.max(1, Date.now() - genT0);
480
537
  const metricsAfter = isHalo ? await readHalogenMetrics(haloUrl).catch(() => null) : null;
481
538
  const metricsDelta = isHalo ? computeHalogenMetricsDelta(metricsBefore, metricsAfter) : null;
482
539
 
@@ -501,12 +558,15 @@ async function runSingleModelSmokeTest(ai, p = {}) {
501
558
  mtpAcceptPct,
502
559
  mtpTokensPerStep,
503
560
  usage,
561
+ engineStartMs,
562
+ totalMs: durationMs + engineStartMs,
504
563
  summary: [
505
564
  tokPerSec > 0 ? `${tokPerSec} tok/s` : `${durationMs} мс`,
506
565
  ttftMs > 0 ? `TTFT ${(ttftMs / 1000).toFixed(2)} с` : '',
507
566
  mtpAcceptPct !== null
508
567
  ? `MTP ${mtpAcceptPct}%${mtpTokensPerStep ? ` (${mtpTokensPerStep} ток/шаг)` : ''}`
509
568
  : '',
569
+ engineStartMs > 500 ? `старт движка ${(engineStartMs / 1000).toFixed(1)} с` : '',
510
570
  ].filter(Boolean).join(' · '),
511
571
  };
512
572
  }
@@ -606,7 +666,9 @@ export const TRAINER_METHODS = Object.freeze({
606
666
  const providerId = parts[1] || 'MODELS';
607
667
  const isLocal = providerId === 'Local' || d.protocol === 'local' || d.protocol === 'halogen';
608
668
  if (isLocal) {
609
- migrateLocalModelsLayoutSync(process.cwd());
669
+ // Миграция раскладки не должна ломать карточку модели (занятые файлы, EBUSY на Windows).
670
+ try { migrateLocalModelsLayoutSync(process.cwd()); }
671
+ catch { /* ignore */ }
610
672
  }
611
673
  const act = evaluateAiNodeActivitySync(this);
612
674
 
@@ -623,13 +685,17 @@ export const TRAINER_METHODS = Object.freeze({
623
685
  const configuredAbs = d.weightsDir ? path.resolve(process.cwd(), d.weightsDir) : '';
624
686
  const wDirAbs = fs.existsSync(canonicalWeightsAbs) ? canonicalWeightsAbs : (configuredAbs || canonicalWeightsAbs);
625
687
  resolvedWeightsRel = path.relative(process.cwd(), wDirAbs).replace(/\\/g, '/');
626
- weightInfo = inspectWeightsDirectorySync(wDirAbs, os.platform());
688
+ try { weightInfo = inspectWeightsDirectorySync(wDirAbs, os.platform()); }
689
+ catch { weightInfo = null; }
627
690
  if (resolvedPrimaryFile === 'bubo-package.json' || (!resolvedPrimaryFile && weightInfo?.hasGguf)) {
628
- const resolvedGguf = resolveBuboModelFiles(wDirAbs);
629
- if (resolvedGguf.mainModel)
630
- resolvedPrimaryFile = path.basename(resolvedGguf.mainModel);
691
+ try {
692
+ const resolvedGguf = resolveBuboModelFiles(wDirAbs);
693
+ if (resolvedGguf.mainModel)
694
+ resolvedPrimaryFile = path.basename(resolvedGguf.mainModel);
695
+ }
696
+ catch { /* ignore */ }
631
697
  }
632
- if (weightInfo.exists) {
698
+ if (weightInfo?.exists) {
633
699
  let bytes = 0;
634
700
  for (const f of weightInfo.files) {
635
701
  try {
@@ -639,10 +705,21 @@ export const TRAINER_METHODS = Object.freeze({
639
705
  }
640
706
  sizeGb = +(bytes / (1024 ** 3)).toFixed(2);
641
707
  }
708
+ // Формат весов всегда виден в карточке: если инспекция не распознала каталог,
709
+ // выводим его по фактическому основному файлу модели.
710
+ if (!weightInfo?.weightFormat && resolvedPrimaryFile) {
711
+ const ext = path.extname(resolvedPrimaryFile).replace('.', '').toLowerCase();
712
+ if (ext)
713
+ weightInfo = { ...(weightInfo || {}), weightFormat: ext };
714
+ }
642
715
  if (d.protocol === 'halogen' || weightInfo?.hasGguf || weightInfo?.hasBuboManifest) {
643
716
  halogenProbe = await probeHalogenServer(d.baseUrl || HALOGEN_DEFAULT_BASE_URL).catch(() => null);
644
- const winEnv = halogenProbe?.windowsEnv || inspectWindowsHalogenEnvironment();
645
- if (os.platform() === 'win32' && !halogenProbe?.online && !winEnv.buboInstalled && !winEnv.gufoInstalled) {
717
+ let winEnv = halogenProbe?.windowsEnv || null;
718
+ if (!winEnv) {
719
+ try { winEnv = inspectWindowsHalogenEnvironment(); }
720
+ catch { winEnv = null; }
721
+ }
722
+ if (os.platform() === 'win32' && !halogenProbe?.online && winEnv && !winEnv.buboInstalled && !winEnv.gufoInstalled) {
646
723
  needsRuntime = true;
647
724
  }
648
725
  }
@@ -655,6 +732,21 @@ export const TRAINER_METHODS = Object.freeze({
655
732
  ? await describeEngineSetup().catch(() => null)
656
733
  : null;
657
734
 
735
+ // Автопочинка раскладки весов: при открытии карточки модель сама проверяет
736
+ // целостность `$ai/#weights` и в фоне докачивает недостающее (подпапки Diffusers,
737
+ // speech_tokenizer, индексы шардов, внешние данные ONNX).
738
+ const modelFolder = String(this?.id || '').trim();
739
+ let weightsRepair = null;
740
+ if (isLocal && modelFolder) {
741
+ try {
742
+ const layout = detectBrokenWeightsLayout(modelWeightsDir(process.cwd(), modelFolder, 'Local'));
743
+ weightsRepair = { broken: layout.broken, reasons: layout.reasons, ...(getWeightsRepairState(modelFolder) || {}) };
744
+ if (layout.broken && process.env.WORK_DISABLE_AUTO_REPAIR !== '1')
745
+ repairLocalModelWeightsIfNeeded({ rootDir: process.cwd(), folderName: modelFolder }).catch(() => {});
746
+ }
747
+ catch { weightsRepair = null; }
748
+ }
749
+
658
750
  return {
659
751
  id: this?.id || '',
660
752
  label: d.label || this?.label || this?.id || '',
@@ -684,21 +776,34 @@ export const TRAINER_METHODS = Object.freeze({
684
776
  halogenOnline: Boolean(halogenProbe?.online),
685
777
  halogenMode: halogenProbe?.mode || '',
686
778
  halogenModeLabel: halogenProbe?.modeLabel || '',
687
- speculation: halogenProbe?.speculation || engineSetup?.plan || null,
779
+ speculation: engineSetup?.plan || halogenProbe?.speculation || null,
780
+ weightsRepair,
688
781
  engineSetup,
689
782
  engineSettings: (resolvedProtocol === 'halogen' || weightInfo?.hasGguf) ? readEngineSettings(process.cwd()) : null,
690
783
  pythonProvision: getPythonProvisionState(),
691
- windowsEnv: halogenProbe?.windowsEnv || null,
784
+ windowsEnv: halogenProbe?.windowsEnv || (() => { try { return inspectWindowsHalogenEnvironment(); } catch { return null; } })(),
692
785
  };
693
786
  },
694
787
  },
695
788
  trainer_provision_status: {
696
789
  level: 'read',
697
790
  fn: async function () {
698
- const winEnv = inspectWindowsHalogenEnvironment();
791
+ let winEnv = null;
792
+ try { winEnv = inspectWindowsHalogenEnvironment(); }
793
+ catch { winEnv = null; }
794
+ let weightsRepair = null;
795
+ const folder = String(this?.id || '').trim();
796
+ if (folder) {
797
+ try {
798
+ const layout = detectBrokenWeightsLayout(modelWeightsDir(process.cwd(), folder, 'Local'));
799
+ weightsRepair = { broken: layout.broken, reasons: layout.reasons, ...(getWeightsRepairState(folder) || {}) };
800
+ }
801
+ catch { weightsRepair = null; }
802
+ }
699
803
  return {
700
804
  python: getPythonProvisionState(),
701
805
  buboPrepare: winEnv?.prepareState || null,
806
+ weightsRepair,
702
807
  };
703
808
  },
704
809
  },
@@ -329,6 +329,17 @@ function resolvePythonCommandAsync(rootDir = process.cwd()) {
329
329
  return _pythonResolving;
330
330
  }
331
331
 
332
+ function hasTorchWeightsSync(weightsDir) {
333
+ if (!weightsDir || !fs.existsSync(weightsDir))
334
+ return false;
335
+ try {
336
+ return fs.readdirSync(weightsDir).some(f => /\.(safetensors|bin|pt|pth)$/i.test(f) && !f.endsWith('.part'));
337
+ }
338
+ catch {
339
+ return false;
340
+ }
341
+ }
342
+
332
343
  function hasOnnxModelSync(weightsDir) {
333
344
  if (!weightsDir || !fs.existsSync(weightsDir))
334
345
  return false;
@@ -347,7 +358,12 @@ export function packagesForModality(modality = 'llm', weightsDir = '') {
347
358
  const mod = String(modality || 'llm').toLowerCase();
348
359
  const hasOnnx = hasOnnxModelSync(weightsDir);
349
360
  if ((mod === 'embed' || mod === 'embedding' || mod === 'rerank') && hasOnnx) {
350
- return [os.platform() === 'win32' ? 'onnxruntime-directml' : 'onnxruntime', 'transformers', 'numpy'];
361
+ const pkgs = [os.platform() === 'win32' ? 'onnxruntime-directml' : 'onnxruntime', 'transformers', 'numpy'];
362
+ // PyTorch-веса лежат рядом как фоллбэк: если DML/NPU-сессия не поднимется,
363
+ // воркер прозрачно считает на torch, не требуя переустановки.
364
+ if (hasTorchWeightsSync(weightsDir))
365
+ pkgs.push('torch', 'safetensors');
366
+ return pkgs;
351
367
  }
352
368
  if (mod === 'embed' || mod === 'embedding' || mod === 'rerank')
353
369
  return ['torch', 'transformers', 'safetensors', 'accelerate'];
@@ -14,9 +14,15 @@ import fs from 'node:fs';
14
14
  import os from 'node:os';
15
15
  import path from 'node:path';
16
16
 
17
- export const WEIGHT_FILE_EXT_RE = /\.(gguf|safetensors|hgn|hnpw|bin|onnx|pt|pth)$/i;
17
+ export const WEIGHT_FILE_EXT_RE = /\.(gguf|safetensors|hgn|hnpw|bin|onnx|onnx_data|pt|pth)$/i;
18
18
  export const LINUX_ONLY_HALOGEN_EXT_RE = /\.(hgn|hnpw)$/i;
19
19
  export const WEIGHT_SIDECAR_SUBDIRS = Object.freeze(['mtp', 'mmproj', 'twin', 'draft_head']);
20
+ // Компоненты Diffusers/токенизаторов и ONNX-подпапка: веса лежат не в корне `#weights`.
21
+ export const WEIGHT_COMPONENT_SUBDIRS = Object.freeze([
22
+ 'transformer', 'vae', 'text_encoder', 'text_encoder_2', 'unet', 'tokenizer', 'tokenizer_2',
23
+ 'scheduler', 'onnx', 'speech_tokenizer', 'audio_encoder', 'decoder', 'prior',
24
+ ]);
25
+ const WEIGHT_SCANNED_SUBDIRS = [...WEIGHT_SIDECAR_SUBDIRS, ...WEIGHT_COMPONENT_SUBDIRS];
20
26
 
21
27
  function collectWeightDirRawEntriesSync(dirPath) {
22
28
  const out = [];
@@ -25,7 +31,7 @@ function collectWeightDirRawEntriesSync(dirPath) {
25
31
  if (ent.isFile()) {
26
32
  out.push(ent.name);
27
33
  }
28
- else if (ent.isDirectory() && WEIGHT_SIDECAR_SUBDIRS.includes(ent.name)) {
34
+ else if (ent.isDirectory() && WEIGHT_SCANNED_SUBDIRS.includes(ent.name)) {
29
35
  try {
30
36
  const subEntries = fs.readdirSync(path.join(dirPath, ent.name), { withFileTypes: true });
31
37
  for (const sub of subEntries) {
@@ -143,7 +149,7 @@ export function inspectWeightsDirectorySync(dirPath, platform = os.platform()) {
143
149
  const hasBuboManifest = files.includes('bubo-package.json');
144
150
  const hasHgn = files.some(f => f.toLowerCase().endsWith('.hgn'));
145
151
  const hasHnpw = files.some(f => f.toLowerCase().endsWith('.hnpw'));
146
- const hasOther = files.some(f => /\.(bin|onnx|pt|pth)$/i.test(f));
152
+ const hasOther = files.some(f => /\.(bin|onnx|onnx_data|pt|pth)$/i.test(f));
147
153
  const hasConfig = files.includes('config.json');
148
154
  const hasTokenizer = files.includes('tokenizer.json');
149
155
  const pendingDownload = hasParts || pendingState;
@@ -294,20 +294,48 @@ def _best_device_and_dtype():
294
294
  return "cpu", (torch.bfloat16 if _cpu_supports_bf16() else torch.float32)
295
295
 
296
296
 
297
+ def _onnx_external_data_ok(onnx_path):
298
+ """Внешние тензоры ONNX лежат рядом с графом (`model.onnx_data` / `model.onnx.data`)."""
299
+ return os.path.isfile(onnx_path + "_data") or os.path.isfile(onnx_path + ".data")
300
+
301
+
297
302
  def _find_onnx_file(weights_dir):
303
+ candidates = []
298
304
  for sub in ("", "onnx"):
299
305
  folder = os.path.join(weights_dir, sub) if sub else weights_dir
300
306
  if not os.path.isdir(folder):
301
307
  continue
302
308
  preferred = os.path.join(folder, "model.onnx")
303
309
  if os.path.isfile(preferred):
304
- return preferred
305
- found = sorted(glob.glob(os.path.join(folder, "*.onnx")))
306
- if found:
307
- return found[0]
310
+ candidates.append(preferred)
311
+ else:
312
+ found = sorted(glob.glob(os.path.join(folder, "*.onnx")))
313
+ candidates.extend(found)
314
+ for path in candidates:
315
+ try:
316
+ size = os.path.getsize(path)
317
+ except OSError:
318
+ continue
319
+ # Маленький ONNX-граф без файла внешних данных не загрузится — пропускаем,
320
+ # чтобы прозрачно использовать PyTorch-веса вместо падения на сессии.
321
+ if size < 512 * 1024 * 1024 and not _onnx_external_data_ok(path):
322
+ continue
323
+ return path
308
324
  return None
309
325
 
310
326
 
327
+ def _has_torch_weights(weights_dir):
328
+ patterns = ("*.safetensors", "*.bin", "*.pt", "*.pth")
329
+ for pattern in patterns:
330
+ if glob.glob(os.path.join(weights_dir, pattern)):
331
+ return True
332
+ for sub in ("transformer", "vae", "text_encoder"):
333
+ folder = os.path.join(weights_dir, sub)
334
+ if os.path.isdir(folder) and glob.glob(os.path.join(folder, "*.safetensors")):
335
+ return True
336
+ return False
337
+
338
+
311
339
  def _has_safetensors(weights_dir):
312
340
  return bool(glob.glob(os.path.join(weights_dir, "*.safetensors")))
313
341
 
@@ -408,7 +436,7 @@ def _load_embed_model(weights_dir, cache):
408
436
  cache[key] = ("onnx", tok, sess, "ort")
409
437
  return cache[key]
410
438
  except Exception:
411
- if not _has_safetensors(weights_dir) or not HAS_TORCH:
439
+ if not _has_torch_weights(weights_dir) or not HAS_TORCH:
412
440
  raise
413
441
  device, dtype = _best_device_and_dtype()
414
442
  try:
@@ -478,7 +506,7 @@ def _load_rerank_model(weights_dir, cache):
478
506
  cache[key] = ("onnx", tok, sess, "ort")
479
507
  return cache[key]
480
508
  except Exception:
481
- if not _has_safetensors(weights_dir) or not HAS_TORCH:
509
+ if not _has_torch_weights(weights_dir) or not HAS_TORCH:
482
510
  raise
483
511
  device, dtype = _best_device_and_dtype()
484
512
  try:
@@ -611,7 +639,14 @@ def handle_tts(req, cache):
611
639
  "soundfile": "soundfile",
612
640
  })))
613
641
  device, dtype = _best_device_and_dtype()
614
- mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=device, dtype=dtype)
642
+ try:
643
+ mdl = Qwen3TTSModel.from_pretrained(weights_dir, device_map=device, dtype=dtype)
644
+ except Exception as e:
645
+ # Пакет установлен, но веса/конфиг не читаются — отдаём реальную причину,
646
+ # а не ложное «нет пакетов», из-за которого раньше шёл бесконечный переустанов.
647
+ raise RuntimeError(json.dumps({
648
+ "error": f"Не удалось загрузить модель синтеза речи из {weights_dir}: {e}",
649
+ }))
615
650
  cache[key] = mdl
616
651
  mdl = cache[key]
617
652
  if hasattr(mdl, "generate_voice_design") and instructions:
@@ -631,22 +666,41 @@ def handle_stt(req, cache):
631
666
  raw = base64.b64decode(audio_b64)
632
667
  key = ("stt", weights_dir)
633
668
  if key not in cache:
634
- loader = None
669
+ device, dtype = _best_device_and_dtype()
670
+ errors = []
635
671
  try:
636
672
  from qwen_asr import Qwen3ASRModel
637
- device, dtype = _best_device_and_dtype()
638
- loader = ("qwen_asr", Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device))
639
- except Exception as e_qwen:
673
+ try:
674
+ cache[key] = ("qwen_asr", Qwen3ASRModel.from_pretrained(weights_dir, dtype=dtype, device_map=device))
675
+ except Exception as e:
676
+ errors.append(f"qwen-asr: {e}")
677
+ except Exception as e:
678
+ errors.append(f"qwen-asr (нет пакета): {e}")
679
+ if key not in cache:
640
680
  try:
641
681
  from transformers import pipeline
642
- device, dtype = _best_device_and_dtype()
643
- loader = ("hf_asr", pipeline("automatic-speech-recognition", model=weights_dir, device=0 if device == "cuda" else -1, torch_dtype=dtype))
644
- except Exception:
645
- raise RuntimeError(json.dumps(_missing_pkg_error(e_qwen, {
682
+ try:
683
+ cache[key] = ("hf_asr", pipeline(
684
+ "automatic-speech-recognition",
685
+ model=weights_dir,
686
+ device=0 if device == "cuda" else -1,
687
+ torch_dtype=dtype,
688
+ ))
689
+ except Exception as e:
690
+ errors.append(f"transformers: {e}")
691
+ except Exception as e:
692
+ errors.append(f"transformers (нет пакета): {e}")
693
+ if key not in cache:
694
+ msg = " | ".join(errors)
695
+ if "No module named" in msg:
696
+ raise RuntimeError(json.dumps(_missing_pkg_error(Exception(msg), {
646
697
  "qwen_asr": "qwen-asr",
647
698
  "soundfile": "soundfile",
699
+ "transformers": "transformers",
648
700
  })))
649
- cache[key] = loader
701
+ raise RuntimeError(json.dumps({
702
+ "error": f"Не удалось загрузить модель распознавания речи из {weights_dir}: {msg}",
703
+ }))
650
704
  kind, mdl = cache[key]
651
705
  import tempfile
652
706
  with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tf: