odant-work 1.0.19 → 1.0.21

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 (32) hide show
  1. package/#system/package-manifest.json +35 -22
  2. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +21 -2
  3. package/$server/$folder/lib/chat-item/chat-item.js +17 -1
  4. package/$server/$folder/lib/local-models-transfer/local-models-transfer.js +972 -0
  5. package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +427 -106
  6. package/MODELS/Local/$provider/handlers/methods/transfer/$handler/class.js +41 -0
  7. package/package.json +1 -1
  8. package/rules/threats.md +117 -116
  9. package/sources/client.js +1 -0
  10. package/sources/data/progress.md +15 -0
  11. package/sources/host/auto-updater.js +30 -2
  12. package/sources/host/http-server.js +23 -0
  13. package/sources/host/websocket.js +127 -120
  14. package/sources/modules/agent/index.js +6 -1
  15. package/sources/modules/agent/readme.md +217 -216
  16. package/sources/modules/agent/tools/chrome.js +263 -0
  17. package/sources/modules/bridge/chrome.js +673 -0
  18. package/sources/modules/bridge/hub.js +395 -361
  19. package/sources/modules/chrome-extension/background.js +299 -0
  20. package/sources/modules/chrome-extension/manifest.json +25 -0
  21. package/sources/modules/chrome-extension/options.html +48 -0
  22. package/sources/modules/chrome-extension/options.js +104 -0
  23. package/sources/modules/chrome-extension/popup.html +25 -0
  24. package/sources/modules/chrome-extension/popup.js +32 -0
  25. package/sources/modules/trainer/halogen.js +16 -4
  26. package/sources/modules/trainer/huggingface.js +471 -95
  27. package/sources/modules/trainer/index.js +288 -1
  28. package/sources/modules/trainer/runner.js +54 -4
  29. package/sources/modules/trainer/tar-stream.js +458 -0
  30. package/sources/modules/trainer/transfer.js +1570 -0
  31. package/sources/modules/user-profile/user-profile.js +34 -10
  32. package/sources/modules/user-profile/user-token.js +168 -0
@@ -1005,9 +1005,73 @@ export default ${JSON.stringify(meta, null, 4)};
1005
1005
  };
1006
1006
  }
1007
1007
 
1008
+ const DOWNLOAD_STATE_FILE = 'download-state.json';
1009
+ const RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);
1010
+
1011
+ function isRetryableDownloadError(err) {
1012
+ if (!err)
1013
+ return false;
1014
+ if (err.httpStatus && RETRYABLE_HTTP_STATUSES.has(err.httpStatus))
1015
+ return true;
1016
+ if (err.httpStatus && err.httpStatus >= 400 && err.httpStatus < 500)
1017
+ return false;
1018
+ const msg = String(err?.message || err);
1019
+ if (/Unexpected URL|Некорректн|отменена/i.test(msg))
1020
+ return false;
1021
+ return err.retryable === true
1022
+ || /ECONNRESET|ETIMEDOUT|EPIPE|EAI_AGAIN|ENOTFOUND|network|fetch failed|terminated|aborted|socket|premature/i.test(msg);
1023
+ }
1024
+
1025
+ async function writeDownloadStateSafe(stagingDir, job, extra = {}) {
1026
+ try {
1027
+ await fsp.mkdir(stagingDir, { recursive: true });
1028
+ const payload = {
1029
+ repoId: job.repoId,
1030
+ label: job.label,
1031
+ modality: job.modality,
1032
+ capabilities: job.capabilities,
1033
+ revision: job.revision,
1034
+ providerFolder: job.providerFolder,
1035
+ folderName: job.folderName,
1036
+ registerInWork: extra.registerInWork !== false,
1037
+ nodeMeta: extra.nodeMeta || null,
1038
+ files: (job.files || []).map(f => ({ name: f.name, size: Number(f.size) || 0 })),
1039
+ totalBytes: Number(job.totalBytes) || 0,
1040
+ downloadedBytes: Number(job.downloadedBytes) || 0,
1041
+ status: job.status,
1042
+ error: job.error || null,
1043
+ updatedAt: Date.now(),
1044
+ };
1045
+ const tmp = path.join(stagingDir, `${DOWNLOAD_STATE_FILE}.tmp`);
1046
+ await fsp.writeFile(tmp, JSON.stringify(payload, null, 2), 'utf-8');
1047
+ await fsp.rename(tmp, path.join(stagingDir, DOWNLOAD_STATE_FILE));
1048
+ }
1049
+ catch { /* ignore state write error */ }
1050
+ }
1051
+
1052
+ function waitAbortable(ms, signal) {
1053
+ if (ms <= 0)
1054
+ return Promise.resolve();
1055
+ return new Promise((resolve, reject) => {
1056
+ if (signal?.aborted) {
1057
+ reject(new Error('Загрузка приостановлена пользователем'));
1058
+ return;
1059
+ }
1060
+ const timer = setTimeout(() => {
1061
+ signal?.removeEventListener('abort', onAbort);
1062
+ resolve();
1063
+ }, ms);
1064
+ const onAbort = () => {
1065
+ clearTimeout(timer);
1066
+ reject(new Error('Загрузка приостановлена пользователем'));
1067
+ };
1068
+ signal?.addEventListener('abort', onAbort, { once: true });
1069
+ });
1070
+ }
1071
+
1008
1072
  /**
1009
1073
  * Запустить прямую загрузку модели с Hugging Face в `MODELS/Local/<Имя>/#weights/`
1010
- * с поддержкой докачки (`Range`), отслеживанием прогресса и авто-созданием узла `$ai`.
1074
+ * с поддержкой докачки (`Range`), авто-ретраев при обрывах, паузы без потери скачанного и авто-созданием узла `$ai`.
1011
1075
  */
