odant-work 1.0.25 → 1.0.26

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.
@@ -21,6 +21,13 @@ import {
21
21
  mergeRanges,
22
22
  sumRangesBytes,
23
23
  } from './downloader.js';
24
+ import {
25
+ localRootDir,
26
+ modelDir as getModelDir,
27
+ modelWeightsDir as getModelWeightsDir,
28
+ migrateLocalModelsLayoutSync,
29
+ hasReadyWeightFilesSync,
30
+ } from './paths.js';
24
31
 
25
32
  const HF_ORIGIN = DEFAULT_HF_ORIGIN;
26
33
  const REPO_ID_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
@@ -1168,9 +1175,12 @@ export async function startHuggingFaceDownload({
1168
1175
  const folderName = targetNodeName
1169
1176
  ? String(targetNodeName).replace(/[<>:"/\\|?*]/g, '-')
1170
1177
  : safeModelFolderName(cleanId, quant && selected.some(f => f.kind === 'gguf') ? quant : '');
1171
- const modelDir = path.join(rootDir, 'MODELS', safeProvider, folderName);
1172
- const weightsDir = path.join(modelDir, '#weights');
1173
- const stagingDir = path.join(rootDir, 'MODELS', safeProvider, '#downloads', folderName);
1178
+
1179
+ migrateLocalModelsLayoutSync(rootDir, { skipModels: new Set([folderName]) });
1180
+
1181
+ const modelDir = getModelDir(rootDir, folderName, safeProvider);
1182
+ const weightsDir = getModelWeightsDir(rootDir, folderName, safeProvider);
1183
+ const stagingDir = weightsDir;
1174
1184
  const primary = selected.find(f => f.name.endsWith('.gguf'))?.name
1175
1185
  || selected.find(f => f.name.endsWith('.safetensors') || f.name.endsWith('.hgn') || f.name.endsWith('.hnpw'))?.name
1176
1186
  || selected[0]?.name || '';
@@ -1178,7 +1188,33 @@ export async function startHuggingFaceDownload({
1178
1188
  const displayLabel = nodeMeta?.label
1179
1189
  || `${cleanId.split('/')[1] || cleanId}${quant && primary.endsWith('.gguf') ? ' (' + quant + ')' : ''}`;
1180
1190
 
1181
- await fsp.mkdir(stagingDir, { recursive: true });
1191
+ await fsp.mkdir(weightsDir, { recursive: true });
1192
+
1193
+ // Если осталась недокачанная старая папка в #downloads/<folderName>, аккуратно перенесём её в $ai/#weights
1194
+ const legacyStaging = path.join(rootDir, 'MODELS', safeProvider, '#downloads', folderName);
1195
+ if (fs.existsSync(legacyStaging))
1196
+ migrateLocalModelsLayoutSync(rootDir);
1197
+
1198
+ // Создаём узел $ai/class.js сразу внутри папки модели (неактивен, пока веса не докачаны)
1199
+ if (registerInWork && safeProvider === 'Local') {
1200
+ await registerLocalModelNode({
1201
+ rootDir,
1202
+ folderName,
1203
+ label: displayLabel,
1204
+ repoId: cleanId,
1205
+ model: nodeMeta?.model || '',
1206
+ protocol: nodeMeta?.protocol || '',
1207
+ icon: nodeMeta?.icon || '',
1208
+ modality: nodeMeta?.modality || repoMeta.modality || 'llm',
1209
+ capabilities: nodeMeta?.capabilities || repoMeta.capabilities || ['chat'],
1210
+ efforts: nodeMeta?.efforts || null,
1211
+ maxTokens: nodeMeta?.maxTokens,
1212
+ maxOutput: nodeMeta?.maxOutput,
1213
+ baseUrl: nodeMeta?.baseUrl,
1214
+ weightsDir,
1215
+ primaryFile: path.basename(primary),
1216
+ });
1217
+ }
1182
1218
 
1183
1219
  // Читаем предыдущий download-state.json (если был), чтобы не потерять карту диапазонов при докачке
1184
1220
  let prevState = {};
@@ -1289,7 +1325,19 @@ export async function startHuggingFaceDownload({
1289
1325
  const runPromise = (async () => {
1290
1326
  const t0 = Date.now();
1291
1327
  const speedSamples = [];
1292
- let lastStateSave = 0;
1328
+ let lastStateSave = Date.now();
1329
+ let downloadFinished = false;
1330
+ let stateWriteChain = Promise.resolve();
1331
+
1332
+ const scheduleStateSave = () => {
1333
+ if (downloadFinished)
1334
+ return;
1335
+ stateWriteChain = stateWriteChain.then(() => {
1336
+ if (downloadFinished)
1337
+ return;
1338
+ return writeDownloadStateSafe(weightsDir, job, { nodeMeta, registerInWork });
1339
+ }).catch(() => {});
1340
+ };
1293
1341
 
1294
1342
  const updateMetrics = (deltaBytes = 0) => {
1295
1343
  const now = Date.now();
@@ -1322,7 +1370,7 @@ export async function startHuggingFaceDownload({
1322
1370
 
1323
1371
  if (now - lastStateSave >= 1500) {
1324
1372
  lastStateSave = now;
1325
- writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
1373
+ scheduleStateSave();
1326
1374
  }
1327
1375
  };
1328
1376
 
@@ -1369,7 +1417,7 @@ export async function startHuggingFaceDownload({
1369
1417
  onRetry: ({ attempt, error }) => {
1370
1418
  job.retryAttempt = attempt;
1371
1419
  job.retryError = error;
1372
- writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
1420
+ scheduleStateSave();
1373
1421
  },
1374
1422
  });
1375
1423
 
@@ -1403,20 +1451,11 @@ export async function startHuggingFaceDownload({
1403
1451
  if (controller.signal.aborted)
1404
1452
  throw new Error('Загрузка приостановлена пользователем');
1405
1453
 
1406
- // Переносим готовые файлы из скрытой папки #downloads в целевую папку модели #weights
1407
- await fsp.mkdir(weightsDir, { recursive: true });
1408
- for (const fileEntry of job.files) {
1409
- const stagedFile = path.join(stagingDir, path.basename(fileEntry.name));
1410
- const destFile = path.join(weightsDir, path.basename(fileEntry.name));
1411
- try {
1412
- await fsp.rename(stagedFile, destFile);
1413
- }
1414
- catch {
1415
- await fsp.copyFile(stagedFile, destFile);
1416
- await fsp.unlink(stagedFile).catch(() => {});
1417
- }
1418
- }
1419
- await fsp.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
1454
+ // Скачивание шло сразу в `$ai/#weights/` — перенос между папками не требуется;
1455
+ // дожидаемся завершения фоновых записей состояния, удаляем служебный файл и пишем итоговый манифест.
1456
+ downloadFinished = true;
1457
+ await stateWriteChain;
1458
+ await fsp.rm(path.join(weightsDir, DOWNLOAD_STATE_FILE), { force: true }).catch(() => {});
1420
1459
 
1421
1460
  const manifestFile = path.join(weightsDir, 'hf-manifest.json');
1422
1461
  await fsp.writeFile(manifestFile, JSON.stringify({
@@ -1428,7 +1467,6 @@ export async function startHuggingFaceDownload({
1428
1467
  files: job.files,
1429
1468
  }, null, 2), 'utf-8');
1430
1469
 
1431
- // Регистрируем узел $ai/class.js только после полного завершения скачивания весов
1432
1470
  if (registerInWork && safeProvider === 'Local') {
1433
1471
  await registerLocalModelNode({
1434
1472
  rootDir,
@@ -1462,6 +1500,8 @@ export async function startHuggingFaceDownload({
1462
1500
  catch { /* ignore */ }
1463
1501
  }
1464
1502
  catch (err) {
1503
+ downloadFinished = true;
1504
+ await stateWriteChain;
1465
1505
  if (controller.signal.aborted) {
1466
1506
  job.status = keepFilesOnAbort ? 'paused' : 'cancelled';
1467
1507
  job.error = keepFilesOnAbort ? null : String(err?.message || err);
@@ -1473,10 +1513,14 @@ export async function startHuggingFaceDownload({
1473
1513
  job.etaSeconds = null;
1474
1514
  job.finishedAt = Date.now();
1475
1515
  if (controller.signal.aborted && !keepFilesOnAbort) {
1476
- await fsp.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
1516
+ await fsp.rm(path.join(weightsDir, DOWNLOAD_STATE_FILE), { force: true }).catch(() => {});
1517
+ for (const fileEntry of job.files)
1518
+ await fsp.rm(path.join(weightsDir, path.basename(fileEntry.name) + '.part'), { force: true }).catch(() => {});
1519
+ if (!hasReadyWeightFilesSync(weightsDir))
1520
+ await fsp.rm(modelDir, { recursive: true, force: true }).catch(() => {});
1477
1521
  }
1478
1522
  else {
1479
- await writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
1523
+ await writeDownloadStateSafe(weightsDir, job, { nodeMeta, registerInWork });
1480
1524
  }
1481
1525
  }
1482
1526
  })();
@@ -1494,32 +1538,47 @@ export function getHuggingFaceDownload(jobId) {
1494
1538
  }
1495
1539
 
1496
1540
  export function listHuggingFaceDownloads(rootDir = process.cwd()) {
1497
- const inMemory = [..._downloads.values()].map(e => ({ ...e.job }));
1541
+ const resolvedRoot = path.resolve(rootDir);
1542
+ const inMemory = [..._downloads.values()]
1543
+ .filter(e => path.resolve(e.job.rootDir || process.cwd()) === resolvedRoot)
1544
+ .map(e => ({ ...e.job }));
1545
+ const activeNames = new Set(inMemory.filter(j => j.status === 'downloading').map(j => j.folderName));
1546
+ migrateLocalModelsLayoutSync(rootDir, { skipModels: activeNames });
1547
+
1498
1548
  const seenFolders = new Set(inMemory.map(j => `${j.providerFolder}:${j.folderName}`));
1499
1549
 
1500
- // Подхватываем недокачанные папки из MODELS/Local/#downloads/* (включая оставшиеся после рестарта)
1501
- const downloadsRoot = path.join(rootDir, 'MODELS', 'Local', '#downloads');
1502
- if (fs.existsSync(downloadsRoot)) {
1550
+ // Подхватываем незавершённые загрузки из метапапок моделей: MODELS/Local/<Модель>/$ai/#weights/
1551
+ const localRoot = localRootDir(rootDir);
1552
+ if (fs.existsSync(localRoot)) {
1503
1553
  try {
1504
- const entries = fs.readdirSync(downloadsRoot, { withFileTypes: true });
1554
+ const entries = fs.readdirSync(localRoot, { withFileTypes: true });
1505
1555
  for (const e of entries) {
1506
- if (!e.isDirectory() || e.name.startsWith('.') || e.name.startsWith('_import_') || e.name.startsWith('_tar_import_'))
1556
+ if (!e.isDirectory() || e.name.startsWith('$') || e.name.startsWith('#') || e.name === 'models')
1507
1557
  continue;
1508
1558
  if (seenFolders.has(`Local:${e.name}`))
1509
1559
  continue;
1510
- const folderDir = path.join(downloadsRoot, e.name);
1560
+ const folderDir = getModelWeightsDir(rootDir, e.name, 'Local');
1561
+ if (!fs.existsSync(folderDir))
1562
+ continue;
1511
1563
  const stateFile = path.join(folderDir, DOWNLOAD_STATE_FILE);
1564
+ const hasStateFile = fs.existsSync(stateFile);
1512
1565
  let state = {};
1513
- if (fs.existsSync(stateFile)) {
1566
+ if (hasStateFile) {
1514
1567
  try { state = JSON.parse(fs.readFileSync(stateFile, 'utf-8')); }
1515
1568
  catch { /* ignore */ }
1516
1569
  }
1517
1570
  const dirFiles = fs.readdirSync(folderDir, { withFileTypes: true });
1571
+ const hasParts = dirFiles.some(f => f.isFile() && f.name.endsWith('.part'));
1572
+ if (!hasStateFile && !hasParts)
1573
+ continue;
1574
+ if (state.status === 'completed' && !hasParts)
1575
+ continue;
1576
+
1518
1577
  const stateFilesMap = new Map((Array.isArray(state.files) ? state.files : []).map(sf => [sf.name, sf]));
1519
1578
  let diskBytes = 0;
1520
1579
  const parsedFiles = [];
1521
1580
  for (const f of dirFiles) {
1522
- if (!f.isFile() || f.name === DOWNLOAD_STATE_FILE || f.name.endsWith('.tmp'))
1581
+ if (!f.isFile() || f.name === DOWNLOAD_STATE_FILE || f.name === 'hf-manifest.json' || f.name.endsWith('.tmp'))
1523
1582
  continue;
1524
1583
  try {
1525
1584
  const st = fs.statSync(path.join(folderDir, f.name));
@@ -1611,8 +1670,19 @@ export async function discardHuggingFaceDownload({ jobId = '', folderName = '',
1611
1670
  if (!targetFolder && key.startsWith('disk_'))
1612
1671
  targetFolder = key.slice(5);
1613
1672
  if (targetFolder) {
1614
- const stagingDir = path.join(rootDir, 'MODELS', 'Local', '#downloads', targetFolder);
1615
- await fsp.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
1673
+ const weightsDir = getModelWeightsDir(rootDir, targetFolder, 'Local');
1674
+ if (fs.existsSync(weightsDir)) {
1675
+ await fsp.rm(path.join(weightsDir, DOWNLOAD_STATE_FILE), { force: true }).catch(() => {});
1676
+ const files = await fsp.readdir(weightsDir).catch(() => []);
1677
+ for (const f of files) {
1678
+ if (f.endsWith('.part') || f.endsWith('.tmp'))
1679
+ await fsp.rm(path.join(weightsDir, f), { force: true }).catch(() => {});
1680
+ }
1681
+ if (!hasReadyWeightFilesSync(weightsDir))
1682
+ await fsp.rm(getModelDir(rootDir, targetFolder, 'Local'), { recursive: true, force: true }).catch(() => {});
1683
+ }
1684
+ const legacyDir = path.join(rootDir, 'MODELS', 'Local', '#downloads', targetFolder);
1685
+ await fsp.rm(legacyDir, { recursive: true, force: true }).catch(() => {});
1616
1686
  }
1617
1687
  return { ok: true, discarded: targetFolder || key };
1618
1688
  }
@@ -1635,9 +1705,12 @@ export async function resumeHuggingFaceDownload({
1635
1705
  const key = String(jobId || '');
1636
1706
  const entry = key ? _downloads.get(key) : null;
1637
1707
  const cleanFolder = String(folderName || entry?.job?.folderName || (key.startsWith('disk_') ? key.slice(5) : '')).trim();
1708
+ if (cleanFolder)
1709
+ migrateLocalModelsLayoutSync(rootDir, { skipModels: new Set() });
1710
+
1638
1711
  let state = {};
1639
1712
  if (cleanFolder) {
1640
- const stateFile = path.join(rootDir, 'MODELS', 'Local', '#downloads', cleanFolder, DOWNLOAD_STATE_FILE);
1713
+ const stateFile = path.join(getModelWeightsDir(rootDir, cleanFolder, 'Local'), DOWNLOAD_STATE_FILE);
1641
1714
  if (fs.existsSync(stateFile)) {
1642
1715
  try { state = JSON.parse(await fsp.readFile(stateFile, 'utf-8')); }
1643
1716
  catch { /* ignore */ }
@@ -90,13 +90,19 @@ export function releaseLocalEngineMemory() {
90
90
 
91
91
  function resolveWeightsDir(ai, rootDir = process.cwd()) {
92
92
  const modelId = String(ai?.id || ai?.label || ai?.model || 'Local-Model').split('/').pop();
93
- const weightsRel = ai?.weightsDir || ai?.DATA?.weightsDir || `MODELS/Local/${modelId}/#weights`;
93
+ const weightsRel = ai?.weightsDir || ai?.DATA?.weightsDir || `MODELS/Local/${modelId}/$ai/#weights`;
94
94
  const primary = path.resolve(rootDir, weightsRel);
95
95
  if (fs.existsSync(primary))
96
96
  return primary;
97
+ const canonical = path.resolve(rootDir, `MODELS/Local/${modelId}/$ai/#weights`);
98
+ if (fs.existsSync(canonical))
99
+ return canonical;
100
+ const legacy = path.resolve(rootDir, `MODELS/Local/${modelId}/#weights`);
101
+ if (fs.existsSync(legacy))
102
+ return legacy;
97
103
  const isHalogen = ai?.protocol === 'halogen' || String(ai?.path || ai?.short || '').startsWith('/MODELS/Halogen/');
98
104
  if (isHalogen) {
99
- const fallback06 = path.resolve(rootDir, 'MODELS/Local/Qwen3-0.6B/#weights');
105
+ const fallback06 = path.resolve(rootDir, 'MODELS/Local/Qwen3-0.6B/$ai/#weights');
100
106
  if (fs.existsSync(fallback06))
101
107
  return fallback06;
102
108
  }
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Канонические пути подсистемы локальных моделей ИИ (правило метапапок WORK / ODANT):
3
+ * - Всё, что относится к провайдеру `/MODELS/Local`, живёт внутри его метапапки `MODELS/Local/$provider/`:
4
+ * - `#datasets/` — собранные обучающие наборы (.jsonl)
5
+ * - `#adapters/` — обученные LoRA-адаптеры
6
+ * - `#runtime/` — нативные рантаймы (bubo, gufo, strata, ROCm)
7
+ * - `#cache/` — дисковый кэш инференса
8
+ * - `#tmp/` — временная область распаковки импорта
9
+ * - Дети `/MODELS/Local` — только папки конкретных моделей `MODELS/Local/<Модель>/`,
10
+ * а всё относящееся к модели (включая `#weights` и активные `.part`-загрузки с `download-state.json`)
11
+ * лежит строго внутри её метапапки `MODELS/Local/<Модель>/$ai/#weights/`.
12
+ */
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+
16
+ export const WEIGHT_FILE_EXT_RE = /\.(gguf|safetensors|hgn|hnpw|bin|onnx|pt|pth)$/i;
17
+
18
+ export function localRootDir(rootDir = process.cwd()) {
19
+ return path.join(rootDir, 'MODELS', 'Local');
20
+ }
21
+
22
+ export function localProviderMetaDir(rootDir = process.cwd()) {
23
+ return path.join(localRootDir(rootDir), '$provider');
24
+ }
25
+
26
+ export function localDatasetsDir(rootDir = process.cwd()) {
27
+ return path.join(localProviderMetaDir(rootDir), '#datasets');
28
+ }
29
+
30
+ export function localAdaptersDir(rootDir = process.cwd()) {
31
+ return path.join(localProviderMetaDir(rootDir), '#adapters');
32
+ }
33
+
34
+ export function localRuntimeDir(rootDir = process.cwd()) {
35
+ return path.join(localProviderMetaDir(rootDir), '#runtime');
36
+ }
37
+
38
+ export function localCacheDir(rootDir = process.cwd()) {
39
+ return path.join(localProviderMetaDir(rootDir), '#cache');
40
+ }
41
+
42
+ export function localTempDir(rootDir = process.cwd()) {
43
+ return path.join(localProviderMetaDir(rootDir), '#tmp');
44
+ }
45
+
46
+ export function modelDir(rootDir = process.cwd(), folderName, providerFolder = 'Local') {
47
+ return path.join(rootDir, 'MODELS', String(providerFolder || 'Local'), String(folderName || ''));
48
+ }
49
+
50
+ export function modelMetaDir(rootDir = process.cwd(), folderName, providerFolder = 'Local') {
51
+ return path.join(modelDir(rootDir, folderName, providerFolder), '$ai');
52
+ }
53
+
54
+ export function modelWeightsDir(rootDir = process.cwd(), folderName, providerFolder = 'Local') {
55
+ return path.join(modelMetaDir(rootDir, folderName, providerFolder), '#weights');
56
+ }
57
+
58
+ export function modelClassFile(rootDir = process.cwd(), folderName, providerFolder = 'Local') {
59
+ return path.join(modelMetaDir(rootDir, folderName, providerFolder), 'class.js');
60
+ }
61
+
62
+ /**
63
+ * Проверить, есть ли в директории готовые файлы весов (не .part).
64
+ */
65
+ export function hasReadyWeightFilesSync(dirPath) {
66
+ if (!dirPath || !fs.existsSync(dirPath))
67
+ return false;
68
+ try {
69
+ return fs.readdirSync(dirPath).some(f => !f.endsWith('.part') && WEIGHT_FILE_EXT_RE.test(f));
70
+ }
71
+ catch {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ /**
77
+ * Безопасно перенести/слить старую папку `src` в `dest` без потери файлов.
78
+ * На одном томе использует мгновенный `renameSync`; при занятых файлах (`EBUSY`) не падает.
79
+ */
80
+ export function mergeMoveDirSync(srcDir, destDir) {
81
+ if (!srcDir || !fs.existsSync(srcDir))
82
+ return false;
83
+ if (path.resolve(srcDir) === path.resolve(destDir))
84
+ return true;
85
+
86
+ fs.mkdirSync(path.dirname(destDir), { recursive: true });
87
+ if (!fs.existsSync(destDir)) {
88
+ try {
89
+ fs.renameSync(srcDir, destDir);
90
+ return true;
91
+ }
92
+ catch { /* слияние по файлам ниже */ }
93
+ }
94
+
95
+ fs.mkdirSync(destDir, { recursive: true });
96
+ const entries = fs.readdirSync(srcDir, { withFileTypes: true });
97
+ for (const e of entries) {
98
+ const srcEntry = path.join(srcDir, e.name);
99
+ const destEntry = path.join(destDir, e.name);
100
+ try {
101
+ if (e.isDirectory()) {
102
+ mergeMoveDirSync(srcEntry, destEntry);
103
+ }
104
+ else if (e.isFile()) {
105
+ if (!fs.existsSync(destEntry)) {
106
+ try {
107
+ fs.renameSync(srcEntry, destEntry);
108
+ }
109
+ catch {
110
+ fs.copyFileSync(srcEntry, destEntry);
111
+ fs.unlinkSync(srcEntry);
112
+ }
113
+ }
114
+ else {
115
+ // Если в цели уже есть файл — для download-state.json берём более свежий, иначе удаляем старый дубль только если целевой >= по размеру
116
+ const srcSt = fs.statSync(srcEntry);
117
+ const dstSt = fs.statSync(destEntry);
118
+ if (e.name === 'download-state.json' ? srcSt.mtimeMs > dstSt.mtimeMs : srcSt.size > dstSt.size) {
119
+ fs.rmSync(destEntry, { force: true });
120
+ try {
121
+ fs.renameSync(srcEntry, destEntry);
122
+ }
123
+ catch {
124
+ fs.copyFileSync(srcEntry, destEntry);
125
+ fs.unlinkSync(srcEntry);
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }
131
+ catch { /* занятый файл другого процесса — оставим до следующего прохода */ }
132
+ }
133
+
134
+ try {
135
+ if (!fs.readdirSync(srcDir).length)
136
+ fs.rmdirSync(srcDir);
137
+ }
138
+ catch { /* папка не пуста или занята */ }
139
+ return true;
140
+ }
141
+
142
+ /**
143
+ * Разовая/идемпотентная миграция старой раскладки `MODELS/Local`:
144
+ * - `#datasets`, `#adapters`, `#runtime`, `#cache` → `MODELS/Local/$provider/#...`;
145
+ * - `#downloads/<Модель>` → `MODELS/Local/<Модель>/$ai/#weights/`;
146
+ * - `MODELS/Local/<Модель>/#weights/` → `MODELS/Local/<Модель>/$ai/#weights/`.
147
+ */
148
+ export function migrateLocalModelsLayoutSync(rootDir = process.cwd(), { skipModels = null } = {}) {
149
+ const localRoot = localRootDir(rootDir);
150
+ if (!fs.existsSync(localRoot))
151
+ return;
152
+
153
+ const providerMeta = localProviderMetaDir(rootDir);
154
+
155
+ // 1. Служебные папки провайдера Local переносим в $provider/
156
+ for (const dirName of ['#datasets', '#adapters', '#runtime', '#cache']) {
157
+ const legacy = path.join(localRoot, dirName);
158
+ if (fs.existsSync(legacy))
159
+ mergeMoveDirSync(legacy, path.join(providerMeta, dirName));
160
+ }
161
+
162
+ // 2. Старая папка #downloads/<Модель> переносится в <Модель>/$ai/#weights
163
+ const legacyDownloads = path.join(localRoot, '#downloads');
164
+ if (fs.existsSync(legacyDownloads)) {
165
+ try {
166
+ const dlEntries = fs.readdirSync(legacyDownloads, { withFileTypes: true });
167
+ for (const e of dlEntries) {
168
+ if (!e.isDirectory() || e.name.startsWith('.'))
169
+ continue;
170
+ if (e.name.startsWith('_import_') || e.name.startsWith('_tar_import_')) {
171
+ mergeMoveDirSync(path.join(legacyDownloads, e.name), path.join(localTempDir(rootDir), e.name));
172
+ continue;
173
+ }
174
+ if (skipModels && skipModels.has(e.name))
175
+ continue;
176
+ const src = path.join(legacyDownloads, e.name);
177
+ const dstWeights = modelWeightsDir(rootDir, e.name);
178
+ mergeMoveDirSync(src, dstWeights);
179
+
180
+ // Если $ai/class.js ещё нет, но в download-state.json сохранены метаданные — создадим неактивный узел $ai
181
+ const aiClass = modelClassFile(rootDir, e.name);
182
+ const stateFile = path.join(dstWeights, 'download-state.json');
183
+ if (!fs.existsSync(aiClass) && fs.existsSync(stateFile)) {
184
+ try {
185
+ const st = JSON.parse(fs.readFileSync(stateFile, 'utf-8')) || {};
186
+ const meta = {
187
+ label: st.label || e.name,
188
+ icon: st.nodeMeta?.icon || 'ai:ollama',
189
+ protocol: st.nodeMeta?.protocol || 'local',
190
+ baseUrl: st.nodeMeta?.baseUrl || 'http://127.0.0.1:8731/v1/chat/completions',
191
+ model: st.nodeMeta?.model || st.repoId || e.name,
192
+ modality: st.modality || st.nodeMeta?.modality || 'llm',
193
+ maxTokens: Number(st.nodeMeta?.maxTokens) || 16384,
194
+ maxOutput: Number(st.nodeMeta?.maxOutput) || 8192,
195
+ capabilities: Array.isArray(st.capabilities) ? st.capabilities : ['chat', 'stream'],
196
+ hfRepo: st.repoId || '',
197
+ weightsDir: path.relative(rootDir, dstWeights).replace(/\\/g, '/'),
198
+ };
199
+ fs.mkdirSync(path.dirname(aiClass), { recursive: true });
200
+ fs.writeFileSync(aiClass, `/**\n * Локальная модель ИИ: ${meta.label}\n */\nexport default ${JSON.stringify(meta, null, 4)};\n`, 'utf-8');
201
+ }
202
+ catch { /* ignore */ }
203
+ }
204
+ }
205
+ try {
206
+ if (!fs.readdirSync(legacyDownloads).length)
207
+ fs.rmdirSync(legacyDownloads);
208
+ }
209
+ catch { /* ignore */ }
210
+ }
211
+ catch { /* ignore */ }
212
+ }
213
+
214
+ // 3. Папки моделей со старым #weights на уровне модели (рядом с $ai) переносим в $ai/#weights
215
+ try {
216
+ const entries = fs.readdirSync(localRoot, { withFileTypes: true });
217
+ for (const e of entries) {
218
+ if (!e.isDirectory() || e.name.startsWith('$') || e.name.startsWith('#') || e.name === 'models')
219
+ continue;
220
+ if (skipModels && skipModels.has(e.name))
221
+ continue;
222
+ const mDir = path.join(localRoot, e.name);
223
+ const legacyWeights = path.join(mDir, '#weights');
224
+ const newWeights = modelWeightsDir(rootDir, e.name);
225
+ if (fs.existsSync(legacyWeights))
226
+ mergeMoveDirSync(legacyWeights, newWeights);
227
+
228
+ const classFile = modelClassFile(rootDir, e.name);
229
+ if (fs.existsSync(classFile)) {
230
+ try {
231
+ const raw = fs.readFileSync(classFile, 'utf-8');
232
+ const jsonPart = raw.replace(/^[^{]*/, '').replace(/;\s*$/, '');
233
+ const meta = JSON.parse(jsonPart);
234
+ let changed = false;
235
+ const expectedWeightsRel = path.relative(rootDir, newWeights).replace(/\\/g, '/');
236
+ if (meta.weightsDir && !meta.weightsDir.includes('/$ai/#weights') && fs.existsSync(newWeights)) {
237
+ meta.weightsDir = expectedWeightsRel;
238
+ changed = true;
239
+ }
240
+ if (meta.adapterPath && !meta.adapterPath.includes('/$provider/#adapters/')) {
241
+ const adName = path.basename(String(meta.adapterPath));
242
+ const newAdPath = path.join(localAdaptersDir(rootDir), adName);
243
+ if (fs.existsSync(newAdPath)) {
244
+ meta.adapterPath = path.relative(rootDir, newAdPath).replace(/\\/g, '/');
245
+ changed = true;
246
+ }
247
+ }
248
+ if (changed) {
249
+ fs.writeFileSync(classFile, `/**\n * Локальная модель ИИ: ${meta.label || e.name}\n */\nexport default ${JSON.stringify(meta, null, 4)};\n`, 'utf-8');
250
+ }
251
+ }
252
+ catch { /* ignore non-json */ }
253
+ }
254
+ }
255
+ }
256
+ catch { /* ignore */ }
257
+ }
@@ -782,9 +782,22 @@ function hasWeightFilesInDirSync(dir) {
782
782
  if (!dir || !fs.existsSync(dir))
783
783
  return false;
784
784
  try {
785
- return fs.readdirSync(dir).some(f =>
785
+ const entries = fs.readdirSync(dir);
786
+ if (entries.includes('download-state.json')) {
787
+ try {
788
+ const st = JSON.parse(fs.readFileSync(path.join(dir, 'download-state.json'), 'utf-8'));
789
+ if (st?.status !== 'completed')
790
+ return false;
791
+ }
792
+ catch {
793
+ return false;
794
+ }
795
+ }
796
+ return entries.some(f =>
786
797
  !f.endsWith('.part')
798
+ && !f.endsWith('.tmp')
787
799
  && f !== 'hf-manifest.json'
800
+ && f !== 'download-state.json'
788
801
  && /\.(safetensors|gguf|bin|onnx|pt|pth|hgn|hnpw|json)$/i.test(f)
789
802
  );
790
803
  }
@@ -861,7 +874,8 @@ export function evaluateAiNodeActivitySync(item, rootDir = process.cwd()) {
861
874
  if (!entry.isDirectory() || entry.name.startsWith('$') || entry.name.startsWith('#') || entry.name === 'models')
862
875
  continue;
863
876
  if (
864
- hasWeightFilesInDirSync(path.join(localDir, entry.name, '#weights'))
877
+ hasWeightFilesInDirSync(path.join(localDir, entry.name, '$ai', '#weights'))
878
+ || hasWeightFilesInDirSync(path.join(localDir, entry.name, '#weights'))
865
879
  || hasWeightFilesInDirSync(path.join(localDir, entry.name, '#adapters'))
866
880
  ) {
867
881
  installedCount++;
@@ -879,15 +893,18 @@ export function evaluateAiNodeActivitySync(item, rootDir = process.cwd()) {
879
893
 
880
894
  // Дочерняя модель в /MODELS/Local/<Model>
881
895
  const modelName = parts[2] || item.id || '';
882
- const weightsRel = data.weightsDir || path.join('MODELS', 'Local', modelName, '#weights');
883
- const adapterRel = data.adapterPath || path.join('MODELS', 'Local', modelName, '#adapters');
884
- const hasWeights = hasWeightFilesInDirSync(path.resolve(rootDir, weightsRel))
896
+ const canonicalWeightsRel = path.join('MODELS', 'Local', modelName, '$ai', '#weights');
897
+ const legacyWeightsRel = path.join('MODELS', 'Local', modelName, '#weights');
898
+ const adapterRel = data.adapterPath || path.join('MODELS', 'Local', '$provider', '#adapters', modelName);
899
+ const hasWeights = hasWeightFilesInDirSync(path.resolve(rootDir, data.weightsDir || canonicalWeightsRel))
900
+ || hasWeightFilesInDirSync(path.resolve(rootDir, canonicalWeightsRel))
901
+ || hasWeightFilesInDirSync(path.resolve(rootDir, legacyWeightsRel))
885
902
  || hasWeightFilesInDirSync(path.resolve(rootDir, adapterRel))
886
903
  || fs.existsSync(path.join(rootDir, 'MODELS', 'Local', 'models', 'qwen38-flash-next-base-ud-q4-k-xl-v1', 'bubo-package.json'));
887
904
  if (hasWeights) {
888
905
  return { active: true, reason: 'Активна (веса модели на диске)', configuredKey: true };
889
906
  }
890
- return { active: false, reason: 'Веса модели не скачаны в #weights', configuredKey: false };
907
+ return { active: false, reason: 'Веса модели не скачаны в $ai/#weights', configuredKey: false };
891
908
  }
892
909
 
893
910
  // 2. Внешние и облачные провайдеры ($provider и их $ai)