odant-work 1.0.40 → 1.0.42

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.
@@ -480,6 +480,7 @@ const BACKEND_LOG_TAIL_CHARS = 8192;
480
480
  let _managedProc = null;
481
481
  let _managedInfo = null;
482
482
  let _lastManagedExit = null;
483
+ let _lastSpeculationFallback = null;
483
484
 
484
485
  function appendLogTail(prev, chunk) {
485
486
  const text = prev + (Buffer.isBuffer(chunk) ? chunk.toString('utf-8') : String(chunk || ''));
@@ -489,8 +490,9 @@ function appendLogTail(prev, chunk) {
489
490
  function attachManagedBackendProcess(proc, meta = {}) {
490
491
  _managedProc = proc;
491
492
  _lastManagedExit = null;
493
+ const { onEarlyExit, ...info } = meta || {};
492
494
  const state = {
493
- ...meta,
495
+ ...info,
494
496
  pid: proc?.pid,
495
497
  startedAt: Date.now(),
496
498
  stdout: '',
@@ -519,10 +521,18 @@ function attachManagedBackendProcess(proc, meta = {}) {
519
521
  errorMessage: state.errorMessage,
520
522
  exitedAt: Date.now(),
521
523
  };
524
+ const earlyExit = Date.now() - state.startedAt < 30000 && code !== 0;
522
525
  if (_managedProc === proc) {
523
526
  _managedProc = null;
524
527
  _managedInfo = null;
525
528
  }
529
+ // Движок мог не принять новый флаг спекуляции — отдаём управление повторному запуску без него.
530
+ if (earlyExit && typeof onEarlyExit === 'function') {
531
+ setTimeout(() => {
532
+ try { onEarlyExit(code); }
533
+ catch { /* ignore */ }
534
+ }, 250);
535
+ }
526
536
  });
527
537
  return state;
528
538
  }
@@ -1100,6 +1110,8 @@ export async function probeHalogenServer(baseUrl = HALOGEN_DEFAULT_BASE_URL, { f
1100
1110
  ? handlesRaw
1101
1111
  : listHalogenSessionHandles(),
1102
1112
  managedProcess: _managedInfo,
1113
+ speculation: _managedInfo?.speculation || null,
1114
+ speculationFallback: _lastSpeculationFallback,
1103
1115
  windowsEnv: inspectWindowsHalogenEnvironment({ rootDir }),
1104
1116
  };
1105
1117
  }
@@ -1401,6 +1413,328 @@ export async function prepareWindowsBuboRuntime({
1401
1413
  }
1402
1414
  }
1403
1415
 
1416
+ /**
1417
+ * Настройки движка Halowin Bubo по умолчанию: спекулятивное декодирование (MTP + Draft Head),
1418
+ * Prompt Lookup (n-граммы), профиль KV-сессий и NPU-prefill.
1419
+ */
1420
+ export const DEFAULT_ENGINE_SETTINGS = Object.freeze({
1421
+ speculation: 'auto',
1422
+ draftMax: 8,
1423
+ promptLookup: 'auto',
1424
+ profile: 'subagents',
1425
+ npuPrefill: true,
1426
+ });
1427
+
1428
+ const ENGINE_STATE_MODES = ['auto', 'on', 'off'];
1429
+
1430
+ function clampInt(value, min, max, fallback) {
1431
+ const n = Number(value);
1432
+ if (!Number.isFinite(n))
1433
+ return fallback;
1434
+ return Math.min(max, Math.max(min, Math.round(n)));
1435
+ }
1436
+
1437
+ /** Файл настроек движка (`MODELS/Local/$provider/#runtime/engine.json`). */
1438
+ export function engineSettingsFile(rootDir = process.cwd()) {
1439
+ return path.join(localRuntimeDir(rootDir), 'engine.json');
1440
+ }
1441
+
1442
+ /** Прочитать сохранённые настройки движка (с валидацией значений). */
1443
+ export function readEngineSettings(rootDir = process.cwd()) {
1444
+ let saved = {};
1445
+ try {
1446
+ saved = JSON.parse(fs.readFileSync(engineSettingsFile(rootDir), 'utf8')) || {};
1447
+ }
1448
+ catch { saved = {}; }
1449
+ const mode = v => ENGINE_STATE_MODES.includes(String(v || '')) ? String(v) : '';
1450
+ return {
1451
+ speculation: mode(saved.speculation) || DEFAULT_ENGINE_SETTINGS.speculation,
1452
+ promptLookup: mode(saved.promptLookup) || DEFAULT_ENGINE_SETTINGS.promptLookup,
1453
+ draftMax: clampInt(saved.draftMax, 1, 32, DEFAULT_ENGINE_SETTINGS.draftMax),
1454
+ profile: typeof saved.profile === 'string' && saved.profile ? saved.profile : DEFAULT_ENGINE_SETTINGS.profile,
1455
+ npuPrefill: saved.npuPrefill !== false,
1456
+ updatedAt: Number(saved.updatedAt) || 0,
1457
+ };
1458
+ }
1459
+
1460
+ /** Сохранить настройки движка (частичное обновление). */
1461
+ export function writeEngineSettings(rootDir = process.cwd(), patch = {}) {
1462
+ const current = readEngineSettings(rootDir);
1463
+ const merged = {
1464
+ ...current,
1465
+ ...(patch && typeof patch === 'object' ? patch : {}),
1466
+ updatedAt: Date.now(),
1467
+ };
1468
+ fs.mkdirSync(localRuntimeDir(rootDir), { recursive: true });
1469
+ fs.writeFileSync(engineSettingsFile(rootDir), JSON.stringify(merged, null, 2), 'utf8');
1470
+ return readEngineSettings(rootDir);
1471
+ }
1472
+
1473
+ /** Разобрать список поддерживаемых флагов CLI из текста `--help` движка. */
1474
+ export function parseEngineHelpFlags(text) {
1475
+ const out = new Set();
1476
+ for (const m of String(text || '').matchAll(/(?:^|[\s,;|[(=])(--[a-z][a-z0-9-]{1,40})/gi))
1477
+ out.add(m[1].toLowerCase());
1478
+ return [...out];
1479
+ }
1480
+
1481
+ function engineCapabilitiesFile(rootDir = process.cwd()) {
1482
+ return path.join(localCacheDir(rootDir), 'engine-capabilities.json');
1483
+ }
1484
+
1485
+ /** Прочитать закэшированные возможности движка (без запуска процесса). */
1486
+ export function readEngineCapabilitiesSync(rootDir = process.cwd(), exePath = '') {
1487
+ try {
1488
+ const raw = JSON.parse(fs.readFileSync(engineCapabilitiesFile(rootDir), 'utf8'));
1489
+ if (Array.isArray(raw?.flags) && (!exePath || raw.exePath === exePath))
1490
+ return raw;
1491
+ }
1492
+ catch { /* нет кэша */ }
1493
+ return null;
1494
+ }
1495
+
1496
+ function captureProcessOutput(cmd, args, spawnImpl, timeoutMs) {
1497
+ return new Promise(resolve => {
1498
+ let text = '';
1499
+ let done = false;
1500
+ const finish = () => {
1501
+ if (!done) {
1502
+ done = true;
1503
+ resolve(text);
1504
+ }
1505
+ };
1506
+ try {
1507
+ const proc = spawnImpl(cmd, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
1508
+ const timer = setTimeout(() => {
1509
+ try { proc?.kill?.(); } catch { /* ignore */ }
1510
+ finish();
1511
+ }, timeoutMs);
1512
+ proc?.stdout?.on?.('data', d => { text += String(d); if (text.length > 40000) text = text.slice(-40000); });
1513
+ proc?.stderr?.on?.('data', d => { text += String(d); if (text.length > 40000) text = text.slice(-40000); });
1514
+ proc?.on?.('error', () => { clearTimeout(timer); finish(); });
1515
+ proc?.on?.('close', () => { clearTimeout(timer); finish(); });
1516
+ }
1517
+ catch {
1518
+ finish();
1519
+ }
1520
+ });
1521
+ }
1522
+
1523
+ /**
1524
+ * Определить возможности `bubo.exe serve llm` по его же `--help` (с кэшем на 7 дней):
1525
+ * поддерживает ли движок `--speculative`, `--draft-max`/`--draft-min`/`--draft-p-min`
1526
+ * и динамический Prompt Lookup (`--lookup-cache-dynamic`).
1527
+ */
1528
+ export async function inspectEngineCapabilities({
1529
+ rootDir = process.cwd(),
1530
+ exePath = '',
1531
+ spawnImpl = spawn,
1532
+ timeoutMs = 9000,
1533
+ maxAgeMs = 7 * 24 * 60 * 60 * 1000,
1534
+ force = false,
1535
+ } = {}) {
1536
+ if (!exePath)
1537
+ return null;
1538
+ const cached = readEngineCapabilitiesSync(rootDir, exePath);
1539
+ if (!force && cached && Date.now() - Number(cached.checkedAt || 0) < maxAgeMs)
1540
+ return { ...cached, cached: true };
1541
+
1542
+ let helpText = '';
1543
+ for (const args of [['serve', 'llm', '--help'], ['--help'], ['serve', '--help']]) {
1544
+ helpText = await captureProcessOutput(exePath, args, spawnImpl, timeoutMs);
1545
+ if (parseEngineHelpFlags(helpText).length)
1546
+ break;
1547
+ }
1548
+ const flags = parseEngineHelpFlags(helpText);
1549
+ const result = {
1550
+ exePath,
1551
+ flags,
1552
+ known: flags.length > 0,
1553
+ speculative: flags.includes('--speculative'),
1554
+ draftMaxFlag: flags.includes('--draft-max'),
1555
+ draftMinFlag: flags.includes('--draft-min'),
1556
+ draftPMinFlag: flags.includes('--draft-p-min'),
1557
+ lookupFlag: flags.includes('--lookup-cache-dynamic')
1558
+ ? '--lookup-cache-dynamic'
1559
+ : (flags.includes('--lookup-cache') ? '--lookup-cache' : ''),
1560
+ checkedAt: Date.now(),
1561
+ helpText: helpText.slice(-4000),
1562
+ };
1563
+ try {
1564
+ fs.mkdirSync(path.dirname(engineCapabilitiesFile(rootDir)), { recursive: true });
1565
+ fs.writeFileSync(engineCapabilitiesFile(rootDir), JSON.stringify(result, null, 2), 'utf8');
1566
+ }
1567
+ catch { /* кэш не критичен */ }
1568
+ return { ...result, cached: false };
1569
+ }
1570
+
1571
+ /**
1572
+ * Собрать аргументы движка для спекулятивного декодирования (чистая функция — без побочных эффектов).
1573
+ * - `mtp`-предсказатель + `Dense twin` + `Q4_K Draft Head` передаются как веса;
1574
+ * - если движок объявляет `--speculative`, добавляется явный режим `mtp` (это и включает спекуляцию);
1575
+ * - при режиме `on` дополнительно передаются параметры черновика (`--draft-max` и порог);
1576
+ * - `promptLookup` включает n-граммный кэш подсказок там, где движок это поддерживает.
1577
+ */
1578
+ export function resolveSpeculationPlan({
1579
+ settings = {},
1580
+ capabilities = null,
1581
+ sidecars = {},
1582
+ hasManifest = false,
1583
+ lookupPath = '',
1584
+ } = {}) {
1585
+ const cfg = { ...DEFAULT_ENGINE_SETTINGS, ...(settings || {}) };
1586
+ const flags = new Set((capabilities?.flags || []).map(f => String(f).toLowerCase()));
1587
+ const capsKnown = flags.size > 0;
1588
+ const mtp = Boolean(sidecars?.mtpModel);
1589
+ const twin = Boolean(sidecars?.twinModel);
1590
+ const draftHead = Boolean(sidecars?.draftHeadModel);
1591
+ const args = [];
1592
+ const reasons = [];
1593
+ let enabled = false;
1594
+
1595
+ if (cfg.speculation === 'off') {
1596
+ reasons.push('Спекулятивное декодирование выключено в настройках движка — веса MTP/Twin/Draft Head не подключаются.');
1597
+ }
1598
+ else if (!mtp) {
1599
+ reasons.push('Файл MTP-предсказателя (mtp-*.gguf) не найден в $ai/#weights — спекуляция недоступна.');
1600
+ }
1601
+ else {
1602
+ args.push('--mtp-model', sidecars.mtpModel);
1603
+ if (twin)
1604
+ args.push('--twin-model', sidecars.twinModel);
1605
+ if (draftHead)
1606
+ args.push('--draft-head-model', sidecars.draftHeadModel);
1607
+ if (flags.has('--speculative')) {
1608
+ args.push('--speculative', 'mtp');
1609
+ enabled = true;
1610
+ reasons.push('Движок объявляет --speculative: передан режим «mtp».');
1611
+ }
1612
+ else if (capsKnown) {
1613
+ reasons.push('Движок не объявляет --speculative: спекуляция включается самим флагом --mtp-model (поведение по умолчанию движка).');
1614
+ }
1615
+ else {
1616
+ reasons.push('Возможности движка неизвестны (--help недоступен): дополнительные флаги спекуляции не передавались, работает режим по умолчанию.');
1617
+ }
1618
+ if (enabled) {
1619
+ if (cfg.speculation === 'on' && flags.has('--draft-max'))
1620
+ args.push('--draft-max', String(clampInt(cfg.draftMax, 1, 32, DEFAULT_ENGINE_SETTINGS.draftMax)));
1621
+ if (cfg.speculation === 'on' && flags.has('--draft-min'))
1622
+ args.push('--draft-min', '0');
1623
+ if (cfg.speculation === 'on' && flags.has('--draft-p-min'))
1624
+ args.push('--draft-p-min', '0.6');
1625
+ }
1626
+ }
1627
+
1628
+ let promptLookup = false;
1629
+ if (cfg.promptLookup !== 'off' && cfg.speculation !== 'off' && !hasManifest && capabilities?.lookupFlag && lookupPath) {
1630
+ args.push(capabilities.lookupFlag, lookupPath);
1631
+ promptLookup = true;
1632
+ reasons.push('Prompt Lookup (n-граммы) включён: ' + capabilities.lookupFlag + '.');
1633
+ }
1634
+ else if (cfg.promptLookup === 'on' && !capabilities?.lookupFlag) {
1635
+ reasons.push('Prompt Lookup запрошен, но движок не объявляет поддерживаемого флага кэша подсказок.');
1636
+ }
1637
+
1638
+ const mode = cfg.speculation === 'off'
1639
+ ? 'off'
1640
+ : (!mtp ? 'unavailable' : (enabled ? 'explicit' : 'weights-only'));
1641
+ const parts = [
1642
+ enabled ? 'MTP включён (--speculative mtp)' : (mtp && mode !== 'off' ? 'MTP передан весами' : 'MTP выключен'),
1643
+ promptLookup ? 'Prompt Lookup вкл.' : 'Prompt Lookup выкл.',
1644
+ cfg.speculation === 'on' && enabled ? `draft-max ${cfg.draftMax}` : '',
1645
+ ].filter(Boolean);
1646
+
1647
+ return {
1648
+ mode,
1649
+ enabled,
1650
+ promptLookup,
1651
+ sidecars: {
1652
+ mtp: Boolean(mtp),
1653
+ twin: Boolean(twin),
1654
+ draftHead: Boolean(draftHead),
1655
+ },
1656
+ capabilitiesKnown: capsKnown,
1657
+ args,
1658
+ reasons,
1659
+ summary: parts.join(' · '),
1660
+ settings: { ...cfg },
1661
+ };
1662
+ }
1663
+
1664
+ /**
1665
+ * Полное описание контура спекулятивного декодирования для UI: сохранённые настройки,
1666
+ * найденные веса (MTP / Dense twin / Draft head / Vision mmproj), возможности движка и итоговые флаги.
1667
+ */
1668
+ export async function describeEngineSetup({
1669
+ rootDir = process.cwd(),
1670
+ settings = null,
1671
+ capabilities = undefined,
1672
+ forceCapabilities = false,
1673
+ } = {}) {
1674
+ const winEnv = inspectWindowsHalogenEnvironment({ rootDir });
1675
+ const gguf = findLocalGgufModel(rootDir);
1676
+ const weightsDir = gguf ? path.dirname(gguf) : modelWeightsDir(rootDir, 'Qwen3.8-Flash-Next', 'Local');
1677
+ const sidecars = resolveBuboModelFiles(weightsDir);
1678
+ const hasManifest = Boolean(gguf && fs.existsSync(path.join(path.dirname(gguf), 'bubo-package.json')));
1679
+ const cfg = { ...readEngineSettings(rootDir), ...(settings || {}) };
1680
+ const exePath = winEnv.buboExePath || winEnv.gufoExePath || '';
1681
+ // Возможности читаем из кэша (быстро); принудительный опрос --help — только по кнопке «Обновить диагностику»
1682
+ // и при самом запуске движка (`startHalogenBackend`), чтобы карточка открывалась мгновенно.
1683
+ const caps = capabilities !== undefined
1684
+ ? capabilities
1685
+ : (readEngineCapabilitiesSync(rootDir, exePath)
1686
+ || (forceCapabilities ? await inspectEngineCapabilities({ rootDir, exePath, force: true }) : null));
1687
+ const plan = resolveSpeculationPlan({
1688
+ settings: cfg,
1689
+ capabilities: caps,
1690
+ sidecars,
1691
+ hasManifest,
1692
+ lookupPath: path.join(localCacheDir(rootDir), 'lookup.bin'),
1693
+ });
1694
+ const describeFile = p => {
1695
+ if (!p)
1696
+ return null;
1697
+ let sizeGb = 0;
1698
+ try { sizeGb = +((fs.statSync(p).size || 0) / (1024 ** 3)).toFixed(2); }
1699
+ catch { /* ignore */ }
1700
+ return { path: p, name: path.basename(p), sizeGb };
1701
+ };
1702
+ return {
1703
+ settings: cfg,
1704
+ weightsDir,
1705
+ mainModel: describeFile(gguf),
1706
+ sidecars: {
1707
+ mtp: describeFile(sidecars?.mtpModel),
1708
+ twin: describeFile(sidecars?.twinModel),
1709
+ draftHead: describeFile(sidecars?.draftHeadModel),
1710
+ mmproj: describeFile(sidecars?.mmprojModel),
1711
+ },
1712
+ plan,
1713
+ hasManifest,
1714
+ capabilities: caps ? {
1715
+ known: Boolean(caps.known),
1716
+ speculative: Boolean(caps.speculative),
1717
+ draftMax: Boolean(caps.draftMaxFlag),
1718
+ lookupFlag: caps.lookupFlag || '',
1719
+ cached: Boolean(caps.cached),
1720
+ checkedAt: caps.checkedAt || 0,
1721
+ flags: caps.flags || [],
1722
+ } : null,
1723
+ engine: {
1724
+ installed: Boolean(winEnv.buboInstalled || winEnv.gufoInstalled),
1725
+ runtime: winEnv.buboInstalled ? 'bubo.exe' : (winEnv.gufoInstalled ? 'gufo.exe' : ''),
1726
+ exePath,
1727
+ },
1728
+ running: _managedInfo ? {
1729
+ runtime: _managedInfo.runtime,
1730
+ profile: _managedInfo.profile || '',
1731
+ speculation: _managedInfo.speculation || null,
1732
+ startedAt: _managedInfo.startedAt,
1733
+ } : null,
1734
+ fallback: _lastSpeculationFallback,
1735
+ };
1736
+ }
1737
+
1404
1738
  /**
1405
1739
  * Запустить локальный сервер на порту 8731:
1406
1740
  * - На Windows 11: приоритетный запуск нативного `bubo.exe serve llm` (Halowin Bubo / Gufo ROCm 10.0 `gfx1151` + XRT NPU)
@@ -1411,9 +1745,13 @@ export async function startHalogenBackend({
1411
1745
  rootDir = process.cwd(),
1412
1746
  port = HALOGEN_DEFAULT_PORT,
1413
1747
  modelPath = '',
1414
- profile = 'subagents',
1415
- npuPrefill = true,
1748
+ profile = '',
1749
+ npuPrefill = null,
1416
1750
  spawnImpl = spawn,
1751
+ settings = null,
1752
+ capabilities = undefined,
1753
+ retryWithoutSpeculation = true,
1754
+ _speculationRetry = false,
1417
1755
  } = {}) {
1418
1756
  const probe = await probeHalogenServer(`http://127.0.0.1:${port}/v1/chat/completions`, { rootDir });
1419
1757
  if (probe.online) {
@@ -1450,23 +1788,37 @@ export async function startHalogenBackend({
1450
1788
  const manifestCandidate = ggufPath ? path.join(path.dirname(ggufPath), 'bubo-package.json') : '';
1451
1789
  const hasBuboManifest = Boolean(manifestCandidate && fs.existsSync(manifestCandidate));
1452
1790
 
1791
+ // Настройки спекулятивного декодирования (MTP + Draft Head + Prompt Lookup) из #runtime/engine.json
1792
+ const engineSettings = { ...readEngineSettings(rootDir), ...(settings || {}) };
1793
+ const activeProfile = profile || engineSettings.profile || 'subagents';
1794
+ const prefillEnabled = npuPrefill === null ? engineSettings.npuPrefill !== false : Boolean(npuPrefill);
1795
+
1453
1796
  // 1. Приоритет №1 на Windows: нативный движок Halowin Bubo (`bubo.exe serve llm` на ROCm 10.0.0 gfx1151 + Ryzen AI NPU)
1454
1797
  if (winEnv.buboInstalled && ggufPath && fs.existsSync(ggufPath)) {
1455
1798
  try {
1799
+ // Возможности движка (--speculative, --draft-max, --lookup-cache-dynamic) определяются один раз по `--help`
1800
+ const caps = capabilities !== undefined
1801
+ ? capabilities
1802
+ : await inspectEngineCapabilities({ rootDir, exePath: winEnv.buboExePath, spawnImpl });
1803
+ const plan = resolveSpeculationPlan({
1804
+ settings: engineSettings,
1805
+ capabilities: caps,
1806
+ sidecars: resolvedSidecars || {},
1807
+ hasManifest: hasBuboManifest,
1808
+ lookupPath: path.join(cacheDir, 'lookup.bin'),
1809
+ });
1456
1810
  const args = [
1457
1811
  'serve', 'llm',
1458
1812
  '--host', '127.0.0.1',
1459
1813
  '--port', String(port),
1460
1814
  '--model', ggufPath,
1461
1815
  ...(hasBuboManifest ? ['--manifest', manifestCandidate, '--cache-disk', path.join(cacheDir, 'disk')] : []),
1462
- ...(resolvedSidecars?.mtpModel ? ['--mtp-model', resolvedSidecars.mtpModel] : []),
1463
1816
  ...(resolvedSidecars?.mmprojModel ? ['--mmproj', resolvedSidecars.mmprojModel] : []),
1464
- ...(resolvedSidecars?.twinModel ? ['--twin-model', resolvedSidecars.twinModel] : []),
1465
- ...(resolvedSidecars?.draftHeadModel ? ['--draft-head-model', resolvedSidecars.draftHeadModel] : []),
1817
+ ...plan.args,
1466
1818
  '--served-model-name', 'halogen-qwen3.8-flash-next',
1467
- '--profile', profile || 'subagents',
1819
+ '--profile', activeProfile,
1468
1820
  ];
1469
- if (npuPrefill && winEnv.npuDriverInstalled && winEnv.npuKernelsPresent && profile !== 'exact' && profile !== 'stock') {
1821
+ if (prefillEnabled && winEnv.npuDriverInstalled && winEnv.npuKernelsPresent && activeProfile !== 'exact' && activeProfile !== 'stock') {
1470
1822
  args.push('--npu-prefill', 'on');
1471
1823
  }
1472
1824
  const env = {
@@ -1485,7 +1837,32 @@ export async function startHalogenBackend({
1485
1837
  port,
1486
1838
  modelPath: ggufPath,
1487
1839
  runtime: 'bubo',
1488
- npuPrefill: Boolean(npuPrefill && winEnv.npuDriverInstalled && winEnv.npuKernelsPresent),
1840
+ npuPrefill: Boolean(prefillEnabled && winEnv.npuDriverInstalled && winEnv.npuKernelsPresent),
1841
+ profile: activeProfile,
1842
+ args,
1843
+ speculation: plan,
1844
+ onEarlyExit: retryWithoutSpeculation && !_speculationRetry && plan.args.length
1845
+ ? async (code) => {
1846
+ _lastSpeculationFallback = {
1847
+ at: Date.now(),
1848
+ reason: `движок завершился с кодом ${code} сразу после запуска со флагами спекуляции`,
1849
+ args: plan.args,
1850
+ };
1851
+ try {
1852
+ await startHalogenBackend({
1853
+ rootDir,
1854
+ port,
1855
+ modelPath: ggufPath,
1856
+ profile: activeProfile,
1857
+ npuPrefill,
1858
+ spawnImpl,
1859
+ settings: { ...engineSettings, speculation: 'off', promptLookup: 'off' },
1860
+ _speculationRetry: true,
1861
+ });
1862
+ }
1863
+ catch { /* останется автономный контур */ }
1864
+ }
1865
+ : null,
1489
1866
  });
