odant-work 1.0.55 → 1.0.56

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 (41) hide show
  1. package/#system/package-manifest.json +32 -38
  2. package/$server/$folder/$class/$structure/$server/class.js +17 -1
  3. package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +26 -1
  4. package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +8 -1
  5. package/SERVICES/$service/$folder/$storage/$service/handlers/pages/form/mcp/$handler/mcp.js +22 -4
  6. package/SERVICES/1C/$service/class.js +209 -0
  7. package/SERVICES/Bitrix24/$service/class.js +180 -0
  8. package/SERVICES/CBR/$service/class.js +263 -0
  9. package/SERVICES/DaData/$service/class.js +352 -0
  10. package/SERVICES/DuckDuckGo/$service/class.js +3 -2
  11. package/SERVICES/RuCalendar/$service/class.js +289 -0
  12. package/SERVICES/SearXNG/$service/class.js +3 -1
  13. package/SERVICES/Telegram/$service/class.js +170 -114
  14. package/SERVICES/Weather/$service/class.js +3 -1
  15. package/SERVICES/Yandex/$service/class.js +4 -2
  16. package/SERVICES/YandexDisk/$service/class.js +191 -0
  17. package/SERVICES/readme.md +31 -43
  18. package/package.json +1 -1
  19. package/sources/data/progress.md +14 -0
  20. package/sources/modules/agent/extensions.js +118 -39
  21. package/sources/modules/agent/voice.js +1 -1
  22. package/sources/modules/trainer/halogen.js +24 -3
  23. package/sources/modules/trainer/huggingface.js +73 -11
  24. package/sources/modules/trainer/index.js +54 -29
  25. package/sources/modules/trainer/local-engine.js +38 -8
  26. package/sources/modules/trainer/paths.js +8 -0
  27. package/sources/modules/trainer/providers.js +14 -0
  28. package/sources/modules/trainer/worker/local_infer_worker.py +160 -1
  29. package/sources/server/access/gateway.js +1 -0
  30. package/SERVICES/ArgoCD/$service/$folder/$class/$service/class.js +0 -356
  31. package/SERVICES/ArgoCD/$service/$folder/$class/$service/handlers/pages/form/orders/$handler/class.js +0 -244
  32. package/SERVICES/ArgoCD/$service/$folder/$class/$service/handlers/pages/form/settings/$handler/class.js +0 -135
  33. package/SERVICES/ArgoCD/$service/class.js +0 -4
  34. package/SERVICES/ArgoCD/$service/readme.md +0 -63
  35. package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/class.js +0 -10
  36. package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/methods/checkDomain/$method/class.js +0 -33
  37. package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/methods/provision/$method/class.js +0 -225
  38. package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/methods/submitOrder/$method/class.js +0 -77
  39. package/SERVICES/ArgoCD/PaaS/$service/$folder/$class/$service/readme.md +0 -33
  40. package/SERVICES/ArgoCD/PaaS/$service/class.js +0 -347
  41. package/SERVICES/ArgoCD/PaaS/$service/order/pass.order +0 -9
@@ -367,6 +367,19 @@ function isPiperOnnxDirSync(weightsDir) {
367
367
  return onnxFiles.some(f => fs.existsSync(`${f}.json`));
368
368
  }
369
369
 
