odant-work 1.0.29 → 1.0.31

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 (33) hide show
  1. package/#system/package-manifest.json +36 -30
  2. package/$server/$folder/$class/ai/agents/builder.md +34 -24
  3. package/$server/$folder/$class/ai/agents/org-architect.md +40 -0
  4. package/$server/$folder/$class/ai/agents/readme.md +3 -1
  5. package/$server/$folder/$class/ai/agents/schema-validator.md +35 -0
  6. package/$server/$folder/$class/ai/skills/accounting-design.md +21 -0
  7. package/$server/$folder/$class/ai/skills/data-modeling.md +25 -0
  8. package/$server/$folder/$class/ai/skills/readme.md +3 -0
  9. package/$server/$folder/$class/ai/skills/schema-migration.md +23 -0
  10. package/$server/$folder/$class/handlers/pages/form/objects/$handler/objects.js +2 -0
  11. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js +4 -0
  12. package/$server/$folder/lib/consultant/consultant.js +1 -1
  13. package/$server/$folder/lib/tree/tree.js +2 -1
  14. package/MODELS/$ai/$folder/$class/$ai/class.js +17 -3
  15. package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +103 -6
  16. package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +41 -16
  17. package/oda/components/layouts/editor-form/editor-form.js +16 -3
  18. package/package.json +1 -1
  19. package/sources/data/progress.md +20 -0
  20. package/sources/data/schema.js +66 -2
  21. package/sources/host/auto-updater.js +1 -1
  22. package/sources/modules/agent/index.js +4 -3
  23. package/sources/modules/agent/tools/work/classes.js +1081 -0
  24. package/sources/modules/agent/tools/work.js +1 -0
  25. package/sources/modules/trainer/halogen.js +532 -32
  26. package/sources/modules/trainer/huggingface.js +86 -6
  27. package/sources/modules/trainer/index.js +141 -3
  28. package/sources/modules/trainer/local-engine.js +26 -29
  29. package/sources/modules/trainer/paths.js +119 -0
  30. package/sources/modules/trainer/providers.js +60 -36
  31. package/sources/modules/trainer/runner.js +142 -31
  32. package/sources/server/class/security.js +10 -3
  33. package/sources/server/class.js +6 -0
@@ -42,6 +42,8 @@ import {
42
42
  modelWeightsDir,
43
43
  modelClassFile,
44
44
  migrateLocalModelsLayoutSync,
45
+ inspectWeightsDirectorySync,
46
+ getFreeDiskSpaceGb,
45
47
  WEIGHT_FILE_EXT_RE,
46
48
  } from './paths.js';
47
49
 
