odant-work 1.0.39 → 1.0.41

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 (27) hide show
  1. package/#system/package-manifest.json +29 -29
  2. package/$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js +212 -72
  3. package/$server/$folder/$file/$task/class.js +3 -0
  4. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +33 -1
  5. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/feed.js +65 -1
  6. package/$server/$folder/lib/consultant/consultant.js +9 -0
  7. package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +27 -7
  8. package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +2 -2
  9. package/package.json +1 -1
  10. package/sources/data/progress.md +11 -0
  11. package/sources/modules/agent/loop.js +39 -4
  12. package/sources/modules/agent/permissions.js +271 -111
  13. package/sources/modules/agent/session.js +89 -2
  14. package/sources/modules/agent/system.js +10 -3
  15. package/sources/modules/agent/tools/chrome.js +25 -4
  16. package/sources/modules/agent/tools/desktop.js +184 -170
  17. package/sources/modules/agent/tools/dev/checks.js +160 -160
  18. package/sources/modules/agent/tools/dev/git.js +276 -276
  19. package/sources/modules/agent/tools/net.js +45 -45
  20. package/sources/modules/agent/tools/os-proc.js +179 -169
  21. package/sources/modules/agent/tools/services.js +280 -275
  22. package/sources/modules/trainer/index.js +1 -0
  23. package/sources/modules/trainer/local-engine.js +321 -55
  24. package/sources/modules/trainer/worker/local_infer_worker.py +34 -12
  25. package/sources/reactor.js +8 -0
  26. package/sources/server/class/feed.js +21 -12
  27. package/sources/server/logs.js +50 -8
@@ -127,6 +127,11 @@ export default {
127
127
  this._resultsList = undefined;
128
128
  this.dockTab = 'context';
129
129
  this.resultKey = '';
130
+ this._monitorOpenedFor = '';
131
+ this._cuFor = null;
132
+ this._cu = null;
133
+ this.computerState = 'missing';
134
+ this.computerChecked = false;
130
135
  }
131
136
  this._bound = n || null;
132
137
  if (!n)
@@ -399,8 +404,11 @@ export default {
399
404
  const r = await fetch('/~computer/' + encodeURIComponent(this.computerName) + '/status' + this.computerQuery, { credentials: 'same-origin', signal: AbortSignal.timeout(6000) });
400
405
  const data = await r.json().catch(() => ({}));
401
406
  const state = data.state || 'missing';
407
+ const prevState = this.computerState;
402
408
  if (state !== this.computerState)
403
409
  this.computerState = state;
410
+ if (state === 'running' && prevState !== 'running')
411
+ this._openMonitorOnce();
404
412
  }
405
413
  catch {
406
414
  if (this.computerState !== 'missing')
@@ -408,6 +416,14 @@ export default {
408
416
  }
409
417
  this.computerChecked = true;
410
418
  },
