odant-work 1.0.27 → 1.0.29

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.
@@ -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);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odant-work",
3
- "version": "1.0.27",
3
+ "version": "1.0.29",
4
4
  "description": "ODANT-WORK — платформа цифровой организации (встроенная система учёта, документооборот, управление процессами и приватный мультимодальный ИИ)",
5
5
  "type": "module",
6
6
  "main": "sources/work.js",
@@ -1,6 +1,15 @@
1
1
  # Прогресс: sources/data
2
2
 
3
3
  ## Последние изменения
4
+ - [12:20, 16.11] Форма задачи (`.task`): чистые «Результаты» только по `publish`, плоский список «Файлы» со штатным открытием и рабочие ссылки (`$server/$folder/$file/$task/handlers/pages/form/file/$handler/{file.js,readme.md,ui/dock.js,ui/docs.js}`, `sources/modules/agent/{index.js,tools/docs.js,tools/meta.js,tools/work/fs.js}`, `tests/{task-docs,agent-core}.test.js`, `tests/ui/task-dock.html`, `odant-work@1.0.29`):
5
+ - **Вкладка «Результаты» без шума переписки:** из `collectDocs()` убрано превращение обычных ответов и вопросов ассистента (`answer:*`) в документы, а вкладка «Результаты» (`microchat-dock`, `microchat-results`, `_noticeDocs`) теперь показывает **только** явно опубликованные через `publish` результаты (`data.results`) и скрыта, пока результатов нет.
6
+ - **Конечная версия файла и карточка офисных форматов:** `results` и `<microchat-doc>` используют конечный живой путь файла (`realPathOfSnapshot(r.snapshot)` с откатом на снимок `r.snapshot` при чтении); для офисных файлов (`.pptx`, `.docx`, `.xlsx` и др.) в узкой панели показывается карточка результата с кнопками «Открыть в редакторе» и «Скачать» вместо пустого встроенного редактора.
7
+ - **Плоский список «Файлы» со штатным открытием:** из `microchat-files` и `file.js` убрано «углубление» внутрь боковой панели (`← Файлы` / `<microchat-doc>`); клик по любой плитке открывает файл штатно в форме WORK (`openWorkPath`), оставляя список файлов на месте.
8
+ - **Рабочие ссылки без ложных путей:** `savedNote` (`docs.js`), `write` (`fs.js`) и `formatResults` (`meta.js`) не подсовывают модели несуществующий запрошенный путь при сохранении артефакта в папку задачи `.task/` (дополнительно закреплено в `ENV_GUIDE`); в `openWorkPath` при отсутствии элемента показывается `toast` вместо открытия пустой вкладки браузера с `not found`.
9
+ - [09:59, 16.11] Защита сервера от падения при сетевых обрывах (`UND_ERR_RES_CONTENT_LENGTH_MISMATCH` / `terminated`) и авто-докачка после рестарта (`sources/modules/trainer/{downloader,huggingface,index}.js`, `sources/host/process-guard.js`, `sources/work.js`, `tests/trainer-downloader.test.js`, `odant-work@1.0.28`):
10
+ - **Устранена причина краха `TypeError: terminated` (`makeIdleChunkReader.close`, `guardBody`, `discardBody`):** при обрыве HTTP/2-потока (`UND_ERR_RES_CONTENT_LENGTH_MISMATCH`) `iterator.return()` и `body.cancel()` на упавшем потоке возвращают отклонённый промис, который не ловился в синхронном `try/catch` и завершал процесс Node по `unhandledRejection`. Теперь отказы закрытия потоков гасятся, на все тела ответов вешается страхующий `'error'`-слушатель (`guardBody`), а `reader.close()` выполняется в `finally` и при нормальном завершении сегмента (снимает зависшие сокеты из пула).
11
+ - **Глобальная страховка процесса (`sources/host/process-guard.js`):** на старте сервера (`sources/work.js`) регистрируются обработчики `unhandledRejection` и `uncaughtException`; сетевые и потоковые сбои (`terminated`, `UND_ERR_*`, `ERR_HTTP2_*`, `ECONNRESET`, `ETIMEDOUT`) логируются в `.data/server-errors.log` без падения сервера, а `isRetryableDownloadError` проверяет также цепочку `err.cause` и коды несовпадения `content-length`.
12
+ - **Авто-докачка прерванных загрузок (`resumeInterruptedDownloads`):** при запуске сервера загрузки со статусом `downloading` в `download-state.json` автоматически возобновляются с сохранённых диапазонов (`WORK_RESUME_DOWNLOADS=0` — отключить); ручные паузы (`paused`) сохраняются.
4
13
  - [18:07, 15.11] Честный ETA загрузки моделей и сторож зависших соединений (`sources/modules/trainer/{huggingface,downloader,index}.js`, `MODELS/$ai/$folder/$class/$provider/handlers/pages/form/trainer/$handler/trainer.js`, `tests/trainer-downloader.test.js`, `odant-work@1.0.27`):