370
+ function isKokoroDirSync(weightsDir) {
371
+ if (!weightsDir || !fs.existsSync(weightsDir))
372
+ return false;
373
+ try {
374
+ const files = fs.readdirSync(weightsDir);
375
+ const hasPth = files.some(f => /^kokoro.*\.pth$/i.test(f) && !f.endsWith('.part'));
376
+ return hasPth && files.includes('config.json');
377
+ }
378
+ catch {
379
+ return false;
380
+ }
381
+ }
382
+
370
383
  export function packagesForModality(modality = 'llm', weightsDir = '') {
371
384
  const mod = String(modality || 'llm').toLowerCase();
372
385
  const hasOnnx = hasOnnxModelSync(weightsDir);
@@ -386,6 +399,8 @@ export function packagesForModality(modality = 'llm', weightsDir = '') {
386
399
  return ['torch', 'diffusers', 'accelerate', 'pillow', 'transformers', 'safetensors'];
387
400
  if ((mod === 'tts' || mod === 'voice') && isPiperOnnxDirSync(weightsDir))
388
401
  return ['piper-tts', 'onnxruntime'];
402
+ if ((mod === 'tts' || mod === 'voice') && isKokoroDirSync(weightsDir))
403
+ return ['torch', 'kokoro', 'soundfile'];
389
404
  if (mod === 'music' || mod === 'text-to-audio')
390
405
  return ['torch', 'transformers', 'accelerate', 'safetensors', 'soundfile'];
391
406
  if (mod === 'tts' || mod === 'voice')
@@ -754,6 +769,15 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
754
769
  throw new Error(wInsp.incompatibleReason);
755
770
  }
756
771
 
772
+ const aiCaps = (Array.isArray(ai?.capabilities || ai?.DATA?.capabilities)
773
+ ? (ai?.capabilities || ai?.DATA?.capabilities)
774
+ : []).map(c => String(c).toLowerCase());
775
+ const aiMod = String(ai?.modality || ai?.DATA?.modality || '').toLowerCase();
776
+ const nonChatCap = aiCaps.find(c => ['music', 'tts', 'stt', 'asr', 'image', 'video', 'embeddings', 'rerank'].includes(c));
777
+ if ((nonChatCap && !aiCaps.includes('chat')) || ['image', 'video', 'embed', 'rerank', 'tts', 'stt', 'music'].includes(aiMod)) {
778
+ throw new Error(`Эта модель (${nonChatCap || aiMod}) не предназначена для текстового чата — используйте соответствующий режим в её карточке.`);
779
+ }
780
+
757
781
  if (wInsp.hasGguf || wInsp.hasBuboManifest || ai?.protocol === 'halogen' || ai?.DATA?.protocol === 'halogen') {
758
782
  const backend = await ensureHalogenBackendRunning({
759
783
  baseUrl: ai?.baseUrl || ai?.DATA?.baseUrl,
@@ -769,15 +793,7 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
769
793
  throw new Error('Загрузка весов модели ещё не завершена (проверьте вкладку «Модели» в /MODELS/Local).');
770
794
  }
771
795
 
772
- const aiCaps = (Array.isArray(ai?.capabilities || ai?.DATA?.capabilities)
773
- ? (ai?.capabilities || ai?.DATA?.capabilities)
774
- : []).map(c => String(c).toLowerCase());
775
- const aiMod = String(ai?.modality || ai?.DATA?.modality || '').toLowerCase();
776
- const nonChatCap = aiCaps.find(c => ['music', 'tts', 'stt', 'asr', 'image', 'video', 'embeddings', 'rerank'].includes(c));
777
796
  if (wInsp.hasReadyWeights) {
778
- if ((nonChatCap && !aiCaps.includes('chat')) || ['image', 'video', 'embed', 'rerank', 'tts', 'stt', 'music'].includes(aiMod)) {
779
- throw new Error(`Эта модель (${nonChatCap || aiMod}) не предназначена для текстового чата — используйте соответствующий режим в её карточке.`);
780
- }
781
797
  if (!wInsp.hasSafetensors) {
782
798
  throw new Error(`Веса модели уже скачаны (формат: ${wInsp.weightFormat || 'other'}), но для локального текстового чата требуются .safetensors + tokenizer.json.`);
783
799
  }
@@ -970,8 +986,20 @@ export async function localRerank(ai, params = {}) {
970
986
  };
971
987
  }
972
988
 
989
+ function assertDiffusersModelIndex(weightsDir) {
990
+ if (!fs.existsSync(path.join(weightsDir, 'model_index.json'))) {
991
+ throw new Error(
992
+ 'В папке весов модели отсутствует model_index.json (конфигурация пайплайна Diffusers). '
993
+ + 'Скачанный файл является одиночным чекпоинтом (ComfyUI / single-file / GGUF) без VAE и текстового энкодера '
994
+ + 'и не может запускаться автономно. Установите полноценную Diffusers-модель из каталога '
995
+ + '(например Z-Image-Turbo, Lightricks/LTX-Video или Wan2.1-T2V).'
996
+ );
997
+ }
998
+ }
999
+
973
1000
  export async function localGenerateImage(ai, params = {}) {
974
1001
  const weightsDir = assertLocalWeightsReady(ai);
1002
+ assertDiffusersModelIndex(weightsDir);
975
1003
  const prompt = String(params.prompt || params.post || '').trim();
976
1004
  if (!prompt)
977
1005
  throw new Error('generateImage: пустой prompt');
@@ -998,6 +1026,7 @@ export async function localGenerateImage(ai, params = {}) {
998
1026
 
999
1027
  export async function localGenerateVideo(ai, params = {}) {
1000
1028
  const weightsDir = assertLocalWeightsReady(ai);
1029
+ assertDiffusersModelIndex(weightsDir);
1001
1030
  const prompt = String(params.prompt || params.post || '').trim();
1002
1031
  if (!prompt)
1003
1032
  throw new Error('generateVideo: пустой prompt');
@@ -1155,6 +1184,7 @@ const ALLOWED_PYTHON_DEPS = new Set([
1155
1184
  'qwen-tts',
1156
1185
  'qwen-asr',
1157
1186
  'piper-tts',
1187
+ 'kokoro',
1158
1188
  'imageio',
1159
1189
  'imageio-ffmpeg',
1160
1190
  'sentencepiece',
@@ -127,6 +127,8 @@ export function inspectWeightsDirectorySync(dirPath, platform = os.platform()) {
127
127
  hasHnpw: false,
128
128
  hasConfig: false,
129
129
  hasTokenizer: false,
130
+ hasModelIndex: false,
131
+ hasDiffusersDirs: false,
130
132
  incompatibleOnPlatform: false,
131
133
  incompatibleReason: '',
132
134
  };
@@ -159,6 +161,10 @@ export function inspectWeightsDirectorySync(dirPath, platform = os.platform()) {
159
161
  const hasOther = files.some(f => /\.(bin|onnx|onnx_data|pt|pth)$/i.test(f));
160
162
  const hasConfig = files.includes('config.json');
161
163
  const hasTokenizer = files.includes('tokenizer.json');
164
+ const hasModelIndex = files.includes('model_index.json');
165
+ const hasDiffusersDirs = ['transformer', 'unet', 'vae', 'text_encoder'].some(d =>
166
+ files.some(f => f.startsWith(`${d}/`)) || fs.existsSync(path.join(dirPath, d))
167
+ );
162
168
  const pendingDownload = hasParts || pendingState;
163
169
  // Основные веса уже на диске — модель работоспособна, даже если в фоне докачиваются
164
170
  // недостающие конфиги/подпапки (speech_tokenizer/, onnx/, индексы шардов).
@@ -210,6 +216,8 @@ export function inspectWeightsDirectorySync(dirPath, platform = os.platform()) {
210
216
  hasHnpw,
211
217
  hasConfig,
212
218
  hasTokenizer,
219
+ hasModelIndex,
220
+ hasDiffusersDirs,
213
221
  incompatibleOnPlatform,
214
222
  incompatibleReason,
215
223
  };
@@ -914,6 +914,20 @@ export function evaluateAiNodeActivitySync(item, rootDir = process.cwd()) {
914
914
  };
915
915
  }
916
916
  if (check.ready) {
917
+ const rawMod = String(data.modality || '').toLowerCase();
918
+ const capsArr = (Array.isArray(data.capabilities) ? data.capabilities : []).map(c => String(c).toLowerCase());
919
+ const modelIdent = `${data.hfRepo || ''} ${data.model || ''} ${modelName}`.toLowerCase();
920
+ const isDiffusionModel = rawMod === 'image' || rawMod === 'video'
921
+ || capsArr.includes('image') || capsArr.includes('video')
922
+ || /\b(ltx(?:[-_.]?(?:video|2(?:\.\d+)?|v))?|wan2(?:\.\d+)?|hunyuan[-_.]?video|cogvideo|flux|sdxl|z-image|qwen-image|sd3\.5|hidream|chroma)\b/.test(modelIdent);
923
+ if (isDiffusionModel && !check.info?.hasModelIndex && (check.info?.hasGguf || !check.info?.hasDiffusersDirs)) {
924
+ return {
925
+ active: false,
926
+ reason: 'Single-file / ComfyUI чекпоинт без model_index.json (пайплайна Diffusers) — не может запускаться автономно',
927
+ incompatibleOnPlatform: true,
928
+ configuredKey: false,
929
+ };
930
+ }
917
931
  return { active: true, reason: 'Активна (веса модели на диске)', configuredKey: true };
918
932
  }
919
933
  if (check.incompatible) {
@@ -763,6 +763,15 @@ def _load_image_pipeline(weights_dir, cache):
763
763
  key = ("image", weights_dir)
764
764
  if key in cache:
765
765
  return cache[key]
766
+ if not os.path.isfile(os.path.join(weights_dir, "model_index.json")):
767
+ raise RuntimeError(json.dumps({
768
+ "error": (
769
+ "В папке весов модели отсутствует model_index.json (конфигурация пайплайна Diffusers). "
770
+ "Скачанный файл является одиночным чекпоинтом (ComfyUI / single-file / GGUF) без VAE и текстового энкодера "
771
+ "и не может запускаться автономно. Установите полноценную Diffusers-модель из каталога "
772
+ "(например Z-Image-Turbo)."
773
+ )
774
+ }))
766
775
  try:
767
776
  import diffusers
768
777
  import accelerate # noqa: F401
@@ -849,6 +858,16 @@ def _load_video_pipeline(weights_dir, cache):
849
858
  key = ("video", weights_dir)
850
859
  if key in cache:
851
860
  return cache[key]
861
+ idx_path = os.path.join(weights_dir, "model_index.json")
862
+ if not os.path.isfile(idx_path):
863
+ raise RuntimeError(json.dumps({
864
+ "error": (
865
+ "В папке весов модели отсутствует model_index.json (конфигурация пайплайна Diffusers). "
866
+ "Скачанный файл является одиночным чекпоинтом (ComfyUI / single-file / GGUF) без VAE и текстового энкодера "
867
+ "и не может запускаться автономно. Установите полноценную Diffusers-модель из каталога "
868
+ "(например Lightricks/LTX-Video или Wan2.1-T2V)."
869
+ )
870
+ }))
852
871
  try:
853
872
  import diffusers
854
873
  import accelerate # noqa: F401
@@ -1516,11 +1535,148 @@ def _handle_tts_piper(req, cache, piper_files):
1516
1535
  }
1517
1536
 
1518
1537
 
1538
+ def _find_kokoro_files(weights_dir):
1539
+ if not weights_dir or not os.path.isdir(weights_dir):
1540
+ return None
1541
+ cfg_p = os.path.join(weights_dir, "config.json")
1542
+ if not os.path.isfile(cfg_p):
1543
+ return None
1544
+ pth_p = None
1545
+ try:
1546
+ for fn in sorted(os.listdir(weights_dir)):
1547
+ low = fn.lower()
1548
+ if low.startswith("kokoro") and low.endswith(".pth") and not low.endswith(".part"):
1549
+ pth_p = os.path.join(weights_dir, fn)
1550
+ break
1551
+ except Exception:
1552
+ return None
1553
+ if not pth_p:
1554
+ return None
1555
+ voices_dir = os.path.join(weights_dir, "voices")
1556
+ return pth_p, cfg_p, (voices_dir if os.path.isdir(voices_dir) else "")
1557
+
1558
+
1559
+ def _kokoro_lang_for_voice(voice_name):
1560
+ v = str(voice_name or "af_heart").strip().lower()
1561
+ if v.startswith(("bf_", "bm_")):
1562
+ return "b"
1563
+ if v.startswith(("ef_", "em_")):
1564
+ return "e"
1565
+ if v.startswith(("ff_", "fm_")):
1566
+ return "f"
1567
+ if v.startswith(("hf_", "hm_")):
1568
+ return "h"
1569
+ if v.startswith(("if_", "im_")):
1570
+ return "i"
1571
+ if v.startswith(("jf_", "jm_")):
1572
+ return "j"
1573
+ if v.startswith(("pf_", "pm_")):
1574
+ return "p"
1575
+ if v.startswith(("zf_", "zm_")):
1576
+ return "z"
1577
+ return "a"
1578
+
1579
+
1580
+ def _handle_tts_kokoro(req, cache, kokoro_files):
1581
+ pth_p, cfg_p, voices_dir = kokoro_files
1582
+ weights_dir = req["weightsDir"]
1583
+ text = str(req.get("text", "")).strip() or "Hello! Local Kokoro-82M speech synthesis in WORK is working."
1584
+ voice_name = str(req.get("voice") or "af_heart").strip() or "af_heart"
1585
+ lang_code = _kokoro_lang_for_voice(voice_name)
1586
+
1587
+ m_key = ("tts_kokoro_model", weights_dir)
1588
+ p_key = ("tts_kokoro_pipe", weights_dir, lang_code)
1589
+ was_cached = (m_key in cache) and (p_key in cache)
1590
+ t_load0 = time.time()
1591
+ try:
1592
+ from kokoro import KModel, KPipeline
1593
+ import numpy as np
1594
+ except Exception as e:
1595
+ raise RuntimeError(json.dumps(_missing_pkg_error(e, {
1596
+ "kokoro": "kokoro",
1597
+ "soundfile": "soundfile",
1598
+ })))
1599
+
1600
+ if m_key not in cache:
1601
+ device, _ = _best_device_and_dtype()
1602
+ try:
1603
+ kmodel = KModel(config=cfg_p, model=pth_p, repo_id="hexgrad/Kokoro-82M").to(device).eval()
1604
+ except Exception:
1605
+ device = "cpu"
1606
+ kmodel = KModel(config=cfg_p, model=pth_p, repo_id="hexgrad/Kokoro-82M").to("cpu").eval()
1607
+ cache[m_key] = (kmodel, device)
1608
+ kmodel, device = cache[m_key]
1609
+
1610
+ if p_key not in cache:
1611
+ cache[p_key] = KPipeline(lang_code=lang_code, repo_id="hexgrad/Kokoro-82M", model=kmodel)
1612
+ pipe = cache[p_key]
1613
+ load_ms = 0 if was_cached else int((time.time() - t_load0) * 1000)
1614
+
1615
+ voice_arg = voice_name
1616
+ if voices_dir:
1617
+ cand = os.path.join(voices_dir, f"{voice_name}.pt")
1618
+ if not os.path.isfile(cand):
1619
+ pts = sorted(f for f in os.listdir(voices_dir) if f.endswith(".pt"))
1620
+ if pts:
1621
+ cand = os.path.join(voices_dir, pts[0])
1622
+ voice_name = os.path.splitext(pts[0])[0]
1623
+ if os.path.isfile(cand):
1624
+ voice_arg = torch.load(cand, map_location="cpu", weights_only=True)
1625
+
1626
+ t_gen0 = time.time()
1627
+
1628
+ def _run_kokoro():
1629
+ chunks = []
1630
+ with torch.inference_mode():
1631
+ for _, _, audio in pipe(text, voice=voice_arg, speed=1.0):
1632
+ if audio is not None:
1633
+ if hasattr(audio, "detach"):
1634
+ audio = audio.detach().cpu().float().numpy()
1635
+ chunks.append(audio)
1636
+ return chunks
1637
+
1638
+ try:
1639
+ chunks = _run_kokoro()
1640
+ except Exception as e:
1641
+ if str(device).startswith("cuda") and _is_recoverable_gpu_error(e):
1642
+ try:
1643
+ torch.cuda.empty_cache()
1644
+ except Exception:
1645
+ pass
1646
+ device = "cpu"
1647
+ kmodel = kmodel.to("cpu").eval()
1648
+ cache[m_key] = (kmodel, "cpu")
1649
+ chunks = _run_kokoro()
1650
+ else:
1651
+ raise
1652
+
1653
+ if not chunks:
1654
+ raise RuntimeError(json.dumps({
1655
+ "error": "Kokoro-82M не смог синтезировать этот текст (модель поддерживает EN/FR/ES/IT/PT/JA/ZH; для русского языка используйте Piper TTS RU или Qwen3-TTS)."
1656
+ }))
1657
+ full_audio = np.concatenate(chunks) if len(chunks) > 1 else chunks[0]
1658
+ gen_ms = max(1, int((time.time() - t_gen0) * 1000))
1659
+ return {
1660
+ "audioBase64": _pcm_to_wav_base64(full_audio, 24000),
1661
+ "sampleRate": 24000,
1662
+ "ttsKind": "kokoro",
1663
+ "voiceUsed": voice_name,
1664
+ "instructUsed": "",
1665
+ "device": _describe_torch_device(device),
1666
+ "loadMs": load_ms,
1667
+ "genMs": gen_ms,
1668
+ "durationMs": gen_ms,
1669
+ }
1670
+
1671
+
1519
1672
  def handle_tts(req, cache):
1520
1673
  weights_dir = req["weightsDir"]
1521
1674
  piper_files = _find_piper_onnx_files(weights_dir)
1522
1675
  if piper_files:
1523
1676
  return _handle_tts_piper(req, cache, piper_files)
1677
+ kokoro_files = _find_kokoro_files(weights_dir)
1678
+ if kokoro_files:
1679
+ return _handle_tts_kokoro(req, cache, kokoro_files)
1524
1680
  text = str(req.get("text", "")).strip()
1525
1681
  language = _tts_language(req.get("language") or "Russian")
1526
1682
  instructions = str(req.get("instructions") or "").strip()
@@ -1983,7 +2139,10 @@ def main():
1983
2139
  elif op == "video":
1984
2140
  needed.extend(["diffusers", "accelerate", "pillow", "transformers", "imageio", "imageio-ffmpeg"])
1985
2141
  elif op == "tts":
1986
- needed.extend(["qwen-tts", "soundfile", "transformers"])
2142
+ if _find_kokoro_files(str(req.get("weightsDir") or "")):
2143
+ needed.extend(["kokoro", "soundfile"])
2144
+ else:
2145
+ needed.extend(["qwen-tts", "soundfile", "transformers"])
1987
2146
  elif op == "music":
1988
2147
  needed.extend(["transformers", "accelerate", "soundfile"])
1989
2148
  elif op == "stt":
@@ -74,6 +74,7 @@ export const MEMBERS = Object.freeze({
74
74
  delete: L.ADMIN, npm: L.ADMIN, restart_normal: L.ADMIN, read_secret: L.ADMIN,
75
75
  save_secret: L.ADMIN, clear_rag: L.ADMIN, security_log: L.ADMIN, agent_panel: L.ADMIN,
76
76
  set_enabled: L.ADMIN, export_archive: L.READ, import_archive: L.ADMIN, delete_log_entry: L.WRITE,
77
+ distro_info: L.READ, export_distro: L.READ,
77
78
  });
78
79
 
79
80
  /** Никогда не вызываются снаружи, даже если объявлены в class.js. */