odant-work 1.0.28 → 1.0.30

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 (40) hide show
  1. package/#system/package-manifest.json +43 -37
  2. package/$server/$folder/$class/ai/agents/builder.md +34 -24
  3. package/$server/$folder/$class/ai/agents/org-architect.md +40 -0
  4. package/$server/$folder/$class/ai/agents/readme.md +3 -1
  5. package/$server/$folder/$class/ai/agents/schema-validator.md +35 -0
  6. package/$server/$folder/$class/ai/skills/accounting-design.md +21 -0
  7. package/$server/$folder/$class/ai/skills/data-modeling.md +25 -0
  8. package/$server/$folder/$class/ai/skills/readme.md +3 -0
  9. package/$server/$folder/$class/ai/skills/schema-migration.md +23 -0
  10. package/$server/$folder/$class/handlers/pages/form/objects/$handler/objects.js +2 -0
  11. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/file.js +60 -74
  12. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/readme.md +3 -3
  13. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/dock.js +65 -82
  14. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/docs.js +0 -20
  15. package/$server/$folder/$file/$task/handlers/pages/form/file/$handler/ui/util.js +4 -0
  16. package/$server/$folder/lib/consultant/consultant.js +1 -1
  17. package/$server/$folder/lib/tree/tree.js +2 -1
  18. package/MODELS/$ai/$folder/$class/$ai/class.js +17 -3
  19. package/MODELS/$ai/$folder/$class/$ai/handlers/pages/form/trainer/$handler/trainer.js +103 -6
  20. package/MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js +37 -14
  21. package/oda/components/layouts/editor-form/editor-form.js +16 -3
  22. package/package.json +1 -1
  23. package/sources/data/progress.md +21 -0
  24. package/sources/data/schema.js +66 -2
  25. package/sources/host/auto-updater.js +1 -1
  26. package/sources/modules/agent/index.js +5 -4
  27. package/sources/modules/agent/tools/docs.js +1 -1
  28. package/sources/modules/agent/tools/meta.js +5 -1
  29. package/sources/modules/agent/tools/work/classes.js +1081 -0
  30. package/sources/modules/agent/tools/work/fs.js +1 -1
  31. package/sources/modules/agent/tools/work.js +1 -0
  32. package/sources/modules/trainer/halogen.js +350 -32
  33. package/sources/modules/trainer/huggingface.js +80 -6
  34. package/sources/modules/trainer/index.js +139 -3
  35. package/sources/modules/trainer/local-engine.js +26 -29
  36. package/sources/modules/trainer/paths.js +119 -0
  37. package/sources/modules/trainer/providers.js +51 -36
  38. package/sources/modules/trainer/runner.js +72 -31
  39. package/sources/server/class/security.js +10 -3
  40. package/sources/server/class.js +6 -0
@@ -12,7 +12,7 @@ import './ui/dock.js';
12
12
  import './ui/voice-ui.js';
13
13
  import { VoiceController } from './ui/voice.js';
14
14
  import { collectDocs, computeStats, stableDocs, activityOf, taskFiles, computerUse, realPathOfSnapshot } from './ui/docs.js';
15
- import { pathOfWorkHref, workHref, extOf } from './ui/util.js';
15
+ import { pathOfWorkHref, workHref } from './ui/util.js';
16
16
 
17
17
  /**
18
18
  * Клик по WORK-ссылке в markdown (событие md-link от oda-markdown-viewer):
@@ -86,14 +86,12 @@ export default {
86
86
  pinned: true,
87
87
  groupOpen: {},
88
88
  dockOpen: { $def: false, $save: true },
89
- /** Вкладка дока: context | monitor | results | files. Открытый на вкладке «Файлы» файл — dockFile (ключ из files), результат — resultKey. */
89
+ /** Вкладка дока: context | monitor | results | files. Выбранный результат — resultKey. */
90
90
  dockTab: { $def: 'context' },
91
- dockFile: '',
92
91
  resultKey: '',
93
92
  resultKeyAt: 0,
94
93
  dockWidth: { $def: 520, $save: true },
95
94
  freshDocs: 0,
96
- extraFiles: [],
97
95
  /** Голосовой режим включён; полосы кнопки в шапке задачи подключаются к голосу при смене. */