5
14
  - **ETA считается по устойчивой средней скорости (`computeDownloadEta`):** раньше «осталось N» делило остаток на мгновенную скорость за последние 5 секунд, поэтому при короткой просадке канала (0,22 МБ/с вместо средних 4,5 МБ/с) показывало ~318 ч при уже скачанных 16 %. Теперь базой служит средняя скорость с начала загрузки, накопленная по «активному» времени передачи и сохраняемая в `download-state.json` (`stats.baseBytes` / `stats.activeMs`), — она переживает паузы и перезапуски сервера; мгновенный замер остаётся только запасным вариантом на первых секундах.
6
15
  - **Средняя скорость видна в карточке** рядом с текущей (`1,2 МБ/с · средняя 4,5 МБ/с · ~16 ч`), низкая скорость и подсказки оцениваются тоже по средней, а не по секундному дрожанию.
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Глобальная страховка Node-процесса WORK от падения из-за фоновых сетевых
3
+ * отказов (например `TypeError: terminated` / `UND_ERR_RES_CONTENT_LENGTH_MISMATCH`
4
+ * при обрыве стримов Hugging Face) и непредвиденных асинхронных исключений.
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+
9
+ const GUARD_SYMBOL = Symbol.for('odant.work.processGuard');
10
+ const MAX_LOG_BYTES = 2 * 1024 * 1024;
11
+
12
+ const TRANSIENT_NET_RE = /ECONNRESET|ETIMEDOUT|EPIPE|EAI_AGAIN|ENOTFOUND|ECONNREFUSED|EHOSTUNREACH|ENETUNREACH|UND_ERR_|ERR_HTTP2_|ResponseContentLengthMismatch|content[- ]length|length does not match|terminated|socket hang up|Premature close|fetch failed|aborted/i;
13
+
14
+ /**
15
+ * Проверить ошибку (включая цепочку `err.cause`), является ли она
16
+ * временным сетевым / HTTP/2 / потоковым сбоем.
17
+ */
18
+ export function isTransientNetworkError(err) {
19
+ let cur = err;
20
+ for (let depth = 0; cur && depth < 5; depth++) {
21
+ if (typeof cur === 'string') {
22
+ if (TRANSIENT_NET_RE.test(cur))
23
+ return true;
24
+ break;
25
+ }
26
+ const hay = [
27
+ cur.code,
28
+ cur.name,
29
+ cur.message,
30
+ cur.http2ErrorCode != null ? `http2ErrorCode=${cur.http2ErrorCode}` : '',
31
+ ].filter(Boolean).join(' ');
32
+ if (TRANSIENT_NET_RE.test(hay))
33
+ return true;
34
+ cur = cur.cause;
35
+ }
36
+ return false;
37
+ }
38
+
39
+ function formatErrorEntry(kind, err) {
40
+ const ts = new Date().toISOString();
41
+ const parts = [`[${ts}] [${kind}]`];
42
+ if (err instanceof Error) {
43
+ const meta = err.code ? ` [code=${err.code}]` : '';
44
+ parts.push((err.stack || `${err.name}: ${err.message}`) + meta);
45
+ let cause = err.cause;
46
+ for (let i = 1; cause && i <= 3; i++) {
47
+ const cMeta = cause.code ? ` [code=${cause.code}]` : '';
48
+ parts.push(` cause(${i}): ${cause.stack || cause.message || String(cause)}${cMeta}`);
49
+ cause = cause.cause;
50
+ }
51
+ }
52
+ else {
53
+ parts.push(String(err));
54
+ }
55
+ return parts.join('\n') + '\n';
56
+ }
57
+
58
+ function appendLogSafe(logFile, entry) {
59
+ if (!logFile)
60
+ return;
61
+ try {
62
+ fs.mkdirSync(path.dirname(logFile), { recursive: true });
63
+ try {
64
+ const st = fs.statSync(logFile);
65
+ if (st.size > MAX_LOG_BYTES) {
66
+ const bak = `${logFile}.1`;
67
+ try { fs.rmSync(bak, { force: true }); } catch { /* ignore */ }
68
+ fs.renameSync(logFile, bak);
69
+ }
70
+ }
71
+ catch { /* файла ещё нет */ }
72
+ fs.appendFileSync(logFile, entry, 'utf-8');
73
+ }
74
+ catch { /* не падаем из-за логгера */ }
75
+ }
76
+
77
+ /**
78
+ * Установить глобальные обработчики `unhandledRejection` и `uncaughtException`.
79
+ * Идемпотентно для переданного `target` (по умолчанию `process`).
80
+ */
81
+ export function installProcessGuards({
82
+ rootDir = process.cwd(),
83
+ logFile = path.join(rootDir, '.data', 'server-errors.log'),
84
+ target = process,
85
+ onError = null,
86
+ } = {}) {
87
+ if (target[GUARD_SYMBOL])
88
+ return target[GUARD_SYMBOL];
89
+
90
+ const handle = (kind, err) => {
91
+ const transient = isTransientNetworkError(err);
92
+ const msg = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
93
+ if (transient) {
94
+ console.warn(`[process-guard] ${kind}: временный сетевой сбой (сервер продолжает работу): ${msg}`);
95
+ }
96
+ else {
97
+ console.error(`[process-guard] ${kind}: неперехваченная ошибка (сервер продолжает работу):`, err);
98
+ }
99
+ appendLogSafe(logFile, formatErrorEntry(transient ? `${kind}:net` : kind, err));
100
+ try { onError?.({ kind, transient, error: err }); } catch { /* ignore */ }
101
+ };
102
+
103
+ const onRejection = (reason) => handle('unhandledRejection', reason);
104
+ const onException = (err) => handle('uncaughtException', err);
105
+
106
+ target.on('unhandledRejection', onRejection);
107
+ target.on('uncaughtException', onException);
108
+
109
+ const uninstall = () => {
110
+ target.off?.('unhandledRejection', onRejection);
111
+ target.off?.('uncaughtException', onException);
112
+ delete target[GUARD_SYMBOL];
113
+ };
114
+ target[GUARD_SYMBOL] = uninstall;
115
+ return uninstall;
116
+ }
@@ -318,7 +318,7 @@ WORK — система управления деятельностью, где
318
318
  - «Доступ запрещён» — не обходи (другими путями, ролями, копиями): объясни пользователю и предложи escalate — запрос ответственному.
