odant-work 1.0.37 → 1.0.39

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.
@@ -44,6 +44,7 @@ import {
44
44
  } from './runner.js';
45
45
  import {
46
46
  localStreamChat,
47
+ localEngine,
47
48
  getLocalEngineStatus,
48
49
  releaseLocalEngineMemory,
49
50
  touchLocalEngineActivity,
@@ -147,6 +148,7 @@ export const halogenFallback = Object.freeze({
147
148
 
148
149
  export {
149
150
  localStreamChat,
151
+ localEngine,
150
152
  SOURCE_PRESETS,
151
153
  THREAD_OPTIONS,
152
154
  loadTrainerNetworkSettings,
@@ -324,6 +326,147 @@ function stripInventoryFiles(inv) {
324
326
  /**
325
327
  * Методы `trainer_*`, подключаемые к узлам `$class` (в `/MODELS/Local` и локальных `$ai`) и в шлюз `gateway.js`.
326
328
  */
329
+ function inferTestModality(ai) {
330
+ const d = ai?.DATA || {};
331
+ const mod = String(ai?.modality || d.modality || '').toLowerCase();
332
+ const rawCaps = ai?.capabilities ?? d.capabilities ?? [];
333
+ const caps = (Array.isArray(rawCaps) ? rawCaps : String(rawCaps || '').split(/[\s,]+/))
334
+ .map(s => String(s).trim().toLowerCase()).filter(Boolean);
335
+ if (caps.includes('tts') || mod === 'tts' || mod === 'voice')
336
+ return 'tts';
337
+ if (caps.includes('stt') || caps.includes('asr') || mod === 'stt' || mod === 'asr')
338
+ return 'stt';
339
+ if (caps.includes('image') || caps.includes('text-to-image') || mod === 'image')
340
+ return 'image';
341
+ if (caps.includes('rerank') || mod === 'rerank' || /rerank/i.test(String(ai?.id || ai?.model || '')))
342
+ return 'rerank';
343
+ if (caps.includes('embeddings') || caps.includes('rag') || mod === 'embed' || mod === 'embedding')
344
+ return 'embed';
345
+ return 'llm';
346
+ }
347
+
348
+ async function runSingleModelSmokeTest(ai, p = {}) {
349
+ await ai?.init?.catch?.(() => {});
350
+ const modality = String(p.modality || inferTestModality(ai));
351
+ const t0 = Date.now();
352
+ try {
353
+ if (modality === 'tts') {
354
+ const text = String(p.text || p.prompt || 'Привет! Проверка локального синтеза речи WORK.').trim();
355
+ const buf = await ai.speak({ text, language: p.language, instructions: p.instructions });
356
+ const durationMs = Math.max(1, Date.now() - t0);
357
+ return {
358
+ ok: true,
359
+ modality,
360
+ durationMs,
361
+ bytes: buf.length,
362
+ audioBase64: buf.toString('base64'),
363
+ summary: `WAV ${(buf.length / 1024).toFixed(1)} КБ за ${(durationMs / 1000).toFixed(2)} с`,
364
+ };
365
+ }
366
+ if (modality === 'stt') {
367
+ let audio = null;
368
+ if (p.audioBase64)
369
+ audio = Buffer.from(String(p.audioBase64), 'base64');
370
+ else
371
+ audio = synthesizeFallbackWav('проверка');
372
+ const res = await ai.transcribe({ audio, language: p.language || 'ru' });
373
+ const durationMs = Math.max(1, Date.now() - t0);
374
+ return {
375
+ ok: true,
376
+ modality,
377
+ durationMs,
378
+ text: res?.text || '',
379
+ summary: res?.text ? `«${res.text.slice(0, 60)}» (${durationMs} мс)` : `Обработано за ${durationMs} мс`,
380
+ };
381
+ }
382
+ if (modality === 'image') {
383
+ const prompt = String(p.prompt || 'Минималистичная 3D-иконка офисного здания на светлом фоне').trim();
384
+ const pic = await ai.generateImage({ prompt, size: p.size || '512x512', steps: p.steps ? Number(p.steps) : undefined });
385
+ const durationMs = Math.max(1, Date.now() - t0);
386
+ return {
387
+ ok: true,
388
+ modality,
389
+ durationMs,
390
+ mime: pic?.mime || 'image/png',
391
+ base64: pic?.base64 || '',
392
+ summary: `Картинка ${pic?.mime || 'image/png'} за ${(durationMs / 1000).toFixed(1)} с`,
393
+ };
394
+ }
395
+ if (modality === 'embed') {
396
+ const input = Array.isArray(p.input) && p.input.length
397
+ ? p.input
398
+ : String(p.prompt || 'Учётная система WORK\nОборотно-сальдовая ведомость').split(/\r?\n/).filter(Boolean);
399
+ const res = await ai.embed({ input });
400
+ const durationMs = Math.max(1, Date.now() - t0);
401
+ const list = res?.data || [];
402
+ const dims = list[0]?.embedding?.length || res?.dimensions || 0;
403
+ return {
404
+ ok: true,
405
+ modality,
406
+ durationMs,
407
+ count: list.length,
408
+ dimensions: dims,
409
+ summary: `${list.length} вект. × ${dims}d за ${durationMs} мс`,
410
+ };
411
+ }
412
+ if (modality === 'rerank') {
413
+ const query = String(p.query || p.prompt || 'остатки на расчётном счёте 51').trim();
414
+ const documents = Array.isArray(p.documents) && p.documents.length
415
+ ? p.documents
416
+ : ['Счёт 51 «Расчётные счета»: обороты и остатки денежных средств', 'Договор аренды офиса и коммунальные услуги'];
417
+ const res = await ai.rerank({ query, documents, top_n: documents.length });
418
+ const durationMs = Math.max(1, Date.now() - t0);
419
+ const top = res?.results?.[0];
420
+ return {
421
+ ok: true,
422
+ modality,
423
+ durationMs,
424
+ results: res?.results || [],
425
+ summary: `Топ #${(top?.index ?? 0) + 1} (${((top?.relevance_score ?? 0) * 100).toFixed(1)}%) за ${durationMs} мс`,
426
+ };
427
+ }
428
+ const messages = Array.isArray(p.messages) && p.messages.length
429
+ ? p.messages
430
+ : [{ role: 'user', content: String(p.prompt || 'Привет! Представься коротко в одном предложении.') }];
431
+ let text = '';
432
+ let usage = null;
433
+ for await (const chunk of ai.streamChat({ messages, max_tokens: Number(p.maxTokens) || 192 }, {})) {
434
+ if (typeof chunk === 'string')
435
+ text += chunk;
436
+ else if (chunk?.type === 'usage')
437
+ usage = chunk;
438
+ }
439
+ const durationMs = Math.max(1, Date.now() - t0);
440
+ const ttftMs = Number(usage?.ttftMs) || 0;
441
+ const tokPerSec = Number(usage?.tokPerSec) || 0;
442
+ const promptTokPerSec = Number(usage?.promptTokPerSec) || 0;
443
+ return {
444
+ ok: true,
445
+ modality: 'llm',
446
+ text: text.trim(),
447
+ durationMs,
448
+ ttftMs,
449
+ tokPerSec,
450
+ promptTokPerSec,
451
+ usage,
452
+ summary: [
453
+ tokPerSec > 0 ? `${tokPerSec} tok/s` : `${durationMs} мс`,
454
+ ttftMs > 0 ? `TTFT ${(ttftMs / 1000).toFixed(2)} с` : '',
455
+ ].filter(Boolean).join(' · '),
456
+ };
457
+ }
458
+ catch (e) {
459
+ const durationMs = Math.max(1, Date.now() - t0);
460
+ return {
461
+ ok: false,
462
+ modality,
463
+ durationMs,
464
+ error: String(e?.message || e),
465
+ ...(Array.isArray(e?.missingDeps) && e.missingDeps.length ? { missingDeps: e.missingDeps } : {}),
466
+ };
467
+ }
468
+ }
469
+
327
470
  export const TRAINER_METHODS = Object.freeze({
328
471
  trainer_status: {
329
472
  level: 'read',
@@ -1088,6 +1231,73 @@ export const TRAINER_METHODS = Object.freeze({
1088
1231
  });
1089
1232
  },
1090
1233
  },
1234
+ trainer_test_model: {
1235
+ level: 'call',
1236
+ fn: async function (p = {}) {
1237
+ const args = mergeTrainerArgs(p);
1238
+ let target = this;
1239
+ if (args.nodePath || args.path) {
1240
+ const found = await globalThis.WORK?.get_item?.(args.nodePath || args.path).catch(() => null);
1241
+ if (found)
1242
+ target = found;
1243
+ }
1244
+ return runSingleModelSmokeTest(target, args);
1245
+ },
1246
+ },
1247
+ trainer_check_all_models: {
1248
+ level: 'call',
1249
+ fn: async function () {
1250
+ const pythonDeps = await localEngine.checkDeps();
1251
+ const localNode = await globalThis.WORK?.get_item?.('/MODELS/Local').catch(() => null);
1252
+ const items = (await localNode?.items) || [];
1253
+ const results = [];
1254
+ for (const m of items) {
1255
+ if (!m || Array.isArray(m))
1256
+ continue;
1257
+ await m.init?.catch?.(() => {});
1258
+ const act = evaluateAiNodeActivitySync(m);
1259
+ const modality = inferTestModality(m);
1260
+ if (!act.active) {
1261
+ results.push({
1262
+ id: m.id,
1263
+ path: m.path,
1264
+ label: m.label || m.DATA?.label || m.id,
1265
+ modality,
1266
+ active: false,
1267
+ ok: false,
1268
+ skipped: true,
1269
+ summary: act.reason || 'Неактивна',
1270
+ });
1271
+ continue;
1272
+ }
1273
+ const res = await runSingleModelSmokeTest(m, {
1274
+ prompt: modality === 'llm' ? 'Ответь одним словом: Готов.' : undefined,
1275
+ });
1276
+ results.push({
1277
+ id: m.id,
1278
+ path: m.path,
1279
+ label: m.label || m.DATA?.label || m.id,
1280
+ active: true,
1281
+ ...res,
1282
+ });
1283
+ }
1284
+ return {
1285
+ ok: results.every(r => r.skipped || r.ok),
1286
+ pythonDeps,
1287
+ results,
1288
+ };
1289
+ },
1290
+ },
1291
+ trainer_install_python_deps: {
1292
+ level: 'admin',
1293
+ fn: async function (p = {}) {
1294
+ const args = mergeTrainerArgs(p);
1295
+ const list = Array.isArray(args.packages)
1296
+ ? args.packages
1297
+ : String(args.packages || '').split(/[\s,]+/).filter(Boolean);
1298
+ return localEngine.installDeps(list);
1299
+ },
1300
+ },
1091
1301
  });
1092
1302
 
1093
1303
  export function attachTrainerMethods($class) {
@@ -133,12 +133,109 @@ async function getTokenizer(weightsDir) {
133
133
  return tok;
134
134
  }
135
135
 
136
- function ensureInferWorker() {
136
+ function venvPythonCandidates(rootDir = process.cwd()) {
137
+ const rel = os.platform() === 'win32'
138
+ ? ['.venv/Scripts/python.exe', 'venv/Scripts/python.exe', 'MODELS/Local/.venv/Scripts/python.exe']
139
+ : ['.venv/bin/python', 'venv/bin/python', 'MODELS/Local/.venv/bin/python'];
140
+ return rel.map(r => path.resolve(rootDir, r));
141
+ }
142
+
143
+ /** Известные расположения python.exe вне PATH (установщики Python пишут сюда). */
144
+ function knownPythonPaths() {
145
+ if (os.platform() !== 'win32')
146
+ return [];
147
+ const out = [];
148
+ const bases = [process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, 'Programs'), 'C:\\Program Files', 'C:\\Program Files (x86)']
149
+ .filter(Boolean);
150
+ for (const base of bases) {
151
+ try {
152
+ for (const dir of fs.readdirSync(base)) {
153
+ if (/^Python/i.test(dir) && fs.existsSync(path.join(base, dir, 'python.exe')))
154
+ out.push(path.join(base, dir, 'python.exe'));
155
+ }
156
+ }
157
+ catch { /* нет папки */ }
158
+ }
159
+ try {
160
+ for (const dir of fs.readdirSync('C:\\')) {
161
+ if (/^Python\d+/i.test(dir) && fs.existsSync(path.join('C:\\', dir, 'python.exe')))
162
+ out.push(path.join('C:\\', dir, 'python.exe'));
163
+ }
164
+ }
165
+ catch { /* нет диска C:\ */ }
166
+ return out;
167
+ }
168
+
169
+ /** Пробный запуск кандидата: заглушка Microsoft Store (код 9009) и отсутствующие команды отсеиваются. */
170
+ function probePython(cmd, extraArgs = []) {
171
+ return new Promise(resolve => {
172
+ let done = false;
173
+ const finish = ok => {
174
+ if (!done) {
175
+ done = true;
176
+ resolve(ok);
177
+ }
178
+ };
179
+ try {
180
+ const p = spawn(cmd, [...extraArgs, '--version'], { windowsHide: true, stdio: 'ignore' });
181
+ const t = setTimeout(() => {
182
+ p.kill();
183
+ finish(false);
184
+ }, 7000);
185
+ p.on('error', () => {
186
+ clearTimeout(t);
187
+ finish(false);
188
+ });
189
+ p.on('close', code => {
190
+ clearTimeout(t);
191
+ finish(code === 0);
192
+ });
193
+ }
194
+ catch {
195
+ finish(false);
196
+ }
197
+ });
198
+ }
199
+
200
+ let _pythonCmd = null;
201
+ let _pythonResolving = null;
202
+
203
+ /**
204
+ * Найти рабочий интерпретатор Python: .venv проекта → команды из PATH (с пробным запуском,
205
+ * чтобы отсеять заглушку WindowsApps, завершающуюся с кодом 9009) → известные папки установки.
206
+ * @returns {Promise<{ cmd: string, args: string[] }>}
207
+ */
208
+ function resolvePythonCommandAsync(rootDir = process.cwd()) {
209
+ if (_pythonCmd)
210
+ return Promise.resolve(_pythonCmd);
211
+ _pythonResolving ??= (async () => {
212
+ for (const v of venvPythonCandidates(rootDir)) {
213
+ if (fs.existsSync(v)) {
214
+ _pythonCmd = { cmd: v, args: [] };
215
+ return _pythonCmd;
216
+ }
217
+ }
218
+ const candidates = ['python', 'python3', 'py', ...knownPythonPaths()];
219
+ for (const c of candidates) {
220
+ const args = c === 'py' ? ['-3'] : [];
221
+ if (await probePython(c, args)) {
222
+ _pythonCmd = { cmd: c, args };
223
+ return _pythonCmd;
224
+ }
225
+ }
226
+ _pythonCmd = { cmd: 'python', args: [] };
227
+ return _pythonCmd;
228
+ })();
229
+ return _pythonResolving;
230
+ }
231
+
232
+ async function ensureInferWorker() {
137
233
  if (_workerProc && !_workerProc.killed)
138
234
  return _workerProc;
139
235
 
140
236
  const scriptPath = path.resolve(import.meta.dirname, './worker/local_infer_worker.py');
141
- const proc = spawn('python', [scriptPath], {
237
+ const { cmd, args } = await resolvePythonCommandAsync();
238
+ const proc = spawn(cmd, [...args, scriptPath], {
142
239
  windowsHide: true,
143
240
  stdio: ['pipe', 'pipe', 'pipe'],
144
241
  });
@@ -171,6 +268,14 @@ function ensureInferWorker() {
171
268
  }
172
269
  });
173
270
 
271
+ // stderr не JSON-протокол: держим кольцевой буфер для диагностики падений (нехватка пакетов, заглушка Store и т.п.)
272
+ const stderrTail = [];
273
+ proc.stderr.on('data', chunk => {
274
+ stderrTail.push(String(chunk));
275
+ if (stderrTail.length > 16)
276
+ stderrTail.shift();
277
+ });
278
+
174
279
  const failAll = (errText) => {
175
280
  for (const req of _pendingRequests.values())
176
281
  req.onMessage({ event: 'error', error: errText });
@@ -181,8 +286,10 @@ function ensureInferWorker() {
181
286
 
182
287
  proc.on('error', err => failAll(String(err?.message || err)));
183
288
  proc.on('close', code => {
184
- if (code !== 0 && _pendingRequests.size > 0)
185
- failAll(`Процесс локального инференса завершился (код ${code})`);
289
+ if (code !== 0 && _pendingRequests.size > 0) {
290
+ const tail = stderrTail.join('').trim().slice(-800);
291
+ failAll(`Процесс локального инференса завершился (код ${code})${tail ? ': ' + tail : ''}`);
292
+ }
186
293
  _workerProc = null;
187
294
  _workerReady = false;
188
295
  });
@@ -295,7 +402,7 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
295
402
  const promptText = buildChatMlPrompt(turns.length ? turns : [{ role: 'user', content: 'Привет!' }], grounding, enableThinking);
296
403
  const inputIds = Array.from(tokenizer.encode(promptText), Number);
297
404
 
298
- const proc = ensureInferWorker();
405
+ const proc = await ensureInferWorker();
299
406
  proc.stdout?.ref?.();
300
407
  const reqId = 'req_' + crypto.randomUUID().slice(0, 8);
301
408
 
@@ -335,6 +442,8 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
335
442
 
336
443
  proc.stdin.write(payload);
337
444
 
445
+ const tStart = Date.now();
446
+ let tFirstToken = 0;
338
447
  const generatedIds = [];
339
448
  let prevDecoded = '';
340
449
 
@@ -344,6 +453,7 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
344
453
  await new Promise(resolve => { notify = resolve; });
345
454
  }
346
455
  while (queue.length > 0) {
456
+ tFirstToken ||= Date.now();
347
457
  const tokId = queue.shift();
348
458
  generatedIds.push(tokId);
349
459
  const fullDecoded = tokenizer.decode(generatedIds, { skip_special_tokens: true });
@@ -377,6 +487,10 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
377
487
  tokens: inputIds.length,
378
488
  });
379
489
  const cachedTokens = sessionRes.cachedTokens ? Math.min(inputIds.length, sessionRes.cachedTokens) : 0;
490
+ const now = Date.now();
491
+ const ttftMs = tFirstToken ? Math.max(1, tFirstToken - tStart) : Math.max(1, now - tStart);
492
+ const decodeMs = tFirstToken ? Math.max(1, now - tFirstToken) : ttftMs;
493
+ const tokPerSec = generatedIds.length > 0 && decodeMs > 0 ? +((generatedIds.length * 1000) / decodeMs).toFixed(1) : 0;
380
494
 
381
495
  yield {
382
496
  type: 'usage',
@@ -384,6 +498,9 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
384
498
  completion_tokens: generatedIds.length,
385
499
  total_tokens: inputIds.length + generatedIds.length,
386
500
  cached_tokens: cachedTokens,
501
+ ttftMs,
502
+ decodeMs,
503
+ ...(tokPerSec > 0 ? { tokPerSec } : {}),
387
504
  ...(sessionRes.fromStatus ? { halogen_from: sessionRes.fromStatus } : {}),
388
505
  };
389
506
  yield {
@@ -420,3 +537,216 @@ export async function* localStreamChat(ai, body = {}, options = {}) {
420
537
 
421
538
  throw new Error('Файлы весов модели ещё не скачаны в $ai/#weights (откройте /MODELS/Local для установки).');
422
539
  }
540
+
541
+ async function runWorkerOp(payload, timeoutMs = 120000) {
542
+ touchLocalEngineActivity();
543
+ const proc = await ensureInferWorker();
544
+ proc.stdout?.ref?.();
545
+ const reqId = 'op_' + crypto.randomUUID().slice(0, 8);
546
+ return new Promise((resolve, reject) => {
547
+ const timer = setTimeout(() => {
548
+ _pendingRequests.delete(reqId);
549
+ if (_pendingRequests.size === 0)
550
+ proc.stdout?.unref?.();
551
+ reject(new Error(`Локальный движок (${payload.op}): таймаут ${Math.round(timeoutMs / 1000)}с`));
552
+ }, timeoutMs);
553
+ _pendingRequests.set(reqId, {
554
+ onMessage(msg) {
555
+ if (msg.event === 'result') {
556
+ clearTimeout(timer);
557
+ _pendingRequests.delete(reqId);
558
+ if (_pendingRequests.size === 0)
559
+ proc.stdout?.unref?.();
560
+ resolve(msg.data || {});
561
+ }
562
+ else if (msg.event === 'error') {
563
+ clearTimeout(timer);
564
+ _pendingRequests.delete(reqId);
565
+ if (_pendingRequests.size === 0)
566
+ proc.stdout?.unref?.();
567
+ const err = new Error(msg.error || 'Ошибка локального движка');
568
+ if (Array.isArray(msg.missingDeps))
569
+ err.missingDeps = msg.missingDeps;
570
+ reject(err);
571
+ }
572
+ },
573
+ });
574
+ proc.stdin.write(JSON.stringify({ id: reqId, ...payload }) + '\n');
575
+ });
576
+ }
577
+
578
+ function assertLocalWeightsReady(ai) {
579
+ const weightsDir = resolveWeightsDir(ai);
580
+ const wInsp = inspectWeightsDirectorySync(weightsDir);
581
+ if (wInsp.incompatibleOnPlatform)
582
+ throw new Error(wInsp.incompatibleReason);
583
+ if (!wInsp.exists || (!wInsp.hasSafetensors && !wInsp.hasConfig))
584
+ throw new Error('Файлы весов модели ещё не скачаны в $ai/#weights.');
585
+ return weightsDir;
586
+ }
587
+
588
+ export async function localEmbed(ai, params = {}) {
589
+ const weightsDir = assertLocalWeightsReady(ai);
590
+ const raw = params.input ?? params.text ?? params.post ?? '';
591
+ const input = Array.isArray(raw) ? raw.map(String) : [String(raw)];
592
+ const res = await runWorkerOp({ op: 'embed', weightsDir, input }, 60000);
593
+ return {
594
+ object: 'list',
595
+ model: String(ai?.model || ai?.id || 'local-embed'),
596
+ data: (res.embeddings || []).map((embedding, index) => ({ object: 'embedding', index, embedding })),
597
+ dimensions: res.dimensions || 0,
598
+ durationMs: res.durationMs || 0,
599
+ };
600
+ }
601
+
602
+ export async function localRerank(ai, params = {}) {
603
+ const weightsDir = assertLocalWeightsReady(ai);
604
+ const query = String(params.query || '').trim();
605
+ const documents = Array.isArray(params.documents) ? params.documents : [];
606
+ const res = await runWorkerOp({
607
+ op: 'rerank',
608
+ weightsDir,
609
+ query,
610
+ documents,
611
+ topN: Number(params.top_n || params.topN) || 0,
612
+ }, 60000);
613
+ return {
614
+ model: String(ai?.model || ai?.id || 'local-rerank'),
615
+ results: res.results || [],
616
+ durationMs: res.durationMs || 0,
617
+ };
618
+ }
619
+
620
+ export async function localGenerateImage(ai, params = {}) {
621
+ const weightsDir = assertLocalWeightsReady(ai);
622
+ const prompt = String(params.prompt || params.post || '').trim();
623
+ if (!prompt)
624
+ throw new Error('generateImage: пустой prompt');
625
+ const res = await runWorkerOp({
626
+ op: 'image',
627
+ weightsDir,
628
+ prompt,
629
+ size: String(params.size || '512x512'),
630
+ steps: Number(params.steps) || 8,
631
+ seed: params.seed != null ? Number(params.seed) : 42,
632
+ }, 240000);
633
+ return {
634
+ mime: res.mime || 'image/png',
635
+ base64: res.base64,
636
+ model: String(ai?.model || ai?.id || 'local-image'),
637
+ durationMs: res.durationMs || 0,
638
+ };
639
+ }
640
+
641
+ export async function localSpeak(ai, params = {}) {
642
+ const weightsDir = assertLocalWeightsReady(ai);
643
+ const text = String(params.text ?? params.post ?? '').trim().slice(0, 1500);
644
+ if (!text)
645
+ throw new Error('speak: пустой текст');
646
+ const res = await runWorkerOp({
647
+ op: 'tts',
648
+ weightsDir,
649
+ text,
650
+ language: String(params.language || ai?.language || 'Russian'),
651
+ instructions: String(params.instructions || ai?.instructions || '').trim(),
652
+ voice: String(params.voice || ai?.voice || 'serena'),
653
+ }, 120000);
654
+ return Buffer.from(res.audioBase64 || '', 'base64');
655
+ }
656
+
657
+ export async function localTranscribe(ai, params = {}) {
658
+ const weightsDir = assertLocalWeightsReady(ai);
659
+ const audio = Buffer.isBuffer(params.audio) ? params.audio : null;
660
+ if (!audio?.length)
661
+ throw new Error('transcribe: нет аудио');
662
+ const res = await runWorkerOp({
663
+ op: 'stt',
664
+ weightsDir,
665
+ audioBase64: audio.toString('base64'),
666
+ language: String(params.language || ai?.language || 'Russian'),
667
+ }, 120000);
668
+ return {
669
+ text: String(res.text || '').trim(),
670
+ model: String(ai?.model || ai?.id || 'local-stt'),
671
+ durationMs: res.durationMs || 0,
672
+ };
673
+ }
674
+
675
+ export async function localDecide(ai, params = {}) {
676
+ const state = String(params.state ?? '').trim();
677
+ const questions = params.questions && typeof params.questions === 'object' ? params.questions : {};
678
+ const prompt = `Ответь строго в JSON по схеме ключей ${JSON.stringify(Object.keys(questions))}.\nВопросы: ${JSON.stringify(questions)}\nКонтекст: ${state}`;
679
+ let out = '';
680
+ for await (const ch of localStreamChat(ai, { messages: [{ role: 'user', content: prompt }], max_tokens: 160, temperature: 0.1 }, { effort: 'off' })) {
681
+ if (typeof ch === 'string')
682
+ out += ch;
683
+ }
684
+ try {
685
+ const m = /\{[\s\S]*\}/.exec(out);
686
+ return { answers: m ? JSON.parse(m[0]) : {}, raw: out.trim(), model: String(ai?.model || ai?.id || 'local-decide') };
687
+ }
688
+ catch {
689
+ return { answers: {}, raw: out.trim(), model: String(ai?.model || ai?.id || 'local-decide') };
690
+ }
691
+ }
692
+
693
+ export async function checkLocalPythonDeps() {
694
+ try {
695
+ return await runWorkerOp({ op: 'check_deps' }, 15000);
696
+ }
697
+ catch (e) {
698
+ return { error: String(e?.message || e), packages: {}, cuda: false, deviceName: 'CPU' };
699
+ }
700
+ }
701
+
702
+ const ALLOWED_PYTHON_DEPS = new Set([
703
+ 'transformers',
704
+ 'diffusers',
705
+ 'accelerate',
706
+ 'pillow',
707
+ 'soundfile',
708
+ 'qwen-tts',
709
+ 'qwen-asr',
710
+ 'sentencepiece',
711
+ 'safetensors',
712
+ ]);
713
+
714
+ export function installLocalPythonDeps(packages = []) {
715
+ const clean = [...new Set((Array.isArray(packages) ? packages : [packages])
716
+ .map(s => String(s || '').trim().toLowerCase())
717
+ .filter(p => ALLOWED_PYTHON_DEPS.has(p)))];
718
+ if (!clean.length)
719
+ return Promise.resolve({ ok: false, error: 'Не указаны разрешённые Python-пакеты.' });
720
+ return resolvePythonCommandAsync().then(({ cmd, args }) => new Promise((resolve) => {
721
+ const proc = spawn(cmd, [...args, '-m', 'pip', 'install', '--upgrade', ...clean], {
722
+ windowsHide: true,
723
+ stdio: ['ignore', 'pipe', 'pipe'],
724
+ });
725
+ let out = '';
726
+ let err = '';
727
+ proc.stdout.on('data', d => { out += String(d); if (out.length > 8000) out = out.slice(-8000); });
728
+ proc.stderr.on('data', d => { err += String(d); if (err.length > 8000) err = err.slice(-8000); });
729
+ proc.on('error', e => resolve({ ok: false, error: String(e?.message || e) }));
730
+ proc.on('close', code => {
731
+ if (code === 0) {
732
+ closeInferWorker();
733
+ resolve({ ok: true, packages: clean, log: out.trim() });
734
+ }
735
+ else {
736
+ resolve({ ok: false, packages: clean, error: (err || out || `pip завершился с кодом ${code}`).trim() });
737
+ }
738
+ });
739
+ }));
740
+ }
741
+
742
+ export const localEngine = Object.freeze({
743
+ streamChat: localStreamChat,
744
+ embed: localEmbed,
745
+ rerank: localRerank,
746
+ generateImage: localGenerateImage,
747
+ speak: localSpeak,
748
+ transcribe: localTranscribe,
749
+ decide: localDecide,
750
+ checkDeps: checkLocalPythonDeps,
751
+ installDeps: installLocalPythonDeps,
752
+ });