@@ -81,6 +83,8 @@ export const HALOGEN_MODELS_CATALOG = Object.freeze([
81
83
  windowsBuboRepo: 'unsloth/Qwen3.8-Flash-Next-GGUF',
82
84
  windowsBuboTwinRepo: 'HaloForgeLabs/bubo-qwen3.8-flash-next',
83
85
  ggufFallbackRepo: 'unsloth/Qwen3.8-Flash-Next-GGUF',
86
+ platforms: ['linux', 'win32'],
87
+ windowsRamGb: 116.6,
84
88
  device: 'iGPU (Radeon 8060S/8065S · gfx1151)',
85
89
  modality: 'llm',
86
90
  maxTokens: 262144,
@@ -91,6 +95,7 @@ export const HALOGEN_MODELS_CATALOG = Object.freeze([
91
95
  efforts: ['off', 'low', 'medium', 'high'],
92
96
  capabilities: ['chat', 'stream', 'tools', 'functions', 'vision', 'effort', 'thinking', 'fork'],
93
97
  role: 'Основная агентская модель (`ai/config.js → model`): 180B MoE (Linux: Halogen 4.16 bpw / Windows: Halowin Bubo UD-Q4_K_XL + Dense Twin + MTP Draft Head, 57–94 tok/s decode, ~1415–1800 tok/s prefill)',
98
+ windowsRole: 'Основная агентская модель 180B MoE для Windows 11 Strix Halo через встроенный движок Halowin Bubo (UD-Q4_K_XL GGUF + MTP + Dense Twin + Vision, ~116.6 ГБ + ROCm 10.0)',
94
99
  },
95
100
  {
96
101
  nodeName: 'Qwen3.5-2B-NPU',
@@ -100,6 +105,7 @@ export const HALOGEN_MODELS_CATALOG = Object.freeze([
100
105
  baseUrl: 'http://127.0.0.1:8731/v1/chat/completions',
101
106
  model: 'qwen3.5-2b',
102
107
  hfRepo: 'peonist-ai/halogen-npu-qwen3.5-2b',
108
+ platforms: ['linux'],
103
109
  device: 'NPU (Ryzen AI 55 TOPS)',
104
110
  modality: 'llm',
105
111
  maxTokens: 32768,
@@ -116,6 +122,7 @@ export const HALOGEN_MODELS_CATALOG = Object.freeze([
116
122
  baseUrl: 'http://127.0.0.1:8731/v1/audio/transcriptions',
117
123
  model: 'qwen3-asr-1.7b',
118
124
  hfRepo: 'peonist-ai/halogen-npu-qwen3-asr-1.7b',
125
+ platforms: ['linux'],
119
126
  gufoService: 'asr',
120
127
  device: 'NPU (Ryzen AI 55 TOPS)',
121
128
  modality: 'audio',
@@ -133,6 +140,7 @@ export const HALOGEN_MODELS_CATALOG = Object.freeze([
133
140
  baseUrl: 'http://127.0.0.1:8731/v1/audio/speech',
134
141
  model: 'qwen3-tts-1.7b-customvoice',
135
142
  hfRepo: 'peonist-ai/halogen-npu-qwen3-tts-1.7b-customvoice',
143
+ platforms: ['linux'],
136
144
  gufoService: 'tts',
137
145
  device: 'NPU (Ryzen AI 55 TOPS)',
138
146
  modality: 'audio',
@@ -150,6 +158,7 @@ export const HALOGEN_MODELS_CATALOG = Object.freeze([
150
158
  baseUrl: 'http://127.0.0.1:8731/v1/images/generations',
151
159
  model: 'flux2-klein-4b',
152
160
  hfRepo: 'peonist-ai/halogen-npu-flux2-klein-4b',
161
+ platforms: ['linux'],
153
162
  gufoService: 'image',
154
163
  device: 'NPU (Ryzen AI 55 TOPS)',
155
164
  modality: 'image',
@@ -167,6 +176,7 @@ export const HALOGEN_MODELS_CATALOG = Object.freeze([
167
176
  baseUrl: 'http://127.0.0.1:8731/v1/embeddings',
168
177
  model: 'qwen3-embedding-0.6b',
169
178
  hfRepo: 'peonist-ai/halogen-npu-qwen3-embedding-0.6b',
179
+ platforms: ['linux'],
170
180
  gufoService: 'embedding',
171
181
  device: 'NPU (Ryzen AI 55 TOPS)',
172
182
  modality: 'embed',
@@ -184,6 +194,7 @@ export const HALOGEN_MODELS_CATALOG = Object.freeze([
184
194
  baseUrl: 'http://127.0.0.1:8731/v1/rerank',
185
195
  model: 'qwen3-reranker-0.6b',
186
196
  hfRepo: 'peonist-ai/halogen-npu-qwen3-reranker-0.6b',
197
+ platforms: ['linux'],
187
198
  device: 'NPU (Ryzen AI 55 TOPS)',
188
199
  modality: 'embed',
189
200
  maxTokens: 8192,
@@ -200,6 +211,7 @@ export const HALOGEN_MODELS_CATALOG = Object.freeze([
200
211
  baseUrl: 'http://127.0.0.1:8731/v1/systemone',
201
212
  model: 'decider-0.8b',
202
213
  hfRepo: 'peonist-ai/halogen-npu-decider-0.8b',
214
+ platforms: ['linux'],
203
215
  gufoService: 'decision',
204
216
  device: 'NPU (Ryzen AI 55 TOPS)',
205
217
  modality: 'llm',
@@ -211,6 +223,162 @@ export const HALOGEN_MODELS_CATALOG = Object.freeze([
211
223
  },
212
224
  ]);
213
225
 
226
+ /**
227
+ * 7 Windows-совместимых моделей-компаньонов (.safetensors) для комплекта Halo на Windows 11,
228
+ * заменяющих Linux-only `.hnpw` модели и работающих на встроенном движке WORK.
229
+ */
230
+ export const HALOGEN_WINDOWS_COMPANIONS = Object.freeze([
231
+ {
232
+ nodeName: 'Qwen3-4B',
233
+ label: 'Qwen3-4B (Быстрая LLM / Сжатие)',
234
+ icon: 'ai:qwen',
235
+ path: '/MODELS/Local/Qwen3-4B',
236
+ baseUrl: '',
237
+ model: 'Qwen/Qwen3-4B',
238
+ hfRepo: 'Qwen/Qwen3-4B',
239
+ protocol: 'local',
240
+ runtimeType: 'local',
241
+ device: 'Встроенный движок WORK (.safetensors)',
242
+ modality: 'llm',
243
+ maxTokens: 32768,
244
+ maxOutput: 8192,
245
+ ramGb: 3.5,
246
+ capabilities: ['chat', 'stream', 'tools', 'functions', 'thinking', 'lora'],
247
+ role: 'Быстрая модель для сжатия контекста (compactModel), сводок и локальных агентов без вымывания кэша основной 180B модели',
248
+ },
249
+ {
250
+ nodeName: 'Qwen3-ASR-1.7B',
251
+ label: 'Qwen3-ASR 1.7B (Распознавание речи)',
252
+ icon: 'carbon:microphone',
253
+ path: '/MODELS/Local/Qwen3-ASR-1.7B',
254
+ baseUrl: '',
255
+ model: 'Qwen/Qwen3-ASR-1.7B',
256
+ hfRepo: 'Qwen/Qwen3-ASR-1.7B',
257
+ protocol: 'local',
258
+ runtimeType: 'local',
259
+ device: 'Встроенный движок WORK (.safetensors)',
260
+ modality: 'audio',
261
+ maxTokens: 4096,
262
+ maxOutput: 2048,
263
+ ramGb: 2.0,
264
+ capabilities: ['stt', 'asr', 'lora'],
265
+ role: 'Потоковое распознавание русской и английской речи для голосового режима (sttModel)',
266
+ },
267
+ {
268
+ nodeName: 'Qwen3-TTS-12Hz-1.7B-VoiceDesign',
269
+ label: 'Qwen3-TTS 1.7B VoiceDesign (Голос)',
270
+ icon: 'carbon:volume-up',
271
+ path: '/MODELS/Local/Qwen3-TTS-12Hz-1.7B-VoiceDesign',
272
+ baseUrl: '',
273
+ model: 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign',
274
+ hfRepo: 'Qwen/Qwen3-TTS-12Hz-1.7B-VoiceDesign',
275
+ protocol: 'local',
276
+ runtimeType: 'local',
277
+ device: 'Встроенный движок WORK (.safetensors)',
278
+ modality: 'audio',
279
+ maxTokens: 4096,
280
+ maxOutput: 2048,
281
+ ramGb: 2.3,
282
+ capabilities: ['tts', 'voice', 'lora'],
283
+ role: 'Синтез живой русской и английской речи для озвучивания ответов агентов (ttsModel)',
284
+ },
285
+ {
286
+ nodeName: 'Z-Image-Turbo',
287
+ label: 'Z-Image-Turbo 6B (Картинки)',
288
+ icon: 'ai:stablediffusion',
289
+ path: '/MODELS/Local/Z-Image-Turbo',
290
+ baseUrl: '',
291
+ model: 'Tongyi-MAI/Z-Image-Turbo',
292
+ hfRepo: 'Tongyi-MAI/Z-Image-Turbo',
293
+ protocol: 'local',
294
+ runtimeType: 'local',
295
+ device: 'Встроенный движок WORK (.safetensors)',
296
+ modality: 'image',
297
+ maxTokens: 4096,
298
+ maxOutput: 1024,
299
+ ramGb: 7.5,
300
+ capabilities: ['image', 'text-to-image', 'lora'],
301
+ role: 'Генерация иллюстраций, фото товаров для Номенклатуры и слайдов презентаций (imageModel)',
302
+ },
303
+ {
304
+ nodeName: 'bge-m3',
305
+ label: 'BGE-M3 (Эмбеддинги RAG)',
306
+ icon: 'carbon:search-locate',
307
+ path: '/MODELS/Local/bge-m3',
308
+ baseUrl: '',
309
+ model: 'BAAI/bge-m3',
310
+ hfRepo: 'BAAI/bge-m3',
311
+ protocol: 'local',
312
+ runtimeType: 'local',
313
+ device: 'Встроенный движок WORK (.safetensors)',
314
+ modality: 'embed',
315
+ maxTokens: 8192,
316
+ maxOutput: 1024,
317
+ ramGb: 1.4,
318
+ capabilities: ['embeddings', 'rag'],
319
+ role: 'Мультиязычные векторные эмбеддинги для семантического поиска RAG по документам и БД WORK',
320
+ },
321
+ {
322
+ nodeName: 'bge-reranker-v2-m3',
323
+ label: 'BGE-Reranker-v2-M3 (Реранкер RAG)',
324
+ icon: 'carbon:filter',
325
+ path: '/MODELS/Local/bge-reranker-v2-m3',
326
+ baseUrl: '',
327
+ model: 'BAAI/bge-reranker-v2-m3',
328
+ hfRepo: 'BAAI/bge-reranker-v2-m3',
329
+ protocol: 'local',
330
+ runtimeType: 'local',
331
+ device: 'Встроенный движок WORK (.safetensors)',
332
+ modality: 'embed',
333
+ maxTokens: 8192,
334
+ maxOutput: 1024,
335
+ ramGb: 1.4,
336
+ capabilities: ['rerank', 'rag'],
337
+ role: 'Точное переранжирование найденных документов и объектов БД для RAG-контекста',
338
+ },
339
+ {
340
+ nodeName: 'Qwen3-0.6B',
341
+ label: 'Qwen3-0.6B (Быстрый классификатор)',
342
+ icon: 'carbon:decision-tree',
343
+ path: '/MODELS/Local/Qwen3-0.6B',
344
+ baseUrl: '',
345
+ model: 'Qwen/Qwen3-0.6B',
346
+ hfRepo: 'Qwen/Qwen3-0.6B',
347
+ protocol: 'local',
348
+ runtimeType: 'local',
349
+ device: 'Встроенный движок WORK (.safetensors)',
350
+ modality: 'llm',
351
+ maxTokens: 32768,
352
+ maxOutput: 2048,
353
+ ramGb: 1.0,
354
+ capabilities: ['chat', 'stream', 'decide', 'classify'],
355
+ role: 'Мгновенный локальный классификатор, маршрутизатор и короткие системные проверки',
356
+ },
357
+ ]);
358
+
359
+ /**
360
+ * Вернуть каталог моделей Halo, совместимый с указанной ОС (`win32` или `linux`).
361
+ * На Windows: 1 основная GPU-модель `Qwen3.8-Flash-Next` через Halowin Bubo (GGUF) + 7 совместимых `.safetensors` моделей.
362
+ * На Linux: 1 `.hgn` + 7 `.hnpw` для контейнера `halogen-flash-server`.
363
+ */
364
+ export function getHalogenCatalogForPlatform(platform = os.platform()) {
365
+ if (platform === 'win32') {
366
+ const flashSpec = HALOGEN_MODELS_CATALOG.find(m => m.nodeName === 'Qwen3.8-Flash-Next');
367
+ const winFlash = flashSpec ? [{
368
+ ...flashSpec,
369
+ hfRepo: flashSpec.windowsBuboRepo || flashSpec.hfRepo,
370
+ ramGb: flashSpec.windowsRamGb || flashSpec.ramGb,
371
+ role: flashSpec.windowsRole || flashSpec.role,
372
+ protocol: 'halogen',
373
+ runtimeType: 'bubo',
374
+ }] : [];
375
+ return [...winFlash, ...HALOGEN_WINDOWS_COMPANIONS.map(m => ({ ...m }))];
376
+ }
377
+ return HALOGEN_MODELS_CATALOG
378
+ .filter(spec => !Array.isArray(spec.platforms) || spec.platforms.includes(platform))
379
+ .map(spec => ({ ...spec, protocol: 'halogen', runtimeType: 'halogen-linux' }));
380
+ }
381
+
214
382
  /** Допустимые пресетные голоса `qwen3-tts-*-customvoice` в Halogen NPU. */
215
383
  export const HALOGEN_TTS_VOICES = new Set([
216
384
  'aiden', 'dylan', 'eric', 'ono_anna', 'ryan', 'serena', 'sohee', 'uncle_fu', 'vivian',
@@ -825,6 +993,47 @@ function findLocalGgufModel(rootDir = process.cwd()) {
825
993
  return null;
826
994
  }
827
995
 
996
+ /**
997
+ * Проверить системные требования Windows 11 перед загрузкой тяжёлого стека Halowin Bubo (диск, RAM+UMA, PageFile).
998
+ */
999
+ export function checkWindowsHalogenPreflight({
1000
+ rootDir = process.cwd(),
1001
+ requiredDiskGb = 120,
1002
+ minTotalMemoryGb = 96,
1003
+ totalMemoryGb = null,
1004
+ } = {}) {
1005
+ const winEnv = inspectWindowsHalogenEnvironment({ rootDir });
1006
+ const freeDiskGb = getFreeDiskSpaceGb(rootDir);
1007
+ const warnings = [];
1008
+ const errors = [];
1009
+
1010
+ // По требованию пользователя загрузка не блокируется из-за памяти или свободного места (может качаться на перенос/флешку),
1011
+ // а все замечания возвращаются как предупреждения.
1012
+ if (freeDiskGb !== null && requiredDiskGb > 0 && freeDiskGb < requiredDiskGb) {
1013
+ warnings.push(`На текущем диске свободно ${freeDiskGb} ГБ (для полной 180B модели требуется ~${requiredDiskGb} ГБ).`);
1014
+ }
1015
+ if (totalMemoryGb !== null && minTotalMemoryGb > 0 && totalMemoryGb < minTotalMemoryGb) {
1016
+ warnings.push(`Обнаружено ${totalMemoryGb} ГБ общей памяти (RAM + UMA); для запуска 180B модели на этой машине рекомендуется 128–192 ГБ.`);
1017
+ }
1018
+ if (winEnv.pageFileOk === false) {
1019
+ warnings.push(`Файл подкачки pagefile.sys равен ${winEnv.pageFileGb} ГБ; для стабильной работы 180B модели на Windows рекомендуется фиксированный PageFile 128 ГБ (131072 МБ).`);
1020
+ }
1021
+ if (!winEnv.vcRedistInstalled) {
1022
+ warnings.push('Не обнаружена библиотека Microsoft VC++ 2015–2022 Redistributable (vcruntime140.dll) — её нужно установить для запуска bubo.exe.');
1023
+ }
1024
+
1025
+ return {
1026
+ ok: true,
1027
+ freeDiskGb,
1028
+ requiredDiskGb,
1029
+ totalMemoryGb,
1030
+ minTotalMemoryGb,
1031
+ errors,
1032
+ warnings,
1033
+ windowsEnv: winEnv,
1034
+ };
1035
+ }
1036
+
828
1037
  /**
829
1038
  * Скачать и подготовить нативный Windows-движок `Halowin Bubo` (`bubo-v0.1.2-windows-x64-gfx1151.zip`),
830
1039
  * официальный рантайм AMD ROCm 10.0.0 (`gfx1151`) и пакет весов `Qwen3.8-Flash-Next` (`UD-Q4_K_XL` + `Dense Twin` + `MTP`).
@@ -862,23 +1071,41 @@ export async function prepareWindowsBuboRuntime({
862
1071
  if (_windowsPrepareState.logs.length > 80)
863
1072
  _windowsPrepareState.logs.shift();
864
1073
  _windowsPrepareState.message = clean;
1074
+ const pctMatch = clean.match(/\b(\d{1,3})%/);
1075
+ if (pctMatch && (step === 'model' || step === 'all')) {
1076
+ const pct = Math.min(99, Math.max(0, Number(pctMatch[1])));
1077
+ if (pct > _windowsPrepareState.progress)
1078
+ _windowsPrepareState.progress = pct;
1079
+ }
865
1080
  _windowsPrepareState.updatedAt = Date.now();
866
1081
  };
867
1082
 
868
1083
  try {
1084
+ if (step === 'model' || step === 'all') {
1085
+ const freeGb = getFreeDiskSpaceGb(rootDir);
1086
+ if (freeGb !== null && freeGb < 118) {
1087
+ appendLog(`Предупреждение: на диске свободно ${freeGb} ГБ (рекомендуется ~120 ГБ для модели).`);
1088
+ }
1089
+ }
1090
+
1091
+ const netCfg = loadTrainerNetworkSettings(rootDir);
1092
+ const childEnv = {
1093
+ ...process.env,
1094
+ ...(netCfg.proxyUrl ? { HTTPS_PROXY: netCfg.proxyUrl, HTTP_PROXY: netCfg.proxyUrl } : {}),
1095
+ };
1096
+
869
1097
  let envInfo = inspectWindowsHalogenEnvironment({ rootDir });
870
1098
 
871
1099
  // Шаг 1: Если `bubo.exe` ещё не установлен, скачиваем официальный релиз `bubo-v0.1.2-windows-x64-gfx1151.zip`
872
1100
  if (!envInfo.buboInstalled || step === 'download-bubo') {
873
1101
  const zipPath = path.join(runtimeRoot, BUBO_WINDOWS_RELEASE.zipFileName);
874
- const netCfg = loadTrainerNetworkSettings(rootDir);
875
1102
  const effProxy = fetchImpl === globalThis.fetch ? netCfg.proxyUrl : '';
876
1103
  const netFetch = createNetworkFetch({ proxyUrl: effProxy, fetchImpl });
877
1104
 
878
1105
  appendLog(`Скачивание ${BUBO_WINDOWS_RELEASE.zipFileName} (${(BUBO_WINDOWS_RELEASE.sizeBytes / (1024 * 1024)).toFixed(1)} МБ, ${netCfg.threads} потоков)…`);
879
- _windowsPrepareState.progress = 15;
1106
+ _windowsPrepareState.progress = 10;
880
1107
 
881
- const dlRes = await downloadFileMultipart({
1108
+ await downloadFileMultipart({
882
1109
  url: BUBO_WINDOWS_RELEASE.downloadUrl,
883
1110
  stagedFile: zipPath,
884
1111
  expectedSize: BUBO_WINDOWS_RELEASE.sizeBytes,
@@ -887,7 +1114,7 @@ export async function prepareWindowsBuboRuntime({
887
1114
  onProgress: ({ downloadedBytes, totalBytes }) => {
888
1115
  const denom = totalBytes || BUBO_WINDOWS_RELEASE.sizeBytes;
889
1116
  if (denom > 0)
890
- _windowsPrepareState.progress = Math.min(55, 15 + Math.round((downloadedBytes / denom) * 40));
1117
+ _windowsPrepareState.progress = Math.min(25, 10 + Math.round((downloadedBytes / denom) * 15));
891
1118
  },
892
1119
  });
893
1120
 
@@ -909,7 +1136,7 @@ export async function prepareWindowsBuboRuntime({
909
1136
 
910
1137
  await fsp.mkdir(buboDir, { recursive: true });
911
1138
  appendLog('Распаковка архива Halowin Bubo…');
912
- _windowsPrepareState.progress = 60;
1139
+ _windowsPrepareState.progress = 28;
913
1140
 
914
1141
  let isPkZip = false;
915
1142
  try {
@@ -940,7 +1167,7 @@ export async function prepareWindowsBuboRuntime({
940
1167
  // Шаг 2: Установка официальных библиотек AMD ROCm 10.0.0 (`gfx1151`) через `bubo.exe prepare runtime --yes`
941
1168
  if ((step === 'runtime' || step === 'all') && fs.existsSync(buboExe)) {
942
1169
  appendLog('Загрузка официальных пакетов AMD ROCm 10.0.0 для gfx1151 (bubo prepare runtime --yes)…');
943
- _windowsPrepareState.progress = 75;
1170
+ _windowsPrepareState.progress = Math.max(_windowsPrepareState.progress, 35);
944
1171
  await new Promise((resolve, reject) => {
945
1172
  const proc = spawnImpl(buboExe, [
946
1173
  'prepare', 'runtime',
@@ -948,6 +1175,7 @@ export async function prepareWindowsBuboRuntime({
948
1175
  '--yes',
949
1176
  ], {
950
1177
  cwd: path.dirname(buboExe),
1178
+ env: childEnv,
951
1179
  windowsHide: true,
952
1180
  });
953
1181
  proc.stdout?.on('data', d => appendLog(d));
@@ -959,8 +1187,8 @@ export async function prepareWindowsBuboRuntime({
959
1187
 
960
1188
  // Шаг 3: Подготовка 8 файлов модели Qwen3.8-Flash-Next (UD-Q4_K_XL + MTP + Dense Twin + Draft Head + Vision)
961
1189
  if ((step === 'model' || step === 'all') && fs.existsSync(buboExe)) {
962
- appendLog(`Подготовка модели Qwen3.8-Flash-Next (${modelSet}) через bubo prepare model…`);
963
- _windowsPrepareState.progress = 90;
1190
+ appendLog(`Подготовка модели Qwen3.8-Flash-Next (${modelSet}, ~116.6 ГБ) через bubo prepare model…`);
1191
+ _windowsPrepareState.progress = Math.max(_windowsPrepareState.progress, 45);
964
1192
  const args = [
965
1193
  'prepare', 'model',
966
1194
  ...(modelSet === 'original' ? ['--model-set', 'original'] : []),
@@ -970,6 +1198,7 @@ export async function prepareWindowsBuboRuntime({
970
1198
  await new Promise((resolve, reject) => {
971
1199
  const proc = spawnImpl(buboExe, args, {
972
1200
  cwd: path.dirname(buboExe),
1201
+ env: childEnv,
973
1202
  windowsHide: true,
974
1203
  });
975
1204
  proc.stdout?.on('data', d => appendLog(d));
@@ -977,6 +1206,36 @@ export async function prepareWindowsBuboRuntime({
977
1206
  proc.on('error', reject);
978
1207
  proc.on('close', code => code === 0 ? resolve() : reject(new Error(`bubo prepare model завершился с кодом ${code}`)));
979
1208
  });
1209
+
1210
+ const afterEnv = inspectWindowsHalogenEnvironment({ rootDir });
1211
+ const flashSpec = HALOGEN_MODELS_CATALOG.find(m => m.nodeName === 'Qwen3.8-Flash-Next');
1212
+ if (flashSpec) {
1213
+ const wDir = afterEnv.buboManifestPath
1214
+ ? path.dirname(afterEnv.buboManifestPath)
1215
+ : modelWeightsDir(rootDir, flashSpec.nodeName, 'Local');
1216
+ await registerLocalModelNode({
1217
+ rootDir,
1218
+ folderName: flashSpec.nodeName,
1219
+ label: flashSpec.label,
1220
+ repoId: flashSpec.windowsBuboRepo || 'unsloth/Qwen3.8-Flash-Next-GGUF',
1221
+ model: flashSpec.model,
1222
+ protocol: 'halogen',
1223
+ icon: flashSpec.icon || 'ai:qwen',
1224
+ modality: flashSpec.modality,
1225
+ capabilities: flashSpec.capabilities,
1226
+ efforts: flashSpec.efforts,
1227
+ maxTokens: flashSpec.maxTokens,
1228
+ maxOutput: flashSpec.maxOutput,
1229
+ baseUrl: flashSpec.baseUrl || HALOGEN_DEFAULT_BASE_URL,
1230
+ weightsDir: wDir,
1231
+ primaryFile: 'bubo-package.json',
1232
+ });
1233
+ try {
1234
+ const localNode = await globalThis.WORK?.get_item?.('/MODELS/Local');
1235
+ localNode?.reset?.();
1236
+ }
1237
+ catch { /* ignore */ }
1238
+ }
980
1239
  }
981
1240
 
982
1241
  _windowsPrepareState.status = 'completed';
@@ -1189,6 +1448,8 @@ export async function startHalogenBackend({
1189
1448
  };
1190
1449
  }
1191
1450
 
1451
+ let _backendStartPromise = null;
1452
+
1192
1453
  export function stopHalogenBackend() {
1193
1454
  if (_managedProc && !_managedProc.killed) {
1194
1455
  try { _managedProc.kill(); } catch { /* ignore */ }
@@ -1198,6 +1459,118 @@ export function stopHalogenBackend() {
1198
1459
  return { stopped: true };
1199
1460
  }
1200
1461
 
1462
+ /**
1463
+ * Проверить готовность локального движка на порту `:8731` и при необходимости автоматически запустить его
1464
+ * внутри ядра WORK (Windows: `bubo.exe` / `gufo.exe` / `llama-server`).
1465
+ */
1466
+ export async function ensureHalogenBackendRunning({
1467
+ rootDir = process.cwd(),
1468
+ baseUrl = HALOGEN_DEFAULT_BASE_URL,
1469
+ ai = null,
1470
+ waitTimeoutMs = 20000,
1471
+ platform = os.platform(),
1472
+ spawnImpl = spawn,
1473
+ } = {}) {
1474
+ let port = HALOGEN_DEFAULT_PORT;
1475
+ try {
1476
+ const u = new URL(baseUrl || HALOGEN_DEFAULT_BASE_URL);
1477
+ if (u.port)
1478
+ port = Number(u.port) || HALOGEN_DEFAULT_PORT;
1479
+ }
1480
+ catch { /* default */ }
1481
+
1482
+ const probe1 = await probeHalogenServer(baseUrl, { rootDir });
1483
+ if (probe1.online) {
1484
+ return {
1485
+ ready: true,
1486
+ alreadyRunning: true,
1487
+ mode: probe1.mode,
1488
+ origin: probe1.origin,
1489
+ };
1490
+ }
1491
+
1492
+ // Проверка на несовместимые Linux-веса (.hgn / .hnpw) на Windows
1493
+ const modelFolderName = String(ai?.id || ai?.path || '').split('/').filter(Boolean).pop() || '';
1494
+ const candidateWeightsDir = ai?.weightsDir
1495
+ ? path.resolve(rootDir, ai.weightsDir)
1496
+ : (modelFolderName ? modelWeightsDir(rootDir, modelFolderName, 'Local') : '');
1497
+ const wInsp = candidateWeightsDir ? inspectWeightsDirectorySync(candidateWeightsDir, platform) : null;
1498
+ const winEnv = inspectWindowsHalogenEnvironment({ rootDir });
1499
+
1500
+ if (platform === 'win32' && wInsp?.incompatibleOnPlatform && !winEnv.buboModelPrepared) {
1501
+ return {
1502
+ ready: false,
1503
+ code: 'INCOMPATIBLE_FORMAT',
1504
+ reason: wInsp.incompatibleReason,
1505
+ weightsDir: candidateWeightsDir,
1506
+ };
1507
+ }
1508
+
1509
+ if (_backendStartPromise)
1510
+ return _backendStartPromise;
1511
+
1512
+ _backendStartPromise = (async () => {
1513
+ try {
1514
+ const explicitGguf = (wInsp?.hasGguf && candidateWeightsDir)
1515
+ ? path.join(candidateWeightsDir, wInsp.files.filter(f => f.toLowerCase().endsWith('.gguf') && !/mtp|mmproj/i.test(f)).sort()[0] || '')
1516
+ : '';
1517
+
1518
+ const startRes = await startHalogenBackend({
1519
+ rootDir,
1520
+ port,
1521
+ modelPath: explicitGguf && fs.existsSync(explicitGguf) ? explicitGguf : '',
1522
+ spawnImpl,
1523
+ });
1524
+
1525
+ if (startRes.mode === 'work-embedded-fallback') {
1526
+ const code = platform === 'win32'
1527
+ ? (winEnv.buboInstalled ? 'MODEL_MISSING' : 'RUNTIME_MISSING')
1528
+ : 'SERVER_OFFLINE';
1529
+ return {
1530
+ ready: false,
1531
+ code,
1532
+ reason: startRes.note,
1533
+ windowsEnv: winEnv,
1534
+ };
1535
+ }
1536
+
1537
+ const deadline = Date.now() + Math.max(2000, Number(waitTimeoutMs) || 20000);
1538
+ while (Date.now() < deadline) {
1539
+ if (!_managedProc && startRes.started && !startRes.alreadyRunning) {
1540
+ return {
1541
+ ready: false,
1542
+ code: 'PROCESS_EXITED',
1543
+ reason: 'Встроенный движок ИИ завершился сразу после запуска (проверьте наличие VC++ Redistributable, драйвера AMD и PageFile 128 ГБ).',
1544
+ windowsEnv: winEnv,
1545
+ };
1546
+ }
1547
+ const probe2 = await probeHalogenServer(baseUrl, { rootDir });
1548
+ if (probe2.online) {
1549
+ return {
1550
+ ready: true,
1551
+ alreadyRunning: false,
1552
+ mode: probe2.mode,
1553
+ origin: probe2.origin,
1554
+ };
1555
+ }
1556
+ await new Promise(r => setTimeout(r, 500));
1557
+ }
1558
+
1559
+ return {
1560
+ ready: false,
1561
+ code: 'START_TIMEOUT',
1562
+ reason: `Встроенный движок (${startRes.runtime || startRes.mode}) запущен, но ещё загружает веса модели в память. Повторите запрос через 15–30 секунд.`,
1563
+ windowsEnv: winEnv,
1564
+ };
1565
+ }
1566
+ finally {
1567
+ _backendStartPromise = null;
1568
+ }
1569
+ })();
1570
+
1571
+ return _backendStartPromise;
1572
+ }
1573
+
1201
1574
  /**
1202
1575
  * Сгенерировать валидный WAV-буфер (24 кГц, 16 бит, моно) для автономного фоллбэка TTS,
1203
1576
  * когда внешний сервер `:8731` (`halogen-flash-server` на Linux или `gufo serve tts` на Windows) не запущен.
@@ -1420,56 +1793,77 @@ export async function ensureHalogenModelNodes(rootDir = process.cwd(), { models
1420
1793
  }
1421
1794
 
1422
1795
  /**
1423
- * Проверить наличие скачанных весов и узлов `$ai` для каждой модели из `HALOGEN_MODELS_CATALOG` в `MODELS/Local/<nodeName>/#weights`.
1796
+ * Проверить наличие скачанных весов и узлов `$ai` для каждой модели Halo, совместимой с текущей ОС.
1424
1797
  */
1425
- export function inspectHalogenCatalogWithStatus(rootDir = process.cwd()) {
1798
+ export function inspectHalogenCatalogWithStatus(rootDir = process.cwd(), { platform = os.platform() } = {}) {
1426
1799
  migrateLocalModelsLayoutSync(rootDir);
1427
1800
  const activeDownloads = listHuggingFaceDownloads(rootDir);
1428
- return HALOGEN_MODELS_CATALOG.map(spec => {
1801
+ const winEnv = platform === 'win32' ? inspectWindowsHalogenEnvironment({ rootDir }) : null;
1802
+ const catalog = getHalogenCatalogForPlatform(platform);
1803
+
1804
+ return catalog.map(spec => {
1429
1805
  const localWeightsDir = modelWeightsDir(rootDir, spec.nodeName, 'Local');
1430
1806
  const legacyLocalDir = path.join(rootDir, 'MODELS', 'Local', spec.nodeName, '#weights');
1431
1807
  const legacyHalogenDir = path.join(rootDir, 'MODELS', 'Halogen', spec.nodeName, '#weights');
1432
1808
  const weightsDir = fs.existsSync(localWeightsDir) ? localWeightsDir
1433
1809
  : (fs.existsSync(legacyLocalDir) ? legacyLocalDir
1434
1810
  : (fs.existsSync(legacyHalogenDir) ? legacyHalogenDir : localWeightsDir));
1435
- let downloadedFiles = [];
1436
- let hasPendingDownload = false;
1437
- if (fs.existsSync(weightsDir)) {
1438
- try {
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'));
1443
- }
1444
- catch { /* ignore */ }
1445
- }
1811
+
1812
+ const wInsp = inspectWeightsDirectorySync(weightsDir, platform);
1813
+ const hasBuboReady = platform === 'win32'
1814
+ && spec.nodeName === 'Qwen3.8-Flash-Next'
1815
+ && Boolean(winEnv?.buboModelPrepared && winEnv?.buboManifestPath);
1816
+
1446
1817
  const nodeConfigured = fs.existsSync(modelClassFile(rootDir, spec.nodeName, 'Local'));
1447
- const activeJob = activeDownloads.find(d =>
1818
+ let activeJob = activeDownloads.find(d =>
1448
1819
  (d.status === 'downloading' || d.status === 'paused' || d.status === 'failed')
1449
1820
  && (d.repoId === spec.hfRepo || d.folderName === spec.nodeName || d.modelPath === spec.path)
1450
1821
  ) || null;
1451
- const hasRealWeightFile = downloadedFiles.some(f => WEIGHT_FILE_EXT_RE.test(f));
1822
+
1823
+ if (!activeJob && platform === 'win32' && spec.nodeName === 'Qwen3.8-Flash-Next' && _windowsPrepareState.status === 'running') {
1824
+ activeJob = {
1825
+ id: 'bubo_prepare',
1826
+ repoId: spec.windowsBuboRepo || spec.hfRepo,
1827
+ folderName: spec.nodeName,
1828
+ label: spec.label,
1829
+ status: 'downloading',
1830
+ progress: _windowsPrepareState.progress || 5,
1831
+ downloadedBytes: 0,
1832
+ totalBytes: 0,
1833
+ currentFile: _windowsPrepareState.message || 'Подготовка Halowin Bubo…',
1834
+ sourceLabel: 'Halowin Bubo (ROCm 10.0)',
1835
+ speedMBs: 0,
1836
+ avgSpeedMBs: 0,
1837
+ };
1838
+ }
1839
+
1840
+ const weightsDownloaded = hasBuboReady || (!activeJob && !wInsp.pendingDownload && wInsp.hasReadyWeights && !wInsp.incompatibleOnPlatform);
1841
+
1452
1842
  return {
1453
1843
  ...spec,
1454
1844
  nodeConfigured,
1455
- weightsDir: path.relative(rootDir, weightsDir).replace(/\\/g, '/'),
1456
- weightsDownloaded: !activeJob && !hasPendingDownload && hasRealWeightFile,
1457
- downloadedFiles,
1845
+ weightsDir: path.relative(rootDir, hasBuboReady ? path.dirname(winEnv.buboManifestPath) : weightsDir).replace(/\\/g, '/'),
1846
+ weightsDownloaded,
1847
+ incompatibleOnPlatform: !hasBuboReady && wInsp.incompatibleOnPlatform,
1848
+ incompatibleReason: !hasBuboReady ? wInsp.incompatibleReason : '',
1849
+ downloadedFiles: wInsp.files,
1458
1850
  activeDownload: activeJob,
1459
1851
  };
1460
1852
  });
1461
1853
  }
1462
1854
 
1463
1855
  /**
1464
- * Поставить в очередь скачивание всего пакета моделей Halo в `/MODELS/Local` (1 основная GPU-модель + 7 NPU-моделей)
1465
- * или выбранного подмножества моделей с Hugging Face Hub прямо в `MODELS/Local/<nodeName>/#weights`,
1466
- * регистрируя узлы `$ai` в `/MODELS/Local/<nodeName>` по мере завершения скачивания каждой модели.
1856
+ * Поставить в очередь скачивание совместимого с текущей ОС стека моделей Halo в `/MODELS/Local`:
1857
+ * - На Windows 11: проверяет диск/память и запускает нативную установку `Halowin Bubo` (ROCm 10.0.0 gfx1151 + GGUF 116.6 ГБ).
1858
+ * - На Linux: скачивает актуальные файлы `.hgn` + `.hnpw` для `halogen-flash-server`.
1467
1859
  */
1468
1860
  export async function downloadHalogenBundle({
1469
1861
  rootDir = process.cwd(),
1470
1862
  models = null,
1471
1863
  token = '',
1472
1864
  waitForCompletion = false,
1865
+ platform = os.platform(),
1866
+ totalMemoryGb = null,
1473
1867
  fetchImpl = globalThis.fetch,
1474
1868
  } = {}) {
1475
1869
  let filterList = null;
@@ -1480,11 +1874,116 @@ export async function downloadHalogenBundle({
1480
1874
  filterList = new Set(models.split(',').map(m => m.trim()).filter(Boolean));
1481
1875
  }
1482
1876
 
1877
+ const platformCatalog = getHalogenCatalogForPlatform(platform);
1483
1878
  const targets = filterList
1484
- ? HALOGEN_MODELS_CATALOG.filter(m =>
1879
+ ? platformCatalog.filter(m =>
1485
1880
  filterList.has(m.nodeName) || filterList.has(m.model) || filterList.has(m.hfRepo) || filterList.has(m.path)
1486
1881
  )
1487
- : [...HALOGEN_MODELS_CATALOG];
1882
+ : [...platformCatalog];
1883
+
1884
+ if (platform === 'win32') {
1885
+ if (!targets.length) {
1886
+ throw new Error('Выбранная модель предназначена только для Linux (формат .hnpw/.hgn) и не поддерживается на Windows. Используйте совместимые Windows-модели из каталога.');
1887
+ }
1888
+
1889
+ const hasBuboTarget = targets.some(m => m.runtimeType === 'bubo');
1890
+ const preflight = hasBuboTarget
1891
+ ? checkWindowsHalogenPreflight({
1892
+ rootDir,
1893
+ requiredDiskGb: 120,
1894
+ minTotalMemoryGb: 96,
1895
+ totalMemoryGb,
1896
+ })
1897
+ : { ok: true, warnings: [], errors: [] };
1898
+
1899
+ const existingDownloads = listHuggingFaceDownloads(rootDir);
1900
+ const jobs = [];
1901
+ let startedCount = 0;
1902
+ let alreadyActiveCount = 0;
1903
+
1904
+ for (const spec of targets) {
1905
+ if (spec.runtimeType === 'bubo') {
1906
+ if (_windowsPrepareState.status === 'running') {
1907
+ alreadyActiveCount++;
1908
+ jobs.push({
1909
+ id: 'bubo_prepare',
1910
+ folderName: spec.nodeName,
1911
+ status: 'downloading',
1912
+ progress: _windowsPrepareState.progress,
1913
+ });
1914
+ }
1915
+ else {
1916
+ const runPrep = prepareWindowsBuboRuntime({
1917
+ rootDir,
1918
+ step: 'all',
1919
+ modelSet: 'original',
1920
+ fetchImpl,
1921
+ });
1922
+ if (waitForCompletion) {
1923
+ const res = await runPrep;
1924
+ if (!res.ok)
1925
+ throw new Error(res.error || 'Не удалось подготовить Halowin Bubo');
1926
+ }
1927
+ else {
1928
+ runPrep.catch(() => {});
1929
+ }
1930
+ startedCount++;
1931
+ jobs.push({
1932
+ id: 'bubo_prepare',
1933
+ folderName: spec.nodeName,
1934
+ status: _windowsPrepareState.status === 'completed' ? 'completed' : 'downloading',
1935
+ progress: _windowsPrepareState.progress,
1936
+ });
1937
+ }
1938
+ continue;
1939
+ }
1940
+
1941
+ const running = existingDownloads.find(d =>
1942
+ d.status === 'downloading'
1943
+ && (d.repoId === spec.hfRepo || d.folderName === spec.nodeName || d.modelPath === spec.path)
1944
+ );
1945
+ if (running) {
1946
+ alreadyActiveCount++;
1947
+ jobs.push(running);
1948
+ continue;
1949
+ }
1950
+ const job = await startHuggingFaceDownload({
1951
+ repoId: spec.hfRepo,
1952
+ providerFolder: 'Local',
1953
+ targetNodeName: spec.nodeName,
1954
+ platform,
1955
+ nodeMeta: {
1956
+ label: spec.label || spec.nodeName,
1957
+ model: spec.model || spec.hfRepo,
1958
+ protocol: spec.protocol || 'local',
1959
+ icon: spec.icon || 'ai:qwen',
1960
+ modality: spec.modality,
1961
+ capabilities: spec.capabilities,
1962
+ efforts: spec.efforts,
1963
+ maxTokens: spec.maxTokens,
1964
+ maxOutput: spec.maxOutput,
1965
+ baseUrl: spec.baseUrl || '',
1966
+ },
1967
+ rootDir,
1968
+ token,
1969
+ registerInWork: true,
1970
+ waitForCompletion,
1971
+ fetchImpl,
1972
+ });
1973
+ startedCount++;
1974
+ jobs.push(job);
1975
+ }
1976
+
1977
+ return {
1978
+ totalModels: targets.length,
1979
+ startedCount,
1980
+ alreadyActiveCount,
1981
+ mode: hasBuboTarget ? 'bubo-windows' : 'local-windows',
1982
+ warnings: preflight.warnings || [],
1983
+ preflight,
1984
+ jobs,
1985
+ };
1986
+ }
1488
1987
 
1489
1988
  const existingDownloads = listHuggingFaceDownloads(rootDir);
1490
1989
  const jobs = [];
@@ -1505,6 +2004,7 @@ export async function downloadHalogenBundle({
1505
2004
  repoId: spec.hfRepo,
1506
2005
  providerFolder: 'Local',
1507
2006
  targetNodeName: spec.nodeName,
2007
+ platform,
1508
2008
  nodeMeta: {
1509
2009
  label: spec.label || spec.nodeName,
1510
2010
  model: spec.model,