1012
1076
  export async function startHuggingFaceDownload({
1013
1077
  repoId,
@@ -1018,135 +1082,282 @@ export async function startHuggingFaceDownload({
1018
1082
  rootDir = process.cwd(),
1019
1083
  providerFolder = 'Local',
1020
1084
  targetNodeName = '',
1085
+ nodeMeta = null,
1021
1086
  registerInWork = true,
1022
1087
  waitForCompletion = false,
1088
+ maxRetries = 20,
1089
+ retryBaseDelayMs = 3000,
1023
1090
  fetchImpl = globalThis.fetch,
1024
1091
  } = {}) {
1025
1092
  const cleanId = validateRepoId(repoId);
1093
+ const safeProvider = String(providerFolder || 'Local').replace(/[<>:"/\\|?*]/g, '-');
1094
+
1095
+ // Если эта модель уже скачивается прямо сейчас — возвращаем активную задачу без дублирования
1096
+ for (const entry of _downloads.values()) {
1097
+ if (
1098
+ entry.job.status === 'downloading'
1099
+ && entry.job.providerFolder === safeProvider
1100
+ && (entry.job.repoId === cleanId || (targetNodeName && entry.job.folderName === targetNodeName))
1101
+ ) {
1102
+ return { ...entry.job };
1103
+ }
1104
+ }
1105
+
1026
1106
  const repoMeta = await inspectHuggingFaceRepo(cleanId, { revision, token, fetchImpl });
1027
1107
  const selected = selectFilesToDownload(repoMeta, { files, quant });
1028
1108
  if (!selected.length)
1029
1109
  throw new Error(`В репозитории ${cleanId} не найдено подходящих файлов весов (.gguf / .safetensors)`);
1030
1110
 
1031
- const safeProvider = String(providerFolder || 'Local').replace(/[<>:"/\\|?*]/g, '-');
1032
1111
  const folderName = targetNodeName
1033
1112
  ? String(targetNodeName).replace(/[<>:"/\\|?*]/g, '-')
1034
1113
  : safeModelFolderName(cleanId, quant && selected.some(f => f.kind === 'gguf') ? quant : '');
1035
1114
  const modelDir = path.join(rootDir, 'MODELS', safeProvider, folderName);
1036
1115
  const weightsDir = path.join(modelDir, '#weights');
1116
+ const stagingDir = path.join(rootDir, 'MODELS', safeProvider, '#downloads', folderName);
1037
1117
  const primary = selected.find(f => f.name.endsWith('.gguf'))?.name
1038
1118
  || selected.find(f => f.name.endsWith('.safetensors') || f.name.endsWith('.hgn') || f.name.endsWith('.hnpw'))?.name
1039
1119
  || selected[0]?.name || '';
1040
1120
 
1041
- // Сначала создаём $ai/class.js (только для новых узлов в /MODELS/Local), чтобы папка с первой миллисекунды распознавалась сервером как $ai, а не $folder
1042
- if (registerInWork && safeProvider === 'Local') {
1043
- await registerLocalModelNode({
1044
- rootDir,
1045
- folderName,
1046
- label: `${cleanId.split('/')[1] || cleanId}${quant && primary.endsWith('.gguf') ? ' (' + quant + ')' : ''}`,
1047
- repoId: cleanId,
1048
- modality: repoMeta.modality || 'llm',
1049
- capabilities: repoMeta.capabilities || ['chat'],
1050
- weightsDir,
1051
- primaryFile: path.basename(primary),
1052
- });
1121
+ const displayLabel = nodeMeta?.label
1122
+ || `${cleanId.split('/')[1] || cleanId}${quant && primary.endsWith('.gguf') ? ' (' + quant + ')' : ''}`;
1123
+
1124
+ await fsp.mkdir(stagingDir, { recursive: true });
1125
+
1126
+ // Убираем старые завершённые/паузовые записи для той же папки из памяти
1127
+ for (const [k, entry] of _downloads.entries()) {
1128
+ if (entry.job.status !== 'downloading' && entry.job.providerFolder === safeProvider && entry.job.folderName === folderName)
1129
+ _downloads.delete(k);
1130
+ }
1131
+
1132
+ const jobFiles = [];
1133
+ for (const f of selected) {
1134
+ const size = Number(f.size) || 0;
1135
+ const stagedFile = path.join(stagingDir, path.basename(f.name));
1136
+ const partFile = stagedFile + '.part';
1137
+ let downloaded = 0;
1138
+ let done = false;
1139
+ try {
1140
+ const stDone = await fsp.stat(stagedFile);
1141
+ if (stDone.isFile() && stDone.size > 0 && (!size || stDone.size === size)) {
1142
+ downloaded = stDone.size;
1143
+ done = true;
1144
+ }
1145
+ }
1146
+ catch { /* ещё не завершён */ }
1147
+ if (!done) {
1148
+ try {
1149
+ const stPart = await fsp.stat(partFile);
1150
+ if (stPart.isFile())
1151
+ downloaded = stPart.size;
1152
+ }
1153
+ catch { /* .part ещё нет */ }
1154
+ }
1155
+ jobFiles.push({ name: f.name, size: size || (done ? downloaded : 0), downloaded, done });
1053
1156
  }
1054
- await fsp.mkdir(weightsDir, { recursive: true });
1055
1157
 
1056
1158
  const jobId = 'hf_' + crypto.randomUUID().slice(0, 8);
1057
- const totalBytes = selected.reduce((acc, f) => acc + (Number(f.size) || 0), 0);
1159
+ const totalBytes = jobFiles.reduce((acc, f) => acc + (Number(f.size) || 0), 0);
1160
+ const initialDownloaded = jobFiles.reduce((acc, f) => acc + (Number(f.downloaded) || 0), 0);
1161
+ const initialProgress = totalBytes > 0 ? Math.min(99, Math.round((initialDownloaded / totalBytes) * 100)) : 0;
1058
1162
  const controller = new AbortController();
1163
+ let keepFilesOnAbort = true;
1059
1164
 
1060
1165
  const job = {
1061
1166
  id: jobId,
1062
1167
  repoId: cleanId,
1063
- modality: repoMeta.modality || 'llm',
1064
- capabilities: repoMeta.capabilities || ['chat'],
1168
+ label: displayLabel,
1169
+ modality: nodeMeta?.modality || repoMeta.modality || 'llm',
1170
+ capabilities: nodeMeta?.capabilities || repoMeta.capabilities || ['chat'],
1065
1171
  revision: String(revision || 'main'),
1066
1172
  providerFolder: safeProvider,
1067
1173
  folderName,
1174
+ rootDir,
1175
+ stagingDir,
1068
1176
  weightsDir,
1069
1177
  status: 'downloading',
1070
- files: selected.map(f => ({ name: f.name, size: Number(f.size) || 0, downloaded: 0, done: false })),
1071
- currentFile: selected[0]?.name || '',
1072
- downloadedBytes: 0,
1178
+ files: jobFiles,
1179
+ currentFile: (jobFiles.find(f => !f.done) || jobFiles[0])?.name || '',
1180
+ downloadedBytes: initialDownloaded,
1073
1181
  totalBytes,
1074
- progress: 0,
1182
+ progress: initialProgress,
1075
1183
  speedMBs: 0,
1184
+ etaSeconds: null,
1185
+ retryAttempt: 0,
1186
+ retryError: '',
1076
1187
  startedAt: Date.now(),
1077
1188
  finishedAt: null,
1078
1189
  modelPath: `/MODELS/${safeProvider}/${folderName}`,
1079
1190
  error: null,
1080
1191
  };
1081
- _downloads.set(jobId, { job, controller });
1192
+ const entryMeta = {
1193
+ job,
1194
+ controller,
1195
+ nodeMeta,
1196
+ registerInWork,
1197
+ setKeepFiles: (v) => { keepFilesOnAbort = Boolean(v); },
1198
+ };
1199
+ _downloads.set(jobId, entryMeta);
1200
+ await writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
1082
1201
 
1083
1202
  const runPromise = (async () => {
1084
1203
  const t0 = Date.now();
1204
+ let sessionDownloadedBytes = 0;
1205
+ const updateMetrics = () => {
1206
+ job.downloadedBytes = job.files.reduce((acc, f) => acc + (Number(f.downloaded) || 0), 0);
1207
+ if (job.totalBytes > 0)
1208
+ job.progress = Math.min(99, Math.round((job.downloadedBytes / job.totalBytes) * 100));
1209
+ const elapsedSec = Math.max(0.2, (Date.now() - t0) / 1000);
1210
+ const bytesPerSec = sessionDownloadedBytes / elapsedSec;
1211
+ job.speedMBs = +(bytesPerSec / (1024 * 1024)).toFixed(2);
1212
+ if (job.totalBytes > 0 && bytesPerSec > 1024) {
1213
+ const remaining = Math.max(0, job.totalBytes - job.downloadedBytes);
1214
+ job.etaSeconds = Math.round(remaining / bytesPerSec);
1215
+ }
1216
+ };
1217
+
1085
1218
  try {
1086
1219
  for (const fileEntry of job.files) {
1087
1220
  if (controller.signal.aborted)
1088
- throw new Error('Загрузка отменена пользователем');
1089
- job.currentFile = fileEntry.name;
1090
- const destFile = path.join(weightsDir, path.basename(fileEntry.name));
1091
- const partFile = destFile + '.part';
1092
-
1093
- let existingSize = 0;
1094
- try {
1095
- const st = await fsp.stat(partFile);
1096
- existingSize = st.size;
1097
- }
1098
- catch { /* файла ещё нет */ }
1221
+ throw new Error('Загрузка приостановлена пользователем');
1222
+ if (fileEntry.done)
1223
+ continue;
1099
1224
 
1225
+ job.currentFile = fileEntry.name;
1226
+ const stagedFile = path.join(stagingDir, path.basename(fileEntry.name));
1227
+ const partFile = stagedFile + '.part';
1100
1228
  const encodedPath = fileEntry.name.split('/').map(encodeURIComponent).join('/');
1101
1229
  const url = `${HF_ORIGIN}/${cleanId}/resolve/${encodeURIComponent(job.revision)}/${encodedPath}`;
1102
- const headers = hfHeaders(token);
1103
- if (existingSize > 0)
1104
- headers.Range = `bytes=${existingSize}-`;
1105
-
1106
- const res = await fetchImpl(url, { headers, signal: controller.signal });
1107
- if (!res.ok && res.status !== 206 && res.status !== 416)
1108
- throw new Error(`Ошибка загрузки ${fileEntry.name}: HTTP ${res.status}`);
1109
-
1110
- const isPartial = res.status === 206;
1111
- if (!isPartial && res.status !== 416)
1112
- existingSize = 0;
1113
-
1114
- const contentLen = Number(res.headers?.get?.('content-length') || 0);
1115
- if (!fileEntry.size && contentLen > 0) {
1116
- fileEntry.size = existingSize + contentLen;
1117
- job.totalBytes = job.files.reduce((acc, f) => acc + (Number(f.size) || 0), 0);
1118
- }
1119
1230
 
1120
- fileEntry.downloaded = existingSize;
1231
+ let attempt = 0;
1232
+ while (true) {
1233
+ if (controller.signal.aborted)
1234
+ throw new Error('Загрузка приостановлена пользователем');
1235
+
1236
+ let existingSize = 0;
1237
+ try {
1238
+ const st = await fsp.stat(partFile);
1239
+ if (st.isFile())
1240
+ existingSize = st.size;
1241
+ }
1242
+ catch { /* файла ещё нет */ }
1243
+
1244
+ if (fileEntry.size > 0 && existingSize >= fileEntry.size) {
1245
+ await fsp.rename(partFile, stagedFile);
1246
+ fileEntry.downloaded = fileEntry.size;
1247
+ fileEntry.done = true;
1248
+ updateMetrics();
1249
+ break;
1250
+ }
1251
+
1252
+ try {
1253
+ const headers = hfHeaders(token);
1254
+ if (existingSize > 0)
1255
+ headers.Range = `bytes=${existingSize}-`;
1256
+
1257
+ const res = await fetchImpl(url, { headers, signal: controller.signal });
1258
+ if (res.status === 416) {
1259
+ if (existingSize > 0 && (!fileEntry.size || existingSize >= fileEntry.size)) {
1260
+ await fsp.rename(partFile, stagedFile);
1261
+ fileEntry.size = fileEntry.size || existingSize;
1262
+ fileEntry.downloaded = existingSize;
1263
+ fileEntry.done = true;
1264
+ updateMetrics();
1265
+ break;
1266
+ }
1267
+ await fsp.rm(partFile, { force: true }).catch(() => {});
1268
+ existingSize = 0;
1269
+ const err416 = new Error(`Сбой Range для ${fileEntry.name}: HTTP 416`);
1270
+ err416.retryable = true;
1271
+ throw err416;
1272
+ }
1273
+ if (!res.ok && res.status !== 206) {
1274
+ const errHttp = new Error(`Ошибка загрузки ${fileEntry.name}: HTTP ${res.status}`);
1275
+ errHttp.httpStatus = res.status;
1276
+ throw errHttp;
1277
+ }
1278
+
1279
+ const isPartial = res.status === 206;
1280
+ if (!isPartial)
1281
+ existingSize = 0;
1282
+
1283
+ const contentLen = Number(res.headers?.get?.('content-length') || 0);
1284
+ if (!fileEntry.size && contentLen > 0) {
1285
+ fileEntry.size = existingSize + contentLen;
1286
+ job.totalBytes = job.files.reduce((acc, f) => acc + (Number(f.size) || 0), 0);
1287
+ }
1121
1288
 
1122
- if (res.status !== 416 && res.body) {
1123
- const flags = isPartial ? 'a' : 'w';
1124
- const out = fs.createWriteStream(partFile, { flags });
1125
- for await (const chunk of res.body) {
1126
- if (controller.signal.aborted) {
1127
- out.destroy();
1128
- throw new Error('Загрузка отменена пользователем');
1289
+ fileEntry.downloaded = existingSize;
1290
+ job.retryAttempt = 0;
1291
+ job.retryError = '';
1292
+ updateMetrics();
1293
+
1294
+ if (res.body) {
1295
+ const flags = isPartial ? 'a' : 'w';
1296
+ const out = fs.createWriteStream(partFile, { flags });
1297
+ try {
1298
+ for await (const chunk of res.body) {
1299
+ if (controller.signal.aborted)
1300
+ throw new Error('Загрузка приостановлена пользователем');
1301
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1302
+ if (!out.write(buf))
1303
+ await new Promise(r => out.once('drain', r));
1304
+ fileEntry.downloaded += buf.length;
1305
+ sessionDownloadedBytes += buf.length;
1306
+ updateMetrics();
1307
+ }
1308
+ await new Promise((resolve, reject) => {
1309
+ out.end();
1310
+ out.once('finish', resolve);
1311
+ out.once('error', reject);
1312
+ });
1313
+ }
1314
+ catch (streamErr) {
1315
+ await new Promise((resolve) => {
1316
+ out.once('finish', resolve);
1317
+ out.once('error', resolve);
1318
+ out.once('close', resolve);
1319
+ try { out.end(); } catch { resolve(); }
1320
+ });
1321
+ if (!controller.signal.aborted && !streamErr.httpStatus)
1322
+ streamErr.retryable = true;
1323
+ throw streamErr;
1324
+ }
1129
1325
  }
1130
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1131
- if (!out.write(buf))
1132
- await new Promise(r => out.once('drain', r));
1133
- fileEntry.downloaded += buf.length;
1134
- job.downloadedBytes = job.files.reduce((acc, f) => acc + f.downloaded, 0);
1135
- if (job.totalBytes > 0)
1136
- job.progress = Math.min(99, Math.round((job.downloadedBytes / job.totalBytes) * 100));
1137
- const elapsedSec = Math.max(0.1, (Date.now() - t0) / 1000);
1138
- job.speedMBs = +((job.downloadedBytes / (1024 * 1024)) / elapsedSec).toFixed(2);
1326
+
1327
+ await fsp.rename(partFile, stagedFile);
1328
+ fileEntry.done = true;
1329
+ updateMetrics();
1330
+ break;
1331
+ }
1332
+ catch (err) {
1333
+ if (controller.signal.aborted)
1334
+ throw err;
1335
+ if (!isRetryableDownloadError(err) || attempt >= maxRetries)
1336
+ throw err;
1337
+ attempt++;
1338
+ job.retryAttempt = attempt;
1339
+ job.retryError = String(err?.message || err);
1340
+ await writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
1341
+ const delay = Math.min(30000, retryBaseDelayMs * attempt);
1342
+ await waitAbortable(delay, controller.signal);
1139
1343
  }
1140
- await new Promise((resolve, reject) => {
1141
- out.end();
1142
- out.once('finish', resolve);
1143
- out.once('error', reject);
1144
- });
1145
1344
  }
1345
+ }
1146
1346
 
1147
- await fsp.rename(partFile, destFile);
1148
- fileEntry.done = true;
1347
+ // Переносим готовые файлы из скрытой папки #downloads в целевую папку модели #weights
1348
+ await fsp.mkdir(weightsDir, { recursive: true });
1349
+ for (const fileEntry of job.files) {
1350
+ const stagedFile = path.join(stagingDir, path.basename(fileEntry.name));
1351
+ const destFile = path.join(weightsDir, path.basename(fileEntry.name));
1352
+ try {
1353
+ await fsp.rename(stagedFile, destFile);
1354
+ }
1355
+ catch {
1356
+ await fsp.copyFile(stagedFile, destFile);
1357
+ await fsp.unlink(stagedFile).catch(() => {});
1358
+ }
1149
1359
  }
1360
+ await fsp.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
1150
1361
 
1151
1362
  const manifestFile = path.join(weightsDir, 'hf-manifest.json');
1152
1363
  await fsp.writeFile(manifestFile, JSON.stringify({
@@ -1158,7 +1369,29 @@ export async function startHuggingFaceDownload({
1158
1369
  files: job.files,
1159
1370
  }, null, 2), 'utf-8');
1160
1371
 
1372
+ // Регистрируем узел $ai/class.js только после полного завершения скачивания весов
1373
+ if (registerInWork && safeProvider === 'Local') {
1374
+ await registerLocalModelNode({
1375
+ rootDir,
1376
+ folderName,
1377
+ label: displayLabel,
1378
+ repoId: cleanId,
1379
+ model: nodeMeta?.model || '',
1380
+ protocol: nodeMeta?.protocol || '',
1381
+ icon: nodeMeta?.icon || '',
1382
+ modality: job.modality,
1383
+ capabilities: job.capabilities,
1384
+ efforts: nodeMeta?.efforts || null,
1385
+ maxTokens: nodeMeta?.maxTokens,
1386
+ maxOutput: nodeMeta?.maxOutput,
1387
+ baseUrl: nodeMeta?.baseUrl,
1388
+ weightsDir,
1389
+ primaryFile: path.basename(primary),
1390
+ });
1391
+ }
1392
+
1161
1393
  job.progress = 100;
1394
+ job.etaSeconds = 0;
1162
1395
  job.status = 'completed';
1163
1396
  job.finishedAt = Date.now();
1164
1397
  try {
@@ -1170,23 +1403,21 @@ export async function startHuggingFaceDownload({
1170
1403
  catch { /* ignore */ }
1171
1404
  }
1172
1405
  catch (err) {
1173
- job.status = controller.signal.aborted ? 'cancelled' : 'failed';
1174
- job.error = String(err?.message || err);
1406
+ if (controller.signal.aborted) {
1407
+ job.status = keepFilesOnAbort ? 'paused' : 'cancelled';
1408
+ job.error = keepFilesOnAbort ? null : String(err?.message || err);
1409
+ }
1410
+ else {
1411
+ job.status = 'failed';
1412
+ job.error = String(err?.message || err);
1413
+ }
1414
+ job.etaSeconds = null;
1175
1415
  job.finishedAt = Date.now();
1176
- // Если ни один файл весов(.gguf / .safetensors / .hgn / .hnpw) не скачался целиком — убираем недокачанную папку
1177
- const hasWeights = job.files.some(f => f.done && /\.(gguf|safetensors|hgn|hnpw|bin|onnx)$/i.test(f.name));
1178
- if (!hasWeights) {
1179
- if (safeProvider === 'Local') {
1180
- await fsp.rm(modelDir, { recursive: true, force: true }).catch(() => {});
1181
- }
1182
- else {
1183
- await fsp.rm(weightsDir, { recursive: true, force: true }).catch(() => {});
1184
- }
1185
- try {
1186
- const localNode = await globalThis.WORK?.get_item?.(`/MODELS/${safeProvider}`);
1187
- localNode?.reset?.();
1188
- }
1189
- catch { /* ignore */ }
1416
+ if (controller.signal.aborted && !keepFilesOnAbort) {
1417
+ await fsp.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
1418
+ }
1419
+ else {
1420
+ await writeDownloadStateSafe(stagingDir, job, { nodeMeta, registerInWork });
1190
1421
  }
1191
1422
  }
1192
1423
  })();
@@ -1202,16 +1433,161 @@ export function getHuggingFaceDownload(jobId) {
1202
1433
  return entry ? { ...entry.job } : null;
1203
1434
  }
1204
1435
 
1205
- export function listHuggingFaceDownloads() {
1206
- return [..._downloads.values()].map(e => ({ ...e.job })).sort((a, b) => b.startedAt - a.startedAt);
1436
+ export function listHuggingFaceDownloads(rootDir = process.cwd()) {
1437
+ const inMemory = [..._downloads.values()].map(e => ({ ...e.job }));
1438
+ const seenFolders = new Set(inMemory.map(j => `${j.providerFolder}:${j.folderName}`));
1439
+
1440
+ // Подхватываем недокачанные папки из MODELS/Local/#downloads/* (включая оставшиеся после рестарта)
1441
+ const downloadsRoot = path.join(rootDir, 'MODELS', 'Local', '#downloads');
1442
+ if (fs.existsSync(downloadsRoot)) {
1443
+ try {
1444
+ const entries = fs.readdirSync(downloadsRoot, { withFileTypes: true });
1445
+ for (const e of entries) {
1446
+ if (!e.isDirectory() || e.name.startsWith('.') || e.name.startsWith('_import_') || e.name.startsWith('_tar_import_'))
1447
+ continue;
1448
+ if (seenFolders.has(`Local:${e.name}`))
1449
+ continue;
1450
+ const folderDir = path.join(downloadsRoot, e.name);
1451
+ const stateFile = path.join(folderDir, DOWNLOAD_STATE_FILE);
1452
+ let state = {};
1453
+ if (fs.existsSync(stateFile)) {
1454
+ try { state = JSON.parse(fs.readFileSync(stateFile, 'utf-8')); }
1455
+ catch { /* ignore */ }
1456
+ }
1457
+ const dirFiles = fs.readdirSync(folderDir, { withFileTypes: true });
1458
+ let diskBytes = 0;
1459
+ const parsedFiles = [];
1460
+ for (const f of dirFiles) {
1461
+ if (!f.isFile() || f.name === DOWNLOAD_STATE_FILE || f.name.endsWith('.tmp'))
1462
+ continue;
1463
+ try {
1464
+ const st = fs.statSync(path.join(folderDir, f.name));
1465
+ diskBytes += st.size || 0;
1466
+ parsedFiles.push({
1467
+ name: f.name.replace(/\.part$/, ''),
1468
+ size: st.size || 0,
1469
+ downloaded: st.size || 0,
1470
+ done: !f.name.endsWith('.part'),
1471
+ });
1472
+ }
1473
+ catch { /* ignore */ }
1474
+ }
1475
+ if (diskBytes <= 0 && !state.repoId)
1476
+ continue;
1477
+ const totalBytes = Number(state.totalBytes) || 0;
1478
+ const progress = totalBytes > 0 ? Math.min(99, Math.round((diskBytes / totalBytes) * 100)) : 0;
1479
+ inMemory.push({
1480
+ id: `disk_${e.name}`,
1481
+ repoId: state.repoId || '',
1482
+ label: state.label || e.name,
1483
+ modality: state.modality || 'llm',
1484
+ capabilities: state.capabilities || ['chat'],
1485
+ revision: state.revision || 'main',
1486
+ providerFolder: 'Local',
1487
+ folderName: e.name,
1488
+ status: state.status === 'failed' ? 'failed' : 'paused',
1489
+ files: Array.isArray(state.files) && state.files.length ? state.files : parsedFiles,
1490
+ currentFile: parsedFiles[0]?.name || '',
1491
+ downloadedBytes: diskBytes,
1492
+ totalBytes,
1493
+ progress,
1494
+ speedMBs: 0,
1495
+ etaSeconds: null,
1496
+ startedAt: state.updatedAt || Date.now(),
1497
+ finishedAt: state.updatedAt || Date.now(),
1498
+ modelPath: `/MODELS/Local/${e.name}`,
1499
+ error: state.error || null,
1500
+ nodeMeta: state.nodeMeta || null,
1501
+ canResume: true,
1502
+ onDiskOnly: true,
1503
+ });
1504
+ }
1505
+ }
1506
+ catch { /* ignore */ }
1507
+ }
1508
+
1509
+ return inMemory.sort((a, b) => (b.startedAt || 0) - (a.startedAt || 0));
1510
+ }
1511
+
1512
+ export function pauseHuggingFaceDownload(jobId) {
1513
+ const entry = _downloads.get(String(jobId || ''));
1514
+ if (!entry)
1515
+ return null;
1516
+ entry.setKeepFiles?.(true);
1517
+ entry.controller.abort();
1518
+ entry.job.status = 'paused';
1519
+ entry.job.etaSeconds = null;
1520
+ entry.job.finishedAt = Date.now();
1521
+ return { ...entry.job };
1522
+ }
1523
+
1524
+ export async function discardHuggingFaceDownload({ jobId = '', folderName = '', rootDir = process.cwd() } = {}) {
1525
+ const key = String(jobId || '');
1526
+ const entry = key ? _downloads.get(key) : null;
1527
+ let targetFolder = String(folderName || entry?.job?.folderName || '').replace(/[<>:"/\\|?*]/g, '').trim();
1528
+ if (entry) {
1529
+ entry.setKeepFiles?.(false);
1530
+ if (entry.job.status === 'downloading')
1531
+ entry.controller.abort();
1532
+ entry.job.status = 'cancelled';
1533
+ _downloads.delete(key);
1534
+ }
1535
+ if (!targetFolder && key.startsWith('disk_'))
1536
+ targetFolder = key.slice(5);
1537
+ if (targetFolder) {
1538
+ const stagingDir = path.join(rootDir, 'MODELS', 'Local', '#downloads', targetFolder);
1539
+ await fsp.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
1540
+ }
1541
+ return { ok: true, discarded: targetFolder || key };
1542
+ }
1543
+
1544
+ export async function resumeHuggingFaceDownload({
1545
+ jobId = '',
1546
+ folderName = '',
1547
+ repoId = '',
1548
+ quant = 'Q8_0',
1549
+ token = '',
1550
+ nodeMeta = null,
1551
+ rootDir = process.cwd(),
1552
+ fetchImpl = globalThis.fetch,
1553
+ } = {}) {
1554
+ const key = String(jobId || '');
1555
+ const entry = key ? _downloads.get(key) : null;
1556
+ const cleanFolder = String(folderName || entry?.job?.folderName || (key.startsWith('disk_') ? key.slice(5) : '')).trim();
1557
+ let state = {};
1558
+ if (cleanFolder) {
1559
+ const stateFile = path.join(rootDir, 'MODELS', 'Local', '#downloads', cleanFolder, DOWNLOAD_STATE_FILE);
1560
+ if (fs.existsSync(stateFile)) {
1561
+ try { state = JSON.parse(await fsp.readFile(stateFile, 'utf-8')); }
1562
+ catch { /* ignore */ }
1563
+ }
1564
+ }
1565
+ const resolvedRepo = repoId || entry?.job?.repoId || state.repoId;
1566
+ if (!resolvedRepo)
1567
+ throw new Error(`Не удалось определить репозиторий Hugging Face для докачки «${cleanFolder || key}»`);
1568
+
1569
+ return startHuggingFaceDownload({
1570
+ repoId: resolvedRepo,
1571
+ quant,
1572
+ revision: entry?.job?.revision || state.revision || 'main',
1573
+ token,
1574
+ rootDir,
1575
+ providerFolder: entry?.job?.providerFolder || state.providerFolder || 'Local',
1576
+ targetNodeName: cleanFolder,
1577
+ nodeMeta: nodeMeta || entry?.nodeMeta || state.nodeMeta || null,
1578
+ registerInWork: entry?.registerInWork ?? state.registerInWork ?? true,
1579
+ fetchImpl,
1580
+ });
1207
1581
  }
1208
1582
 
1209
- export function cancelHuggingFaceDownload(jobId) {
1583
+ export function cancelHuggingFaceDownload(jobId, { keepFiles = false } = {}) {
1210
1584
  const entry = _downloads.get(String(jobId || ''));
1211
1585
  if (!entry)
1212
1586
  return null;
1587
+ entry.setKeepFiles?.(Boolean(keepFiles));
1213
1588
  entry.controller.abort();
1214
- entry.job.status = 'cancelled';
1589
+ entry.job.status = keepFiles ? 'paused' : 'cancelled';
1590
+ entry.job.etaSeconds = null;
1215
1591
  entry.job.finishedAt = Date.now();
1216
1592
  return { ...entry.job };
1217
1593
  }