419
+ _openMonitorOnce() {
420
+ const taskKey = this.$item?.path || this.$item?.id || '_';
421
+ if (this._monitorOpenedFor === taskKey)
422
+ return;
423
+ this._monitorOpenedFor = taskKey;
424
+ this.dockOpen = true;
425
+ this.dockTab = 'monitor';
426
+ },
411
427
  _startPcPoll() {
412
428
  if (this._pcPoll)
413
429
  return;
@@ -434,6 +450,8 @@ export default {
434
450
  this._lastDelta = Date.now();
435
451
  if (this.status !== 'running')
436
452
  this.status = 'running';
453
+ if (/^(?:computer_|sandbox_)/.test(String(d.name || '')) && d.name !== 'computer_destroy')
454
+ this._openMonitorOnce();
437
455
  this._stick();
438
456
  return;
439
457
  }
@@ -473,12 +491,16 @@ export default {
473
491
  this.streams = s;
474
492
  }
475
493
  const before = this._docKeys;
494
+ const prevComputerUsed = Boolean(this._cu?.used);
476
495
  this.data = data;
477
496
  this.status = data.status || 'idle';
478
497
  this._lastDelta = Date.now();
479
498
  this._noticeDocs(before);
480
- if (this.computer.used)
499
+ if (this.computer.used) {
500
+ if (!prevComputerUsed && this.status === 'running')
501
+ this._openMonitorOnce();
481
502
  this._checkComputer();
503
+ }
482
504
  if (this.starting)
483
505
  this.async(() => this.invalidate?.('starting', 'feedItems', 'activity'), Math.max(50, 20100 - (Date.now() - (+data.created || 0))));
484
506
  this._stick();
@@ -616,6 +638,16 @@ export default {
616
638
  const res = await this.$item?.fetch('approve', {}, JSON.stringify({ call: callId, ...payload }));
617
639
  if (res && res.ok === false)
618
640
  this.toast(res.error || 'Не удалось отправить ответ');
641
+ else if (this.$item?.path && navigator.serviceWorker?.controller) {
642
+ try {
643
+ navigator.serviceWorker.controller.postMessage({ type: 'work:task-visible', task: this.$item.path });
644
+ }
645
+ catch { /* ignore */ }
646
+ }
647
+ },
648
+ /** Кратко объяснить действие и последствия ожидающего подтверждения с помощью быстрой модели. */
649
+ async explainCall(callId) {
650
+ return this.$item?.fetch('explain_call', {}, JSON.stringify({ call: callId }));
619
651
  },
620
652
  async revert(item) {
621
653
  if (!item?.id || item.id === 'optimistic')
@@ -349,6 +349,18 @@ ODA({ is: 'microchat-tool',
349
349
  .ask .why { @apply --muted; font-size: x-small; }
350
350
  .btns { @apply --horizontal; flex-wrap: wrap; gap: 8px; }
351
351
  .btns oda-button { border-radius: var(--radius-s); padding: 4px 12px; box-sizing: border-box; }
352
+ .btns .help-btn { padding: 4px 9px; font-weight: 700; min-width: 28px; }
353
+ .auto-tag { padding: 1px 6px; border-radius: 999px; background: var(--accent-soft); color: var(--accent-color); font-weight: 600; }
354
+ .explain-box {
355
+ padding: 8px 10px;
356
+ border-radius: var(--radius-s);
357
+ background: var(--content-background);
358
+ border: 1px solid var(--subtle-border);
359
+ font-size: 12px;
360
+ line-height: 1.45;
361
+ user-select: text;
362
+ }
363
+ .explain-err { color: var(--error-color); font-size: 12px; }
352
364
  .ghost { border: 1px solid var(--subtle-border); background: var(--content-background); }
353
365
  .danger { color: var(--error-color); fill: var(--error-color); }
354
366
  .opt[selected] { outline: 2px solid var(--accent-color); }
@@ -375,6 +387,7 @@ ODA({ is: 'microchat-tool',
375
387
  <span class="label" no-flex>{{meta.label}}</span>
376
388
  <span class="target" flex :title="linkPath ? 'Открыть ' + linkPath : target" :link="!!linkPath" @tap.stop="openArtifact">{{target}}</span>
377
389
  <span class="aux" no-flex ~if="data?.diff"><span class="plus">+{{data.diff.added}}</span> <span class="minus">−{{data.diff.removed}}</span></span>
390
+ <span class="aux auto-tag" no-flex ~if="data?.autoAllowed" :title="data?.scopeLabel || 'Разрешено ранее в этой задаче'">авторазрешено</span>
378
391
  <span class="aux" no-flex ~if="statusLabel">{{statusLabel}}</span>
379
392
  <span class="aux" no-flex ~if="duration">{{duration}}</span>
380
393
  <oda-icon no-flex :icon="statusIcon" :icon-size="16" :bad="['error', 'denied'].includes(data?.status)" :good="data?.status === 'ok'" :hold="attention"></oda-icon>
@@ -387,8 +400,15 @@ ODA({ is: 'microchat-tool',
387
400
  <div class="why" ~if="data?.reason">{{data.reason}}</div>
388
401
  <div class="btns">
389
402
  <oda-button hide-icon accent-invert label="Разрешить" @tap="approve(true)"></oda-button>
390
- <oda-button hide-icon class="ghost" ~if="!data?.noAlways" label="Разрешить всегда" :title="'Не спрашивать про «' + meta.label + '» в этой задаче'" @tap="approve(true, true)"></oda-button>
403
+ <oda-button hide-icon class="ghost" ~if="!data?.noAlways" :label="alwaysBtnLabel" :title="alwaysBtnTitle" @tap="approve(true, true)"></oda-button>
391
404
  <oda-button hide-icon class="ghost danger" label="Отклонить" @tap="approve(false)"></oda-button>
405
+ <oda-button hide-icon class="ghost help-btn" label="?" :disabled="explainLoading" title="Кратко объяснить действие и последствия с помощью ИИ" @tap="toggleExplain()"></oda-button>
406
+ </div>
407
+ <div class="why" ~if="!data?.noAlways && data?.approvalLabel">Общее разрешение: {{data.approvalLabel}}</div>
408
+ <div class="explain-box" ~if="explainLoading">Анализирую действие…</div>
409
+ <div class="explain-err" ~if="explainError && !explainLoading">{{explainError}}</div>
410
+ <div class="explain-box" ~if="explainOpen && !explainLoading && explainText">
411
+ <oda-markdown-viewer vertical :value="explainText"></oda-markdown-viewer>
392
412
  </div>
393
413
  </div>
394
414
 
@@ -638,6 +658,50 @@ ODA({ is: 'microchat-tool',
638
658
  return shell.reply(this.data.id, { values: this.values, content: text || undefined });
639
659
  shell.reply(this.data.id, { content: text });
640
660
  },
661
+ explainOpen: false,
662
+ explainLoading: false,
663
+ explainError: '',
664
+ explainLocal: '',
665
+ get explainText() {
666
+ return this.explainLocal || this.data?.explanation || '';
667
+ },
668
+ get alwaysBtnLabel() {
669
+ return this.data?.alwaysLabel || 'Разрешить подобные';
670
+ },
671
+ get alwaysBtnTitle() {
672
+ return this.data?.approvalLabel
673
+ ? 'Не спрашивать в этой задаче: ' + this.data.approvalLabel
674
+ : 'Не спрашивать про «' + (this.meta?.label || '') + '» в этой задаче';
675
+ },
676
+ async toggleExplain() {
677
+ if (this.explainLoading)
678
+ return;
679
+ if (this.explainText) {
680
+ this.explainOpen = !this.explainOpen;
681
+ return;
682
+ }
683
+ const shell = findShell(this);
684
+ if (typeof shell?.explainCall !== 'function') {
685
+ this.explainError = 'Пояснение недоступно вне окна задачи';
686
+ return;
687
+ }
688
+ this.explainLoading = true;
689
+ this.explainError = '';
690
+ this.explainOpen = true;
691
+ try {
692
+ const res = await shell.explainCall(this.data.id);
693
+ if (res?.ok && res.text)
694
+ this.explainLocal = String(res.text);
695
+ else
696
+ this.explainError = res?.error || 'Не удалось получить пояснение от модели';
697
+ }
698
+ catch (e) {
699
+ this.explainError = String(e?.message || e || 'Ошибка запроса');
700
+ }
701
+ finally {
702
+ this.explainLoading = false;
703
+ }
704
+ },
641
705
  approve(accept, always) {
642
706
  findShell(this)?.reply(this.data.id, { accept, always: !!always, content: String(this.comment || '').trim() || undefined });
643
707
  },
@@ -1282,6 +1282,15 @@ ODA({
1282
1282
  const res = await this.taskItem?.fetch('approve', {}, JSON.stringify({ call: callId, ...payload }));
1283
1283
  if (res && res.ok === false)
1284
1284
  this.toast(res.error || 'Не удалось отправить ответ');
1285
+ else if (this.taskItem?.path && navigator.serviceWorker?.controller) {
1286
+ try {
1287
+ navigator.serviceWorker.controller.postMessage({ type: 'work:task-visible', task: this.taskItem.path });
1288
+ }
1289
+ catch { /* ignore */ }
1290
+ }
1291
+ },
1292
+ async explainCall(callId) {
1293
+ return this.taskItem?.fetch('explain_call', {}, JSON.stringify({ call: callId }));
1285
1294
  },
1286
1295
 
1287
1296
  async revert(item) {
@@ -294,10 +294,11 @@ export default {
294
294
  {{testing ? 'Выполняю…' : testButtonLabel}}
295
295
  </button>
296
296
  </div>
297
- <div class="msg warn" ~if="testMissingDeps.length">
298
- <span>Не хватает Python-библиотек: <code>{{testMissingDeps.join(', ')}}</code></span>
297
+ <div class="msg warn" ~if="testPythonMissing || testMissingDeps.length">
298
+ <span ~if="testPythonMissing">На ПК не найден Python — WORK автоматически установит изолированный Python 3.11 и библиотеки: <code>{{testDepsToInstall.join(', ')}}</code></span>
299
+ <span ~if="!testPythonMissing">Не хватает Python-библиотек: <code>{{testMissingDeps.join(', ')}}</code></span>
299
300
  <button type="button" class="btn primary" :disabled="installingDeps" @tap="installMissingDeps()">
300
- {{installingDeps ? 'Установка…' : 'Доустановить зависимости'}}
301
+ {{installingDeps ? 'Установка среды…' : (testPythonMissing ? 'Установить Python и пакеты' : 'Доустановить зависимости')}}
301
302
  </button>
302
303
  </div>
303
304
  <div class="toolbar" ~if="testMetricsLine" style="font-size:12px;opacity:0.85;">
@@ -323,8 +324,22 @@ export default {
323
324
  testImageUrl: '',
324
325
  testMetricsLine: '',
325
326
  testMissingDeps: [],
327
+ testPythonMissing: false,
326
328
  testing: false,
327
329
  installingDeps: false,
330
+ get testDepsToInstall() {
331
+ if (this.testMissingDeps?.length)
332
+ return this.testMissingDeps;
333
+ const map = {
334
+ llm: ['torch'],
335
+ embed: ['torch', 'transformers'],
336
+ rerank: ['torch', 'transformers'],
337
+ image: ['torch', 'diffusers', 'accelerate', 'pillow', 'transformers'],
338
+ tts: ['torch', 'qwen-tts', 'soundfile', 'transformers'],
339
+ stt: ['torch', 'qwen-asr', 'soundfile', 'transformers'],
340
+ };
341
+ return map[this.testModality] || ['torch', 'transformers'];
342
+ },
328
343
  busyAction: false,
329
344
  notice: '',
330
345
  error: '',
@@ -515,20 +530,22 @@ export default {
515
530
  reader.readAsDataURL(f);
516
531
  },
517
532
  async installMissingDeps() {
518
- if (!this.$item || !this.testMissingDeps.length)
533
+ const pkgs = this.testDepsToInstall;
534
+ if (!this.$item || !pkgs.length)
519
535
  return;
520
536
  this.installingDeps = true;
521
537
  this.error = '';
522
538
  this.notice = '';
523
539
  try {
524
- const res = await this.$item.fetch('trainer_install_python_deps', {}, { packages: this.testMissingDeps });
540
+ const res = await this.$item.fetch('trainer_install_python_deps', {}, { packages: pkgs });
525
541
  if (res?.ok) {
526
542
  this.testMissingDeps = [];
527
- this.notice = 'Пакеты установлены: ' + (res.packages || []).join(', ') + '. Повторяем проверку…';
543
+ this.testPythonMissing = false;
544
+ this.notice = 'Среда готова, пакеты установлены: ' + (res.packages || []).join(', ') + '. Повторяем проверку…';
528
545
  await this.runTestPrompt();
529
546
  }
530
547
  else {
531
- this.error = res?.error || 'Не удалось установить Python-пакеты.';
548
+ this.error = res?.error || 'Не удалось установить Python-среду и пакеты.';
532
549
  }
533
550
  }
534
551
  catch (e) {
@@ -552,6 +569,7 @@ export default {
552
569
  this.testImageUrl = '';
553
570
  this.testMetricsLine = '';
554
571
  this.testMissingDeps = [];
572
+ this.testPythonMissing = false;
555
573
  try {
556
574
  const body = { modality: m };
557
575
  if (m === 'llm')
@@ -572,6 +590,8 @@ export default {
572
590
  const res = await this.$item.fetch('trainer_test_model', {}, body);
573
591
  if (!res?.ok) {
574
592
  this.error = res?.error || 'Ошибка проверки модели.';
593
+ if (res?.pythonMissing)
594
+ this.testPythonMissing = true;
575
595
  if (Array.isArray(res?.missingDeps))
576
596
  this.testMissingDeps = res.missingDeps;
577
597
  return;
@@ -413,9 +413,9 @@ export default {
413
413
  <div class="model-main" style="margin-bottom:6px;">
414
414
  <strong>Диагностика локальных моделей (/MODELS/Local)</strong>
415
415
  <div class="toolbar">
416
- <span class="status-chip ok" ~if="checkAllResult.pythonDeps?.deviceName">Python: {{checkAllResult.pythonDeps.deviceName}}</span>
416
+ <span class="status-chip" ~class="checkAllResult.pythonDeps?.pythonMissing ? 'err' : 'ok'" ~if="checkAllResult.pythonDeps?.deviceName">Python: {{checkAllResult.pythonDeps.deviceName}}</span>
417
417
  <button type="button" class="btn primary" ~if="missingPythonPkgs.length" :disabled="installingPythonDeps" @tap="installMissingPythonDeps()">
418
- {{installingPythonDeps ? 'Установка…' : ('Доустановить пакеты (' + missingPythonPkgs.join(', ') + ')')}}
418
+ {{installingPythonDeps ? 'Установка среды (это займёт 1–3 мин)…' : (checkAllResult.pythonDeps?.pythonMissing ? 'Установить Python 3.11 и все библиотеки' : ('Доустановить пакеты (' + missingPythonPkgs.join(', ') + ')'))}}
419
419
  </button>
420
420
  </div>
421
421
  </div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.39",
3
+ "version": "1.0.41",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -1,6 +1,17 @@
1
1
  # Прогресс: sources/data
2
2
 
3
3
  ## Последние изменения
4
+ - [~21:40, 17.11] «Разрешить подобные» с точной областью действия, кнопка `?` с пояснением ИИ, автооткрытие «Монитора» песочницы и авторазвёртывание Python-среды ИИ (`sources/modules/agent/{permissions,system,loop,session}.js`, `sources/modules/agent/tools/{chrome,desktop,net,os-proc,services}.js`, `sources/modules/agent/tools/dev/{git,checks}.js`, `sources/modules/trainer/{index,local-engine}.js`, `sources/modules/trainer/worker/local_infer_worker.py`, `$server/$folder/$file/$task/{class.js,handlers/pages/form/file/$handler/{file.js,ui/feed.js}}`, `$server/$folder/lib/consultant/consultant.js`, `MODELS/$ai/$folder/$class/{$ai,$provider}/handlers/pages/form/trainer/$handler/trainer.js`, `tests/{agent-core,chrome-bridge,dev-tools}.test.js`, `tests/ui/{task-dock,task-page,chat-create}.html`, `odant-work@1.0.41`):
5
+ - **Умные разрешения в задаче вместо «Разрешить всегда» наугад (`permissions.js`):** `classifyShellCommand` и `resolveApprovalScope` вычисляют точную область «подобных» вызовов: `shell:read` для чтения и проверки состояния (`Get-Content`, `Get-Process`, `git status/log/diff`, `wsl --status`, `docker ps` и т.п.), `shell:prog:<утилита>` для запуска конкретной программы, `os_service:<служба>`, `chrome:page:<домен>` для клика/ввода/перехода на конкретном сайте, `desktop_file:write`, `desktop_app:open:<приложение>`, `desktop_app:focus` и `svc:<id>` для прочих сервисов. Разрушительные команды (`Remove-Item`, `rm`, `del`, `format`, `Stop-Process`, `taskkill`, `shutdown`, `wsl --unregister`, конвейеры `curl | …`) и опасные инструменты (`taint`, `os_delete`, `computer_destroy`, `git_push`, `merge_branch`, `open_page`, `os_kill`, `http_request`, `desktop_mode`, `chrome_mode`) по-прежнему требуют подтверждения каждый раз (`noAlways: true`).
6
+ - **Кнопка «Разрешить подобные» и бейдж «авторазрешено» (`ui/feed.js`, `loop.js`, `session.js`):** кнопка подтверждения переименована и показывает в `title`/подписи, что именно разрешается («команды чтения и проверки состояния (логи, статусы, файлы без изменений)», «команды с утилитой «node» в этой задаче» и т.д.); выданная область сохраняется в `body.allowed` задачи и переиспользуется при перезапуске; автоматически разрешённые вызовы в ленте помечаются бейджем **`авторазрешено`**. Кнопки `Разрешить` / `Отклонить` в push-уведомлениях Windows по-прежнему работают, а после ответа в карточке видимые уведомления задачи закрываются (`work:task-visible`).
7
+ - **Кнопка `?` с пояснением вызова ИИ (`explain_call`, `explainCall`):** рядом с `Разрешить` появилась кнопка `?`, которая просит модель кратко объяснить суть вызова и его последствия (`compactLlm`, при недоступности — модель задачи, `effort: 'off'`); ответ кэшируется в `entry.explanation` и показывается в `.explain-box`, повторные нажатия не тратят токены. Тот же метод доступен в карточке подтверждения Консультанта (`consultant.js`).
8
+ - **Автооткрытие правой панели на вкладке «Монитор» (`file.js`):** при появлении в задаче первого вызова `sandbox_*` / `computer_*` (кроме `computer_destroy`) или при переходе контейнера в состояние `running` правая панель открывается сама и встаёт на вкладку **«Монитор»** (один раз на задачу, чтобы не перебивать ручной выбор пользователя).
9
+ - **Авторазвёртывание изолированного Python 3.11 и библиотек ИИ (`local-engine.js`, `local_infer_worker.py`, `form/trainer`):** если на ПК нет Python вне заглушки Microsoft Store, карточка модели и `/MODELS/Local` показывают кнопку **«Установить Python и пакеты»**: WORK скачивает `uv`, разворачивает Python 3.11 + `venv` в `MODELS/Local/$provider/#runtime/` (без прав администратора и без Microsoft Store) и ставит `torch`, `transformers`, `diffusers`, `accelerate`, `pillow`, `soundfile`, `qwen-tts`, `qwen-asr`. Поиск интерпретатора проверяет фактический `sys.executable` и отсекает `WindowsApps\python.exe`; воркер больше не падает при отсутствии `torch`, а возвращает `missingDeps`; ответы `pythonMissing`/`missingDeps` доводятся до UI (`trainer_test_model`, `trainer_check_all_models`).
10
+ - [~19:00, 17.11] Единая личная лента по умолчанию в чате всех точек, переключатель «Мои записи / Местный лог» для BOSS и очистка пустых дат (`$server/$folder/$class/$structure/handlers/pages/form/chat/$handler/chat.js`, `sources/server/{class/feed.js,logs.js}`, `sources/reactor.js`, `tests/{access,logs-module}.test.js`, `tests/ui/chat-create.html`, `odant-work@1.0.40`):
11
+ - **Личная лента пользователя везде по умолчанию (`feed.js`, `chat.js`):** `chatSource` по умолчанию всегда возвращает личный кабинет (`/USERS//<uid>`), независимо от того, открыт ли `WORK` (`$server`), база или подразделение и есть ли там роль `BOSS`. Местный лог точки (`this.path`) открывается только при явном `local: true` и подтверждённой роли `BOSS` (в т.ч. унаследованной сверху по дереву).
12
+ - **Переключатель `[ Мои записи | Местный лог ]` (`oda-chat`):** компактная капсула в правом верхнем углу чата, видимая только на наследниках `$structure` (включая `$server`) и только для `BOSS` (при открытии/смене точки сбрасывается в «Мои записи»). В режиме «Мои записи» `chat-ribbon` слушает `changed` и на точке, и на личном кабинете, а при отсутствии прав на запись в чужую точку отправка задачи/сообщения автоматически сохраняется в `/USERS/<uid>`.
13
+ - **Без пустых плашек дат и пунктирной линии (`logs.js`, `chat.js`):** при `nonEmpty: 1` `datesList` исключает пустой `today` и дни только со скрытыми `mainContext`-вложениями; у `chat-day` удалена `.date-line::before`.
14
+ - **Фикс `Reactor.join_props` (`sources/reactor.js`):** при переопределении реактивного свойства родителя методом потомка (`skill-tree extends item-tree` / `execute`) очищаются родительские `get`/`set`, устраняя `Invalid property descriptor` при регистрации компонента.
4
15
  - [~17:30, 17.11] Починка локального Python-движка на Windows: асинхронный подбор интерпретатора вместо заглушки Microsoft Store (код 9009) (`sources/modules/trainer/local-engine.js`, `odant-work@1.0.39`):
5
16
  - **Причина ошибки «Процесс локального инференса завершился (код 9009)» на всех не-LLM моделях (`/MODELS/Local/*`, кроме основной через `bubo.exe`):** воркер спавнился командой `python` без проверки; на Windows первой по PATH может оказаться заглушка Microsoft Store (`WindowsApps\python.exe`), которая молча завершается с кодом 9009 («Python was not found…»).
6
17
  - **Асинхронный подбор рабочего интерпретатора (`resolvePythonCommandAsync`):** `.venv` проекта → команды из PATH (`python`, `python3`, лаунчер `py -3`) с пробным запуском `--version` (заглушки и отсутствующие команды отсеиваются) → известные папки установки (`%LOCALAPPDATA%\Programs\Python\*`, `C:\Program Files\Python*`, `C:\Python*`). Результат кэшируется.
@@ -23,7 +23,7 @@
23
23
  */
24
24
  import { log } from './log.js';
25
25
  import { genId, clip, estimateTokens, resultText, StopError, throwIfStopped } from './util.js';
26
- import { decide } from './permissions.js';
26
+ import { decide, resolveApprovalScope } from './permissions.js';
27
27
  import { newNonce, wrapUntrusted, taintSources, untrustedNames } from './taint.js';
28
28
  import { runPreTool, runAppend, runNotify } from './hooks.js';
29
29
  import { costOf, recordUsage, budgetExceeded } from './cost.js';
@@ -734,6 +734,11 @@ async function runOne({ entry, tool, it, host, llm, opts, preapproved }) {
734
734
  await noteAudit(tool, entry, ctx, 'deny', 'policy', { reason: clip(entry.error, 300) });
735
735
  return;
736
736
  }
737
+ if (decision.verdict === 'allow' && decision.autoAllowed) {
738
+ entry.autoAllowed = true;
739
+ if (decision.scopeLabel)
740
+ entry.scopeLabel = decision.scopeLabel;
741
+ }
737
742
  if (decision.verdict === 'ask' && typeof host.wait !== 'function') {
738
743
  entry.status = 'denied';
739
744
  entry.error = 'нужно подтверждение человека (' + (decision.reason || 'политика') + '), а запуск автономный — предложи действие в ответе';
@@ -748,23 +753,53 @@ async function runOne({ entry, tool, it, host, llm, opts, preapproved }) {
748
753
  entry.status = 'approval';
749
754
  entry.reason = decision.reason;
750
755
  // действия во внешнем мире — каждое подтверждается отдельно («разрешить всегда» не предлагается)
751
- if (decision.noAlways)
756
+ if (decision.noAlways) {
752
757
  entry.noAlways = true;
758
+ }
759
+ else {
760
+ const scope = decision.scope || resolveApprovalScope(tool, entry.args || {}, ctx);
761
+ if (scope?.noAlways) {
762
+ entry.noAlways = true;
763
+ }
764
+ else if (scope?.key) {
765
+ entry.approvalScope = scope.key;
766
+ if (scope.label)
767
+ entry.approvalLabel = scope.label;
768
+ if (scope.buttonLabel)
769
+ entry.alwaysLabel = scope.buttonLabel;
770
+ }
771
+ }
753
772
  if (decision.hideArgs)
754
773
  entry.hideArgs = true;
755
774
  await host.save();
756
- const res = await host.wait({ kind: 'approval', item: it.id, call: entry.id, tool: entry.name, args: entry.args, reason: decision.reason, hideArgs: decision.hideArgs }) || {};
775
+ const res = await host.wait({
776
+ kind: 'approval',
777
+ item: it.id,
778
+ call: entry.id,
779
+ tool: entry.name,
780
+ args: entry.args,
781
+ reason: decision.reason,
782
+ hideArgs: decision.hideArgs,
783
+ approvalScope: entry.approvalScope,
784
+ approvalLabel: entry.approvalLabel,
785
+ alwaysLabel: entry.alwaysLabel,
786
+ }) || {};
757
787
  throwIfStopped(host.signal);
758
788
  delete entry.reason;
789
+ const scopeKey = entry.approvalScope || entry.name;
790
+ delete entry.approvalLabel;
791
+ delete entry.alwaysLabel;
759
792
  if (res.always && !entry.noAlways)
760
- host.allowed?.add?.(entry.name);
793
+ host.allowed?.add?.(scopeKey);
761
794
  if (!res.accept) {
795
+ delete entry.approvalScope;
762
796
  entry.status = 'denied';
763
797
  entry.answer = res.content ? String(res.content) : undefined;
764
798
  await host.save();
765
799
  await noteAudit(tool, entry, ctx, 'ask', 'denied', { reason: clip(decision.reason, 300), answer: entry.answer ? clip(entry.answer, 300) : undefined });
766
800
  return;
767
801
  }
802
+ delete entry.approvalScope;
768
803
  approved = { reason: decision.reason, always: !!(res.always && !entry.noAlways) };
769
804
  }
770
805
  entry.status = 'running';