319
319
  - Нет нужного инструмента в твоём списке (например os_*/net_*/shell без роли ADMIN) — так и скажи сразу: что нужно и какая роль требуется. Не ищи инструмент в дереве (read/find/schema/call его не создадут — это инструменты агента, а не методы дерева) и не перепоручай такую работу субагенту: у него та же роль и те же ограничения.
320
320
  - Устойчивые факты, решения и предпочтения, которые пригодятся в следующих задачах, сохраняй memory (remember); устаревшее — forget.
321
- - Отвечай по-русски, по делу, markdown; ссылки на элементы — WORK-путями. В конце работы — краткий итог: что сделано, где результат.
321
+ - Отвечай по-русски, по делу, markdown; ссылки на элементы — только фактическими WORK-путями из результатов инструментов (если инструмент поместил файл в папку задачи .task/, указывай именно возвращённый фактический путь, а не запрошенный). В конце работы — краткий итог: что сделано, где результат.
322
322
  - Удачную повторяемую работу предложи сохранить навыком (save_skill).
323
323
  # Внешние сервисы (аккаунты пользователя)
324
324
  - Ты можешь действовать в интернет-сервисах через их API: календари, почта, диски, задачи, CRM, GitHub и любой API по токену (http_request).
@@ -387,7 +387,7 @@ export function slidesToPptxData(slides, { title: deckTitle, date } = {}) {
387
387
  }
388
388
  export function savedNote(requested, real) {
389
389
  return real && real !== requested
390
- ? 'сохранено ' + real + ' (запрошено ' + requested + '; дальше используй фактический путь ' + real + ')'
390
+ ? 'сохранено ' + real + ' (помещено в папку задачи — в ссылках и дальнейших вызовах используй только этот путь)'
391
391
  : 'сохранено ' + (real || requested);
392
392
  }
393
393
 
@@ -74,7 +74,11 @@ function formatResults(results) {
74
74
  const list = Array.isArray(results) ? results : [];
75
75
  if (!list.length)
76
76
  return 'результаты не отмечены';
77
- return list.map((r, i) => (i + 1) + '. ' + (r.title || r.snapshot) + '\n ' + r.snapshot).join('\n');
77
+ return list.map((r, i) => {
78
+ const snap = String(r.snapshot || '');
79
+ const real = snap.replace(/\/\.([^/]+)\/history\/\d{4}-\d{2}-\d{2}\/[^/]+$/, '/$1');
80
+ return (i + 1) + '. ' + (r.title || real) + '\n путь: ' + real + (real !== snap ? '\n снимок: ' + snap : '');
81
+ }).join('\n');
78
82
  }
79
83
 
80
84
  /** Продолжимый ребёнок доступен только из своей родительской задачи под тем же пользователем. */
@@ -180,7 +180,7 @@ export const write = {
180
180
  await trackWrite(ctx, real, log, pre);
181
181
  const req = absPath(args.path, ctx);
182
182
  return (before == null ? 'создан ' : 'перезаписан ') + real + ' (' + String(args.content).length + ' символов)'
183
- + (real !== req ? '; запрошено ' + req + ' — дальше используй фактический путь ' + real : '');
183
+ + (real !== req ? ' (помещён в папку задачи — в ссылках и дальнейших вызовах используй только этот путь)' : '');
184
184
  },
185
185
  };
186
186