98
96
  voiceOn: {
99
97
  $def: false,
@@ -123,13 +121,11 @@ export default {
123
121
  this.streams = {};
124
122
  this.optimistic = null;
125
123
  this.status = 'idle';
126
- this.extraFiles = [];
127
124
  this._docKeys = undefined;
128
125
  this._docsList = undefined;
129
126
  this._filesList = undefined;
130
127
  this._resultsList = undefined;
131
128
  this.dockTab = 'context';
132
- this.dockFile = '';
133
129
  this.resultKey = '';
134
130
  }
135
131
  this._bound = n || null;
@@ -325,25 +321,25 @@ export default {
325
321
  },
326
322
  /** Стабилизированный список опубликованных результатов (data.results) без пересоздания объектов при _reload. */
327
323
  get results() {
328
- const list = (this.data?.results || []).filter(r => r?.snapshot).map(r => ({
329
- key: 'result:' + r.snapshot,
330
- kind: 'file',
331
- path: r.snapshot,
332
- snapshot: r.snapshot,
333
- title: r.title || (r.snapshot ? String(r.snapshot).split('/').pop() : 'Результат'),
334
- time: r.time,
335
- published: true,
336
- }));
324
+ const list = (this.data?.results || []).filter(r => r?.snapshot).map(r => {
325
+ const real = realPathOfSnapshot(r.snapshot) || r.snapshot;
326
+ return {
327
+ key: 'result:' + r.snapshot,
328
+ kind: 'file',
329
+ path: real,
330
+ snapshot: r.snapshot,
331
+ title: r.title || (real ? String(real).split('/').pop() : 'Результат'),
332
+ time: r.time,
333
+ published: true,
334
+ };
335
+ });
337
336
  const { docs } = stableDocs(this._resultsList, list);
338
337
  this._resultsList = docs;
339
338
  return docs;
340
339
  },
341
- /** Все файлы задачи: вложения человека, созданное агентом, опубликованное (+ открытые по ссылке из ответа). */
340
+ /** Все файлы задачи: вложения человека, созданное агентом, опубликованное. */
342
341
  get files() {
343
342
  const list = taskFiles(this.items, this.data?.results || []);
344
- for (const x of this.extraFiles)
345
- if (!list.some(f => f.real === x.real))
346
- list.push(x);
347
343
  const { docs } = stableDocs(this._filesList, list);
348
344
  this._filesList = docs;
349
345
  return docs;
@@ -487,30 +483,28 @@ export default {
487
483
  })();
488
484
  },
489
485
  /**
490
- * Новый результат, отчёт или файл во время работы:
491
- * - если размещён результат (publish / data.results или отчёт субагента) — сразу открываем правую панель
486
+ * Новый результат (publish / data.results) или файл во время работы:
487
+ * - если размещён результат (publish / data.results) — сразу открываем правую панель
492
488
  * и переключаемся на вкладку «Результаты»;
493
- * - если создан обычный файл: при открытом доке показываем его, при закрытом — индикатор на кольце.
489
+ * - если создан обычный файл: при открытом доке показываем список файлов, при закрытом — индикатор на кольце.
494
490
  */