1490
1867
  return {
1491
1868
  started: true,
@@ -1495,6 +1872,11 @@ export async function startHalogenBackend({
1495
1872
  port,
1496
1873
  modelPath: ggufPath,
1497
1874
  windowsEnv: winEnv,
1875
+ speculation: {
1876
+ ...plan,
1877
+ appliedArgs: plan.args,
1878
+ },
1879
+ capabilities: caps ? { known: caps.known, flags: caps.flags, cached: Boolean(caps.cached) } : null,
1498
1880
  };
1499
1881
  }
1500
1882
  catch { /* try next runtime */ }
@@ -1503,6 +1885,7 @@ export async function startHalogenBackend({
1503
1885
  // 2. Приоритет №2 на Windows: нативный Gufo (`gufo.exe serve --port 8731 llm`)
1504
1886
  if (winEnv.gufoInstalled && ggufPath && fs.existsSync(ggufPath)) {
1505
1887
  try {
1888
+ const gufoSpeculation = engineSettings.speculation !== 'off' && Boolean(resolvedSidecars?.mtpModel);
1506
1889
  const args = [
1507
1890
  'serve',
1508
1891
  '--host', '127.0.0.1',
@@ -1510,7 +1893,8 @@ export async function startHalogenBackend({
1510
1893
  'llm',
1511
1894
  '--model', ggufPath,
1512
1895
  '--served-model-name', 'halogen-qwen3.8-flash-next',
1513
- '--speculative', 'mtp',
1896
+ ...(gufoSpeculation ? ['--speculative', 'mtp'] : []),
1897
+ ...(gufoSpeculation && resolvedSidecars?.mmprojModel ? ['--mmproj', resolvedSidecars.mmprojModel] : []),
1514
1898
  ];
1515
1899
  const proc = spawnImpl(winEnv.gufoExePath, args, {
1516
1900
  cwd: path.dirname(winEnv.gufoExePath),
@@ -1523,6 +1907,13 @@ export async function startHalogenBackend({
1523
1907
  port,
1524
1908
  modelPath: ggufPath,
1525
1909
  runtime: 'gufo',
1910
+ args,
1911
+ speculation: {
1912
+ mode: gufoSpeculation ? 'explicit' : 'off',
1913
+ enabled: gufoSpeculation,
1914
+ summary: gufoSpeculation ? 'MTP включён (--speculative mtp)' : 'MTP выключен',
1915
+ args: gufoSpeculation ? ['--speculative', 'mtp'] : [],
1916
+ },
1526
1917
  });
1527
1918
  return {
1528
1919
  started: true,
@@ -1595,6 +1986,7 @@ export function stopHalogenBackend() {
1595
1986
  _managedProc = null;
1596
1987
  _managedInfo = null;
1597
1988
  _lastManagedExit = null;
1989
+ _lastSpeculationFallback = null;
1598
1990
  return { stopped: true };
1599
1991
  }
1600
1992
 
@@ -82,6 +82,13 @@ import {
82
82
  ensureHalogenModelNodes,
83
83
  inspectHalogenCatalogWithStatus,
84
84
  downloadHalogenBundle,
85
+ describeEngineSetup,
86
+ readEngineSettings,
87
+ writeEngineSettings,
88
+ inspectEngineCapabilities,
89
+ resolveSpeculationPlan,
90
+ parseEngineHelpFlags,
91
+ DEFAULT_ENGINE_SETTINGS,
85
92
  } from './halogen.js';
86
93
  import {
87
94
  AI_PROVIDER_PRESETS,
@@ -197,6 +204,13 @@ export {
197
204
  ensureHalogenModelNodes,
198
205
  inspectHalogenCatalogWithStatus,
199
206
  downloadHalogenBundle,
207
+ describeEngineSetup,
208
+ readEngineSettings,
209
+ writeEngineSettings,
210
+ inspectEngineCapabilities,
211
+ resolveSpeculationPlan,
212
+ parseEngineHelpFlags,
213
+ DEFAULT_ENGINE_SETTINGS,
200
214
  CURATED_HF_MODELS,
201
215
  MODEL_MODALITIES,
202
216
  MODEL_CAPABILITIES,
@@ -462,11 +476,36 @@ async function runSingleModelSmokeTest(ai, p = {}) {
462
476
  modality,
463
477
  durationMs,
464
478
  error: String(e?.message || e),
479
+ ...(e?.pythonMissing ? { pythonMissing: true } : {}),
465
480
  ...(Array.isArray(e?.missingDeps) && e.missingDeps.length ? { missingDeps: e.missingDeps } : {}),
466
481
  };
467
482
  }
468
483
  }
469
484
 
485
+ /**
486
+ * Привести значение из UI/HTTP (true, 1, '1', 'true') к булеву.
487
+ */
488
+ const isTruthy = v => v === true || v === 1 || v === '1' || v === 'true' || v === 'yes';
489
+
490
+ /**
491
+ * Остановить движок и дождаться освобождения порта, после чего запустить его с новыми настройками
492
+ * (иначе `startHalogenBackend` увидит ещё живой сервер и вернёт `alreadyRunning`).
493
+ */
494
+ async function restartHalogenEngine(settings = null, params = {}) {
495
+ stopHalogenBackend();
496
+ const deadline = Date.now() + 8000;
497
+ while (Date.now() < deadline) {
498
+ const probe = await probeHalogenServer().catch(() => ({ online: false }));
499
+ if (!probe?.online)
500
+ break;
501
+ await new Promise(resolve => setTimeout(resolve, 250));
502
+ }
503
+ return startHalogenBackend({
504
+ ...(settings ? { settings } : {}),
505
+ ...params,
506
+ });
507
+ }
508
+
470
509
  export const TRAINER_METHODS = Object.freeze({
471
510
  trainer_status: {
472
511
  level: 'read',
@@ -595,6 +634,9 @@ export const TRAINER_METHODS = Object.freeze({
595
634
  halogenOnline: Boolean(halogenProbe?.online),
596
635
  halogenMode: halogenProbe?.mode || '',
597
636
  halogenModeLabel: halogenProbe?.modeLabel || '',
637
+ speculation: halogenProbe?.speculation || null,
638
+ speculationFallback: halogenProbe?.speculationFallback || null,
639
+ engineSettings: (d.protocol === 'halogen' || weightInfo?.hasGguf) ? readEngineSettings(process.cwd()) : null,
598
640
  windowsEnv: halogenProbe?.windowsEnv || null,
599
641
  };
600
642
  },
@@ -827,7 +869,48 @@ export const TRAINER_METHODS = Object.freeze({
827
869
  return startHalogenBackend({
828
870
  port: Number(p.port) || HALOGEN_DEFAULT_PORT,
829
871
  modelPath: p.modelPath || '',
872
+ ...(p.profile ? { profile: String(p.profile) } : {}),
873
+ ...(p.npuPrefill === undefined ? {} : { npuPrefill: isTruthy(p.npuPrefill) }),
874
+ ...(p.settings && typeof p.settings === 'object' ? { settings: p.settings } : {}),
875
+ });
876
+ },
877
+ },
878
+ /** Текущие настройки движка и готовность спекулятивного декодирования (MTP + Draft Head). */
879
+ halogen_engine_config: {
880
+ level: 'read',
881
+ fn: async function (p = {}) {
882
+ return describeEngineSetup({ forceCapabilities: isTruthy(p.refresh) });
883
+ },
884
+ },
885
+ /** Сохранить настройки спекуляции и (по желанию) перезапустить движок с ними. */
886
+ halogen_save_engine_config: {
887
+ level: 'admin',
888
+ fn: async function (p = {}) {
889
+ const saved = writeEngineSettings(process.cwd(), {
890
+ ...(p.speculation ? { speculation: p.speculation } : {}),
891
+ ...(p.promptLookup ? { promptLookup: p.promptLookup } : {}),
892
+ ...(p.draftMax !== undefined ? { draftMax: p.draftMax } : {}),
893
+ ...(p.profile ? { profile: p.profile } : {}),
894
+ ...(p.npuPrefill === undefined ? {} : { npuPrefill: isTruthy(p.npuPrefill) }),
895
+ });
896
+ const wantsRestart = isTruthy(p.restart);
897
+ if (wantsRestart)
898
+ await restartHalogenEngine(saved).catch(() => null);
899
+ return {
900
+ ...(await describeEngineSetup({ settings: saved, forceCapabilities: isTruthy(p.refresh) })),
901
+ saved,
902
+ restarted: wantsRestart,
903
+ };
904
+ },
905
+ },
906
+ /** Перезапустить встроенный движок с текущими настройками. */
907
+ halogen_restart: {
908
+ level: 'admin',
909
+ fn: async function (p = {}) {
910
+ const started = await restartHalogenEngine(null, {
911
+ ...(p.profile ? { profile: String(p.profile) } : {}),
830
912
  });
913
+ return { ...started, restarted: true };
831
914
  },
832
915
  },
833
916
  halogen_stop: {