495
491
  _noticeDocs(before) {
496
492
  const resultKeys = (this.data?.results || []).filter(r => r?.snapshot).map(r => 'result:' + r.snapshot);
497
- const reportKeys = this.docs.filter(d => d.kind === 'text').map(d => d.key);
498
- const allResultKeys = [...resultKeys, ...reportKeys];
499
493
  const fileKeys = this.files.map(f => f.key);
500
- const keys = [...allResultKeys, ...fileKeys];
494
+ const keys = [...resultKeys, ...fileKeys];
501
495
  this._docKeys = keys;
502
496
  if (!before) {
503
- if (allResultKeys.length) {
497
+ if (resultKeys.length) {
504
498
  this.dockOpen = true;
505
499
  this.dockTab = 'results';
506
- this.resultKey = allResultKeys.at(-1);
500
+ this.resultKey = resultKeys.at(-1);
507
501
  this.resultKeyAt = Date.now();
508
502
  this.freshDocs = 0;
509
503
  }
510
504
  return;
511
505
  }
512
506
  const added = keys.filter(k => !before.includes(k));
513
- const newResultKeys = added.filter(k => k.startsWith('result:') || k.startsWith('agent:') || k.startsWith('answer:'));
507
+ const newResultKeys = added.filter(k => k.startsWith('result:'));
514
508
  const files = added.map(k => this.files.find(f => f.key === k)).filter(f => f && f.source !== 'user');
515
509
  if (!newResultKeys.length && !files.length)
516
510
  return;
@@ -526,10 +520,8 @@ export default {
526
520
  this.freshDocs += files.length;
527
521
  return;
528
522
  }
529
- if (files.length && ['context', 'files'].includes(this.dockTab)) {
523
+ if (files.length && ['context', 'files'].includes(this.dockTab))
530
524
  this.dockTab = 'files';
531
- this.dockFile = files.at(-1).key;
532
- }
533
525
  else
534
526
  this.freshDocs += files.length;
535
527
  },
@@ -641,47 +633,29 @@ export default {
641
633
  if (this.dockOpen)
642
634
  this.freshDocs = 0;
643
635
  },
644
- /** Выбор вкладки; повторный клик по «Файлы» (когда файл открыт) возвращает к списку. */
636
+ /** Выбор вкладки в правой панели доков. */
645
637
  selectTab(key) {
646
638
  const tab = ['context', 'monitor', 'results', 'files'].includes(key) ? key : 'context';
647
- if (tab === 'files' && this.dockTab === 'files')
648
- this.dockFile = '';
649
639
  this.dockTab = tab;
650
640
  if (this.dockOpen)
651
641
  this.freshDocs = 0;
652
642
  },
653
643
  /**
654
- * Открыть док: файл по пути (снимок или живой путь — в списке или нет) → вкладка «Файлы» на этом файле;
655
- * отчёт (key agent:…) → вкладка «Результаты».
644
+ * Открыть док: опубликованный результат (key result:…) → вкладка «Результаты»;
645
+ * любой файл → штатное открытие в форме WORK (work-form / execute).
656
646
  */
657
647
  openDoc(doc = {}) {
658
- if (String(doc.key || '').startsWith('agent:')) {
648
+ if (String(doc.key || '').startsWith('result:')) {
659
649
  this.resultKey = doc.key;
660
650
  this.resultKeyAt = Date.now();
661
651
  this.dockTab = 'results';
652
+ this.dockOpen = true;
653
+ this.freshDocs = 0;
654
+ return;
662
655
  }
663
- else {
664
- const path = doc.path || '';
665
- const real = realPathOfSnapshot(path);
666
- let file = this.files.find(f => f.key === doc.key || (path && (f.real === real || f.path === path)));
667
- if (!file && path) {
668
- file = { key: 'f:' + real, real, path, title: real.split('/').pop(), ext: extOf(real), icon: 'carbon:document', time: Date.now(), source: 'link' };
669
- this.extraFiles = [...this.extraFiles, file];
670
- }
671
- if (!file)
672
- return;
673
- this.dockFile = file.key;
674
- this.dockTab = 'files';
675
- }
676
- this.dockOpen = true;
677
- this.freshDocs = 0;
678
- }, /** Файл на вкладке «Файлы»: открыть / вернуться к списку. */
679
- openFile(key) {
680
- this.dockFile = key || '';
681
- this.dockTab = 'files';
682
- },
683
- closeFile() {
684
- this.dockFile = '';
656
+ const path = doc.real || doc.path || '';
657
+ if (path)
658
+ this.openWorkPath(path, doc.snapshot || doc.path);
685
659
  },
686
660
  /** Сохранить текстовый док файлом в класс задачи → путь. */
687
661
  async saveDoc(name, text) {
@@ -697,28 +671,40 @@ export default {
697
671
  return '';
698
672
  }
699
673
  },
700
- /** Путь WORK: всегда открывает элемент (включая файлы и документы) в стандартном представлении формы. */
701
- async openWorkPath(path) {
674
+ /** Путь WORK: всегда открывает существующий элемент (включая файлы и документы) в стандартном представлении формы; при отсутствии показывает toast вместо битой вкладки. */
675
+ async openWorkPath(path, fallbackPath = '') {
702
676
  const raw = String(path || '').trim();
703
677
  if (!raw)
704
678
  return;
705
679
  const targetPath = realPathOfSnapshot(raw) || raw;
680
+ const candidates = [targetPath];
681
+ for (const alt of [raw, String(fallbackPath || '').trim()]) {
682
+ if (alt && !candidates.includes(alt))
683
+ candidates.push(alt);
684
+ }
685
+ let item = null;
686
+ for (const p of candidates) {
687
+ try {
688
+ let found = await WORK.get_item(p);
689
+ if (Array.isArray(found))
690
+ found = found.at(-1) || null;
691
+ if (found) {
692
+ item = found;
693
+ break;
694
+ }
695
+ }
696
+ catch { /* пробуем следующий вариант */ }
697
+ }
698
+ if (!item) {
699
+ this.toast('Файл или элемент не найден: ' + targetPath);
700
+ return;
701
+ }
706
702
  const exec = window.top?.execute || window.execute;
707
703
  if (typeof exec === 'function') {
708
- let item = await WORK.get_item(targetPath);
709
- if (Array.isArray(item))
710
- item = item.at(-1) || null;
711
- if (!item && targetPath !== raw) {
712
- item = await WORK.get_item(raw);
713
- if (Array.isArray(item))
714
- item = item.at(-1) || null;
715
- }
716
- if (item) {
717
- await exec(item);
718
- return;
719
- }
704
+ await exec(item);
705
+ return;
720
706
  }
721
- window.open(workHref(targetPath), '_blank');
707
+ window.open(workHref(item.path || targetPath), '_blank');
722
708
  },
723
709
  closeView() {
724
710
  this.fire('close-view');
@@ -12,10 +12,10 @@
12
12
 
13
13
  - **Шапка одна.** Развёрнутая в чате (`chat-item`) — своя шапка с кнопкой закрытия; chat-item по событию `own-header` прячет свою полосу, `close-view` — сворачивает. В странице `form` (`work-form`) — шапка встраивается в её верхнюю панель (на место `slot[name=top-panel]`), своей нет.
14
14
  - **Кольцо контекста** (% окна модели) — показ/скрытие доков; точка — появились новые доки, пока панель закрыта.
15
- - **Доки.** Вкладка живёт в шелле (`dockTab`: `context | monitor | results | files`), открытый на «Файлах» файл — `dockFile`, результат — `resultKey`; на «Контекст» вкладка возвращается только если её больше нет.
16
- - **Файлы** (`ui/docs.js` `taskFiles`): *все* файлы задачи одним списком — вложения человека, созданное агентом (write/edit/append, таблицы, картинки, `export_pdf`, `render_doc`, выгрузка из песочницы, `call → save_files`, файлы субагентов) и опубликованные результаты; один файл — одна плитка с последней версией. Плитки — те же карточки `chat-item compact`, что и в ленте чата; клик открывает файл в доке («← Файлы» — к списку). Тот же список показывает карточка задачи в ленте чата (превью `.task`).
15
+ - **Доки.** Вкладка живёт в шелле (`dockTab`: `context | monitor | results | files`), выбранный результат — `resultKey`; на «Контекст» вкладка возвращается только если её больше нет.
16
+ - **Файлы** (`ui/docs.js` `taskFiles`): *все* файлы задачи одним плоским списком — вложения человека, созданное агентом (write/edit/append, таблицы, картинки, `create_office_file`, `export_pdf`, `render_doc`, выгрузка из песочницы, `call → save_files`, файлы субагентов) и опубликованные результаты; один файл — одна плитка с последней версией. Плитки — те же карточки `chat-item compact`, что и в ленте чата; клик открывает файл штатно в форме WORK (`openWorkPath`), без углубления внутри панели. Тот же список показывает карточка задачи в ленте чата (превью `.task`).
17
17
  - **Монитор** (`computerUse`): есть, если задача хоть раз пользовалась компьютером (`computer_*`, `browser_*`, `sandbox_*`), даже когда он уже удалён. Жив — живой экран; иначе подпись «выключен / удалён», последние скриншоты и команды из ленты. Имя компьютера — из аргументов вызовов.
18
- - **Результаты** — опубликованные результаты и отчёты субагентов; новый отчёт при открытой панели выбирается сам. Текстовый док — копировать, скачать, сохранить файлом `.md` в класс задачи.
18
+ - **Результаты** — только явно опубликованные через `publish` (`data.results`) конечные результаты задачи (реплики агента и промежуточные отчёты субагентов сюда не попадают); для файла показывается его конечная живая версия (для лёгких форматов — превью, для офисных `.pptx`/`.docx`/`.xlsx` — карточка результата с кнопками «Открыть в редакторе» и «Скачать»). Пока результатов нет — вкладка скрыта.
19
19
  - **Контекст** (`computeStats`): модель, провайдер, лимит, использование, токены (вход/выход/всего), рассуждение, сообщения, вызовы, даты, разбивка контекста последнего хода (`body.context` от ядра: system, схемы инструментов; диалог — оценка), исходные элементы ленты с JSON и экспорт сессии.
20
20
  - **Лента**: подряд идущие действия — группа «N действий» (раскрыта, пока идёт работа или нужен человек; свёрнута по завершении). Стрим — `task.delta` → `streams[id]`; строка берёт более длинное из сохранённого и стрима. Карточка разрешения показывает только суть (что и зачем) и крупные кнопки «Разрешить / Разрешить всегда / Отклонить»: служебные аргументы — в раскрытой карточке вызова, комментарий к отказу — в поле ввода композера.
21
21
  - **Композер**: автовысота, Enter/Shift+Enter, Esc — стоп; вложения — «+», вставка, перетаскивание; диктовка (Web Speech API, где есть); меню режима, выбор модели, уровень рассуждения (если модель умеет), отправка/стоп.
@@ -228,14 +228,13 @@ ODA({ is: 'microchat-dock',
228
228
  `,
229
229
  get shell() { return findShell(this); },
230
230
  get docs() { return this.shell?.docs || []; },
231
- /** Опубликованные результаты (из shell.results / data.results) и отчёты субагентов. */
231
+ /** Опубликованные результаты (из shell.results / data.results). */
232
232
  get results() { return this.shell?.results || this.shell?.data?.results || []; },
233
- get reports() { return this.docs.filter(d => d.kind === 'text'); },
234
233
  /** Вкладка живёт в шелле (dockTab): openDoc и новые файлы переключают её оттуда. */
235
234
  get tab() { return this.shell?.dockTab || 'context'; },
236
235
  /** Компьютер использовался в задаче — «Монитор» есть и после его удаления (скриншоты и команды остаются в ленте). */
237
236
  get hasComputer() { return !!this.shell?.computer?.used; },
238
- get hasResults() { return this.results.length + this.reports.length > 0; },
237
+ get hasResults() { return this.results.length > 0; },
239
238
  get fileCount() { return this.shell?.files?.length || 0; },
240
239
  get tabs() {
241
240
  const list = [{ id: 'context', label: 'Контекст', icon: 'carbon:chart-pie', title: 'Статистика сессии' }];
@@ -244,7 +243,7 @@ ODA({ is: 'microchat-dock',
244
243
  if (this.fileCount)
245
244
  list.push({ id: 'files', label: 'Файлы', icon: 'carbon:folder', title: 'Файлы задачи: ваши вложения и созданное агентом', count: this.fileCount });
246
245
  if (this.hasResults)
247
- list.push({ id: 'results', label: 'Результаты', icon: 'carbon:report', title: 'Результаты работы', count: this.results.length + this.reports.length });
246
+ list.push({ id: 'results', label: 'Результаты', icon: 'carbon:report', title: 'Результаты работы', count: this.results.length });
248
247
  return list;
249
248
  },
250
249
  select(key) { this.shell?.selectTab(key); },
@@ -461,26 +460,29 @@ ODA({ is: 'microchat-results',
461
460
  pickedKey: '',
462
461
  pickedAt: 0,
463
462
  get shell() { return findShell(this); },
464
- /** Опубликованные результаты (shell.results / data.results) и отчёты субагентов (стабилизированные без моргания). */
463
+ /** Опубликованные результаты (shell.results / data.results, стабилизированные без моргания). */
465
464
  get items() {
466
465
  const shell = this.shell;
467
- const mapped = shell?.results || (shell?.data?.results || []).map(r => ({
468
- key: 'result:' + r.snapshot,
469
- kind: 'file',
470
- path: r.snapshot,
471
- title: r.title || snapshotName(r.snapshot),
472
- time: r.time,
473
- published: true,
474
- }));
475
- const reports = (shell?.docs || []).filter(d => d.kind === 'text');
476
- const next = [...mapped, ...reports];
466
+ const mapped = shell?.results || (shell?.data?.results || []).filter(r => r?.snapshot).map(r => {
467
+ const real = cleanWorkFilePath(r.snapshot) || r.snapshot;
468
+ return {
469
+ key: 'result:' + r.snapshot,
470
+ kind: 'file',
471
+ path: real,
472
+ snapshot: r.snapshot,
473
+ title: r.title || snapshotName(r.snapshot),
474
+ time: r.time,
475
+ published: true,
476
+ };
477
+ });
478
+ const next = [...mapped];
477
479
  const prev = this._itemsList;
478
480
  if (Array.isArray(prev) && prev.length === next.length && prev.every((d, i) => d === next[i]))
479
481
  return prev;
480
482
  this._itemsList = next;
481
483
  return next;
482
484
  },
483
- /** Выбор: последний сделанный человеком; запрос шелла (новый отчёт, ссылка из ответа) новее — он главнее; иначе — самый новый результат. */
485
+ /** Выбор: последний сделанный человеком; запрос шелла (новый результат) новее — он главнее; иначе — самый новый результат. */
484
486
  get selectedKey() {
485
487
  const fromShell = this.shell?.resultKey;
486
488
  return this.pickedAt >= (this.shell?.resultKeyAt || 0) ? this.pickedKey : fromShell;
@@ -500,7 +502,7 @@ ODA({ is: 'microchat-results',
500
502
  const cache = this._docs ??= new Map();
501
503
  const key = item.key + '|' + item.path;
502
504
  if (!cache.has(key))
503
- cache.set(key, { kind: 'file', path: item.path, title: item.title, time: item.time, published: true });
505
+ cache.set(key, { kind: 'file', path: item.path, snapshot: item.snapshot, title: item.title, time: item.time, published: true });
504
506
  return cache.get(key);
505
507
  },
506
508
  go(i) {
@@ -528,18 +530,13 @@ ODA({ is: 'microchat-files',
528
530
  .tile chat-item { pointer-events: none; width: 100%; }
529
531
  .meta { @apply --horizontal; @apply --muted; align-items: center; gap: 4px; font-size: x-small; padding: 0 4px 2px; }
530
532
  .meta .pub { color: var(--accent-color); font-weight: 600; }
531
- .view { @apply --vertical; flex: 1; min-height: 0; overflow: hidden; }
532
- .back-bar { @apply --horizontal-center; @apply --light; @apply --border-bottom; gap: 8px; padding: 3px 8px; box-sizing: border-box; }
533
- .back { @apply --content; @apply --border; cursor: pointer; padding: 3px 10px; color: inherit; font-size: small; border-radius: 0; flex-shrink: 0; }
534
- .back:hover { @apply --hover; }
535
- .back-bar .file-title { font-size: small; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
536
533
  .empty { @apply --muted; text-align: center; padding: 40px 20px; }
537
534
  </style>
538
- <div class="list" ~if="!cur">
535
+ <div class="list">
539
536
  <div class="empty" ~if="!items.length">Файлов пока нет</div>
540
537
  <div class="head" ~if="items.length">Файлы задачи · {{items.length}}</div>
541
538
  <div class="grid">
542
- <div class="tile" ~for="items" tabindex="0" role="button" :title="'Открыть ' + $for.item.title" @tap="open($for.item)" @keydown="tileKey($event, $for.item)">
539
+ <div class="tile" ~for="items" tabindex="0" role="button" :title="'Открыть ' + ($for.item.real || $for.item.title)" @tap="open($for.item)" @keydown="tileKey($event, $for.item)">
543
540
  <chat-item visible history compact :$file="itemOf($for.item)"></chat-item>
544
541
  <div class="meta">
545
542
  <oda-icon :icon="$for.item.source === 'user' ? 'carbon:user' : 'carbon:bot'" :icon-size="12"></oda-icon>
@@ -549,33 +546,13 @@ ODA({ is: 'microchat-files',
549
546
  </div>
550
547
  </div>
551
548
  </div>
552
- <div class="view" ~if="cur">
553
- <div class="back-bar" no-flex>
554
- <button class="back" @tap="close" title="К списку файлов">← Файлы</button>
555
- <span class="file-title" flex :title="cur.title || cur.real">{{cur.title}}</span>
556
- </div>
557
- <microchat-doc flex :doc="curDoc"></microchat-doc>
558
- </div>
559
549
  `,
560
550
  fmtTime,
561
551
  get shell() { return findShell(this); },
562
552
  get items() { return this.shell?.files || []; },
563
- get cur() { return this.items.find(f => f.key === this.shell?.dockFile) || null; },
564
- /** Один и тот же объект, пока версия файла не изменилась: microchat-doc перезагружает текст при каждой смене doc. */
565
- get curDoc() {
566
- const f = this.cur;
567
- if (!f)
568
- return null;
569
- const cache = this._docs ??= new Map();
570
- const key = f.key + '|' + f.path;
571
- if (!cache.has(key))
572
- cache.set(key, { kind: 'file', path: f.path, title: f.title, time: f.time, published: !!f.published });
573
- return cache.get(key);
574
- },
575
553
  /** Карточка файла — тот же chat-item, что в ленте чата (превью, иконка, имя). Обещание кэшируется, иначе плитка перезагружалась бы на каждой перерисовке. */
576
- itemOf(f) { return fileItemOf(f.path); },
577
- open(f) { this.shell?.openFile(f.key); },
578
- close() { this.shell?.closeFile(); },
554
+ itemOf(f) { return fileItemOf(f.real || f.path); },
555
+ open(f) { this.shell?.openWorkPath(f.real || f.path, f.path); },
579
556
  tileKey(e, f) {
580
557
  if (e.key === 'Enter' || e.key === ' ') {
581
558
  e.preventDefault();
@@ -597,15 +574,35 @@ ODA({ is: 'microchat-doc',
597
574
  .md { padding: 14px 20px; user-select: text; line-height: 1.6; }
598
575
  pre { margin: 0; padding: 12px 16px; font-family: var(--font-mono); font-size: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; user-select: text; }
599
576
  .empty { @apply --muted; padding: 24px; text-align: center; }
577
+ .file-card { @apply --vertical; align-items: center; justify-content: center; gap: 12px; padding: 32px 20px; text-align: center; flex: 1; }
578
+ .file-card .name { font-size: 15px; font-weight: 600; word-break: break-word; max-width: 100%; }
579
+ .file-card .path { @apply --muted; font-family: var(--font-mono); font-size: x-small; word-break: break-all; max-width: 100%; }
580
+ .file-card .actions { @apply --horizontal; flex-wrap: wrap; justify-content: center; gap: 8px; margin-top: 6px; }
581
+ .file-card oda-button { @apply --border; border-radius: var(--radius-m); padding: 6px 14px; font-size: small; }
600
582
  </style>
601
583
  <div class="body" flex vertical>
602
584
  <iframe flex ~if="isPage" :src="url"></iframe>
603
- <oda-office-editor flex ~if="isOffice && officeReady" :$item="officeItem"></oda-office-editor>
585
+ <div class="file-card" ~if="isOffice">
586
+ <oda-icon :icon="officeIcon" :icon-size="40"></oda-icon>
587
+ <div class="name">{{doc?.title || fileName()}}</div>
588
+ <div class="path" :title="realPath || path">{{realPath || path}}</div>
589
+ <div class="actions">
590
+ <oda-button icon="carbon:launch" :icon-size="16" label="Открыть в редакторе" @tap="openForm"></oda-button>
591
+ <oda-button icon="carbon:download" :icon-size="16" label="Скачать" @tap="download"></oda-button>
592
+ </div>
593
+ </div>
604
594
  <div class="img" flex ~if="isImage"><img :src="url"></div>
605
595
  <video flex controls preload="metadata" ~if="isVideo" :src="url"></video>
606
596
  <div class="md" ~if="isMarkdown && text"><oda-markdown-viewer vertical :value="md"></oda-markdown-viewer></div>
607
597
  <pre ~if="!isPage && !isOffice && !isImage && !isVideo && !isMarkdown && !isBinary && text">{{text}}</pre>
608
- <div class="empty" ~if="isBinary">Двоичный файл — скачайте или откройте в приложении</div>
598
+ <div class="file-card" ~if="isBinary">
599
+ <oda-icon icon="carbon:document" :icon-size="40"></oda-icon>
600
+ <div class="name">{{doc?.title || fileName()}}</div>
601
+ <div class="path" :title="realPath || path">{{realPath || path}}</div>
602
+ <div class="actions">
603
+ <oda-button icon="carbon:download" :icon-size="16" label="Скачать" @tap="download"></oda-button>
604
+ </div>
605
+ </div>
609
606
  <div class="empty" ~if="!isPage && !isOffice && !isImage && !isVideo && !isBinary && !text">{{loading ? 'Загрузка…' : 'Нет содержимого'}}</div>
610
607
  </div>
611
608
  `,
@@ -621,9 +618,7 @@ ODA({ is: 'microchat-doc',
621
618
  this.fileText = '';
622
619
  this.bust = Date.now();
623
620
  this.saved = '';
624
- if (this.isOffice)
625
- this.ensureOfficeEditor();
626
- else
621
+ if (!this.isOffice)
627
622
  this.loadText();
628
623
  },
629
624
  },
@@ -631,24 +626,12 @@ ODA({ is: 'microchat-doc',
631
626
  loading: false,
632
627
  bust: 0,
633
628
  saved: '',
634
- officeReady: false,
635
- async ensureOfficeEditor() {
636
- if (!customElements.get('oda-office-editor')) {
637
- try {
638
- await import('/$server/$folder/$file/$office/handlers/pages/form/file/$handler/file.js');
639
- }
640
- catch (e) {
641
- console.warn('[microchat-doc] office import:', e);
642
- }
643
- }
644
- this.officeReady = !!customElements.get('oda-office-editor');
645
- },
646
629
  get isFile() { return this.doc?.kind === 'file'; },
647
630
  get path() { return this.isFile ? this.doc.path : ''; },
648
631
  get realPath() { return this.isFile ? (cleanWorkFilePath(this.path) || this.path) : ''; },
649
632
  get ext() { return this.isFile ? (extOf(this.realPath) || extOf(this.path)) : 'md'; },
650
633
  get isOffice() { return OFFICE.includes(this.ext); },
651
- get officeItem() { return this.isOffice && this.realPath ? fileItemOf(this.realPath) : null; },
634
+ get officeIcon() { return extIcon(this.realPath || this.path); },
652
635
  get isBinary() { return BINARY.includes(this.ext); },
653
636
  get isImage() { return IMAGE.includes(this.ext); },
654
637
  get isPage() { return PAGE.includes(this.ext); },
@@ -667,7 +650,7 @@ ODA({ is: 'microchat-doc',
667
650
  get md() { return linkifyWork(this.text, this.doc?.artifacts || new Map()); },
668
651
  get subtitle() {
669
652
  if (this.isFile)
670
- return ['Снимок файла', this.doc?.published ? 'показан в общей ленте' : '', fmtTime(this.doc?.time)].filter(Boolean).join(' · ');
653
+ return ['Конечная версия', this.doc?.published ? 'показана в общей ленте' : '', fmtTime(this.doc?.time)].filter(Boolean).join(' · ');
671
654
  return [this.doc?.subtitle, fmtTime(this.doc?.time)].filter(Boolean).join(' · ');
672
655
  },
673
656
  async loadText() {
@@ -675,7 +658,9 @@ ODA({ is: 'microchat-doc',
675
658
  return;
676
659
  this.loading = true;
677
660
  try {
678
- const item = await WORK.get_item(this.path);
661
+ let item = await WORK.get_item(this.path);
662
+ if ((!item || Array.isArray(item)) && this.doc?.snapshot && this.doc.snapshot !== this.path)
663
+ item = await WORK.get_item(this.doc.snapshot);
679
664
  const raw = await item?.load?.();
680
665
  this.fileText = typeof raw === 'string' ? raw : (raw == null ? '' : JSON.stringify(raw, null, 2));
681
666
  }
@@ -688,9 +673,7 @@ ODA({ is: 'microchat-doc',
688
673
  },
689
674
  reload() {
690
675
  this.bust = Date.now();
691
- if (this.isOffice)
692
- this.$?.('oda-office-editor')?.loadOfficeItem?.(this.officeItem);
693
- else
676
+ if (!this.isOffice)
694
677
  this.loadText();
695
678
  },
696
679
  copy() { copyText(this.text); },
@@ -701,7 +684,7 @@ ODA({ is: 'microchat-doc',
701
684
  download() {
702
685
  if (this.isFile && (this.isImage || this.isPage || this.isVideo || this.isOffice || !this.text)) {
703
686
  const a = document.createElement('a');
704
- a.href = fileUrl(this.path);
687
+ a.href = fileUrl(this.realPath || this.path);
705
688
  a.download = this.fileName();
706
689
  a.click();
707
690
  return;
@@ -724,21 +707,21 @@ ODA({ is: 'microchat-doc',
724
707
  if (!this.isFile)
725
708
  return;
726
709
  const targetPath = this.realPath || this.path;
710
+ const shell = findShell(this);
711
+ if (shell?.openWorkPath) {
712
+ await shell.openWorkPath(targetPath, this.doc?.snapshot || this.path);
713
+ return;
714
+ }
727
715
  const exec = window.top?.execute || window.execute;
728
- if (typeof exec === 'function') {
729
- let item = await WORK.get_item(targetPath);
716
+ let item = await WORK.get_item(targetPath).catch(() => null);
717
+ if (Array.isArray(item))
718
+ item = item.at(-1) || null;
719
+ if (!item && this.doc?.snapshot && this.doc.snapshot !== targetPath) {
720
+ item = await WORK.get_item(this.doc.snapshot).catch(() => null);
730
721
  if (Array.isArray(item))
731
722
  item = item.at(-1) || null;
732
- if (!item && targetPath !== this.path) {
733
- item = await WORK.get_item(this.path);
734
- if (Array.isArray(item))
735
- item = item.at(-1) || null;
736
- }
737
- if (item) {
738
- await exec(item);
739
- return;
740
- }
741
723
  }
742
- window.open(workHref(targetPath), '_blank');
724
+ if (item && typeof exec === 'function')
725
+ await exec(item);
743
726
  },
744
727
  });
@@ -101,26 +101,6 @@ export function collectDocs(items, published) {
101
101
  if (Array.isArray(t.items))
102
102
  walkFiles(t.items, true);
103
103
  }
104
- const ansText = String(it.content || '').trim();
105
- if (!nested && !it.error && !it.interrupted && !it.stopped && (it.durationMs || it.finish === 'stop') && ansText.length >= 80 && !(ansText.length < 180 && /\?\s*$/.test(ansText))) {
106
- const isStructured = ansText.length >= 160
107
- || /^\s{0,3}#{1,4}\s+\S/m.test(ansText)
108
- || /^\s*\|.+\|\s*$/m.test(ansText)
109
- || /```|~~~/.test(ansText)
110
- || /(?:^|\n)\s*(?:[-*•]|\d+[.)])\s+.+\n\s*(?:[-*•]|\d+[.)])\s+/m.test(ansText);
111
- if (isStructured) {
112
- put({
113
- key: 'answer:' + it.id,
114
- kind: 'text',
115
- text: ansText,
116
- title: plainTitle(ansText),
117
- icon: 'carbon:report',
118
- time: it.time,
119
- source: it.id,
120
- subtitle: 'ответ агента',
121
- });
122
- }
123
- }
124
104
  }
125
105
  };
126
106
  walkFiles(items, false);
@@ -8,6 +8,10 @@ export const TOOL_META = {
8
8
  append: { label: 'Дополнение', icon: 'carbon:document-add' },
9
9
  edit: { label: 'Правка', icon: 'carbon:edit' },
10
10
  create_class: { label: 'Новый класс', icon: 'carbon:tree-view-alt' },
11
+ update_class: { label: 'Схема класса', icon: 'carbon:settings-adjust' },
12
+ inspect_class_tree: { label: 'Аудит структуры', icon: 'carbon:flow-modeler' },
13
+ move_class: { label: 'Перенос класса', icon: 'carbon:move' },
14
+ delete_class: { label: 'Удаление класса', icon: 'carbon:trash-can' },
11
15
  schema: { label: 'Методы', icon: 'carbon:api' },
12
16
  call: { label: 'Вызов', icon: 'carbon:function' },
13
17
  logs: { label: 'Журнал', icon: 'carbon:catalog' },
@@ -715,7 +715,7 @@ ODA({
715
715
  prompt: `Покажи схему операции «${lbl}» (${ctx.path}), её проводки и последние зарегистрированные документы.`,
716
716
  };
717
717
  }
718
- if (t === '$structure' || t === '$base') {
718
+ if (t === '$structure' || t === '$base' || t === '$server') {
719
719
  return {
720
720
  icon: 'icons:supervisor-account',
721
721
  label: `Проверить роли BOSS, рабочие места и ленту «${lbl}»`,
@@ -745,7 +745,8 @@ ODA({is: 'oda-tree-node',
745
745
  if (!it || isLinkNode(it) || ('isPlace' in Object(it) && it.isPlace))
746
746
  return false;
747
747
  const t = it.type;
748
- return t === '$base' || t === '$structure';
748
+ // $server (корень WORK) — тоже наследник $structure: на нём тоже показываем BOSS.
749
+ return t === '$base' || t === '$structure' || t === '$server';
749
750
  },
750
751
  get isModule() {
751
752
  const it = this.$item;