@itphx/synth-backend 0.12.4 → 0.13.4

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.
package/dist/app/deps.js CHANGED
@@ -4,10 +4,19 @@
4
4
  // Вынесено из `app.ts` (ADR-095, шаг 4b) — «вынос по швам», без изменения поведения.
5
5
  import { mkdir } from 'node:fs/promises';
6
6
  import { join } from 'node:path';
7
- import { ensureDataDir, parsePrincipalId, resolveDefaultWorkspace, resolveSecretKey, resolveStorageBackend, resolvePostgresConfig, resolvePostgresPassword, resolveDegradedMode, resolveStorageFallbackDir, resolveExecutionConfig, readTlsRuntimeSettings, SYNTH_VERSION, } from '@itphx/synth-shared';
8
- import { SessionManager, EventBus, QueueProcessorManager, ContextBuilder, ContextOptimizer, ChatOrchestrator, enqueueUserMessage, createToolRegistry, createAgentRegistry, McpManager, DEFAULT_AGENT_ID, registerStoredAgents, AuditLogger, mergeLlmGatewayConfig, mergeSecurityConfig, mergeEventsConfig, mergeDecisionConfig, mergePluginsConfig,
7
+ import { ensureDataDir, mergeModelCompatibility, parsePrincipalId, resolveDefaultWorkspace, resolveSecretKey, resolveStorageBackend, resolvePostgresConfig, resolvePostgresPassword, resolveDegradedMode, resolveStorageFallbackDir, resolveExecutionConfig, readTlsRuntimeSettings, SYNTH_VERSION, generateId, makeTextPart, nowISO, MessageRole, } from '@itphx/synth-shared';
8
+ import { DEFAULT_TOOL_OUTPUT_MAX_BYTES, DEFAULT_TOOL_OUTPUT_MAX_LINES } from '@itphx/synth-shared/config';
9
+ import { SessionManager, EventBus, QueueProcessorManager, ContextBuilder, ContextOptimizer, ChatOrchestrator, enqueueUserMessage, requeueMessages, createToolRegistry, createAgentRegistry, McpManager, DEFAULT_AGENT_ID, registerStoredAgents, migrateLegacyStoredAgents, AuditLogger, mergeLlmGatewayConfig, mergeSecurityConfig, mergeEventsConfig, mergeDecisionConfig, mergePluginsConfig,
9
10
  // ADR-115: живое состояние runtime-настроек вложений (`/settings/attachments`).
10
- createLiveAttachmentsSettings, createEgressPolicyResolver, createEgressLogSink, configureEgressRuntime, startEgressLogPruner,
11
+ createLiveAttachmentsSettings,
12
+ // Политика контекстного окна (`/settings/context-window`).
13
+ createLiveContextWindowPolicy,
14
+ // Бюджет промпта саб-агента (`/settings/agents-limits`).
15
+ createLiveSubagentMaxInputTokens,
16
+ // Дефолты оптимизации контекста новых сессий (`/settings/context-defaults`).
17
+ createLiveContextDefaults,
18
+ // Instance-wide лимиты заметок сессии (`/settings/sticky-notes`).
19
+ createLiveStickyNotesLimits, createEgressPolicyResolver, createEgressLogSink, configureEgressRuntime, startEgressLogPruner,
11
20
  // ADR-105 (Ф3): источник access-токена для MCP-коннекторов + OAuth-сервис.
12
21
  OAuthCredentialService, OAuthProviderRegistry, registerOAuthProvidersFromConfig, createRepositoryCredentialSource, SkillService, resolveProjectSkillSeed, CommandService, detectRuntimeDeps, syncProvidersFromEnv,
13
22
  // ADR-115 × ADR-101: доступность `ffmpeg` — обработчик вложения aux-моделью шага.
@@ -20,6 +29,11 @@ BackgroundRunService, startBackgroundRunPruner, createBackgroundParentNotifier,
20
29
  ProcessService, startProcessLogPruner,
21
30
  // ADR-115: GC осиротевших вложений сообщений.
22
31
  startAttachmentPruner,
32
+ // ADR-115 × ADR-077: медиа-раннер (ffmpeg inline/remote) и серверные миниатюры.
33
+ createMediaRunner, ThumbnailService,
34
+ // ADR-115 × ADR-077: уборка временных каталогов медиа-раннера
35
+ // (`{workspacesRoot}/.synth-media/*`) — после жёсткого kill они остаются.
36
+ startMediaTempPruner,
23
37
  // ADR-114: сервис worktree'ов (per-session рабочий каталог) + публикация
24
38
  // `worktree.updated` в каналы сессий проекта.
25
39
  WorktreeService, publishWorktreeUpdated, startWorktreeSweeper, WebhookService, startWebhookDeliveryPruner, AnalyticsRecorder, attachAnalyticsActivityHooks, startAnalyticsRollupPruner, sessionAxes, createStorageContextAsync, initTlsTrust, applyStartupProxyConfig, attachBusMetrics, startSessionMetrics, startStorageMetrics,
@@ -44,14 +58,21 @@ PipelineArtifactStore, PipelineEngine,
44
58
  // для HTTP-роута пайплайнов и встроенных тулов агента.
45
59
  PipelineRunControl, createToolStepExecutor, createScriptStepExecutor, createHumanStepExecutor, createAgentStepExecutor, createPipelineExitHandler, createPipelineMetrics,
46
60
  // ADR-115 × ADR-101: вложения прогона — derive для text-only модели шага.
47
- createPipelineAttachmentDerive, ensureBuiltinPipelines, toCoreProviderConfig, ProviderFactory,
61
+ createPipelineAttachmentDerive, ensureBuiltinPipelines,
62
+ // ADR-101 §4 × `AgentDefinition`: провайдер агентского шага (код общий с core).
63
+ resolvePipelineStepProvider, toCoreProviderConfig, ProviderFactory,
48
64
  // ADR-077: порт исполнения команд (inline/remote).
49
65
  createExecutionPortForConfig,
50
66
  // ADR-090 (Ф3а) / §5, §10 (Ф5б-1): общий реестр
51
67
  // блоков промпта (композер + фасад плагинов) и рантайм плагинов.
52
- PromptBlockRegistry, PluginRuntime, PluginProcessManager, PluginFacadeError, createInlinePluginLoader, createRemotePluginLoader, resolvePluginLayout, } from '@itphx/synth-core';
68
+ PromptBlockRegistry, PluginRuntime, PluginProcessManager, PluginFacadeError, createInlinePluginLoader, createRemotePluginLoader, resolvePluginLayout, serializeMessage, } from '@itphx/synth-core';
53
69
  import { EventHub } from '../events/hub.js';
54
70
  import { seedDebugTestUsers } from './bootstrap.js';
71
+ /**
72
+ * Fallback-текст info-блока автопродолжения после рестарта: content — en-текст
73
+ * по контракту ADR-041 (LLM-контекст), UI локализует по `metadata.i18n`.
74
+ */
75
+ const RESTART_RESUMED_TEXT = 'The turn was interrupted by an instance restart and continued automatically';
55
76
  /**
56
77
  * ADR-096 (W2.4): единая точка сборки слоя хранения backend — `app.ts` строит
57
78
  * её до `auth` (реестр `serviceKeys` нужен резолверу ключа, `mcpRegistry` —
@@ -146,12 +167,26 @@ executionConfig) {
146
167
  };
147
168
  // ADR-030: ядровая шина хуков — общий инстанс для SessionManager и оркестратора.
148
169
  const hooks = new HookBus();
170
+ // Дефолты оптимизации контекста для новых сессий (`context.defaults`):
171
+ // runtime-патч поверх config.yaml; применяются без рестарта.
172
+ const contextDefaultsSettings = createLiveContextDefaults({
173
+ config: config.synth.context?.defaults,
174
+ runtime: await settingsStore.getContextDefaults(),
175
+ });
176
+ // Instance-wide лимиты заметок сессии (`context.stickyNotes`): runtime-патч
177
+ // поверх config.yaml; применятся без рестарта (резолвер читается на операцию).
178
+ const stickyNotesLimitsSettings = createLiveStickyNotesLimits({
179
+ config: config.synth.context?.stickyNotes,
180
+ runtime: await settingsStore.getStickyNotesLimits(),
181
+ });
149
182
  // ADR-102: сборщик роллапов аналитики (write-path) — только через порт слоя
150
183
  // хранения; в деградации выключен (не пишем домен в файловый фоллбек).
151
184
  const analytics = storageDegraded ? undefined : new AnalyticsRecorder({ repo: analyticsRollups });
152
185
  const sessionManager = new SessionManager(fileStore, {
153
186
  projectStore,
154
187
  hooks,
188
+ // Дефолты оптимизации контекста новых сессий (`context.defaults` + runtime).
189
+ contextDefaults: () => contextDefaultsSettings.getDefaults(),
155
190
  // ADR-102: точка персиста сообщений (`messages_assistant`/`messages_tool`).
156
191
  analytics,
157
192
  // ADR-071 §2.4 / ADR-046 §4.5: системные дефолты для сессий без проекта.
@@ -218,6 +253,18 @@ executionConfig) {
218
253
  config: config.synth.attachments,
219
254
  runtime: await settingsStore.getAttachments(),
220
255
  });
256
+ // Политика ограничения контекстного окна (`context.windowPolicy`):
257
+ // приоритет env > runtime > config.yaml > default; применяется сразу.
258
+ const contextWindowSettings = createLiveContextWindowPolicy({
259
+ config: config.synth.context?.windowPolicy,
260
+ runtime: await settingsStore.getContextWindowPolicy(),
261
+ });
262
+ // Предохранитель объёма промпта саб-агента (`agents.subagentMaxInputTokens`):
263
+ // приоритет env > runtime > config.yaml > 0; читается при сборке `task` extra.
264
+ const subagentMaxInputTokensSettings = createLiveSubagentMaxInputTokens({
265
+ config: config.synth.agents.subagentMaxInputTokens,
266
+ runtime: await settingsStore.getSubagentMaxInputTokens(),
267
+ });
221
268
  const stopEgressLogPruner = storageDegraded || !egressLogConfig.enabled
222
269
  ? () => { }
223
270
  : startEgressLogPruner(egressRequests, { getRetentionDays: () => egressLogConfig.retentionDays });
@@ -296,15 +343,70 @@ executionConfig) {
296
343
  // создаётся лениво, при первом вызове колбэка (он приходит только из
297
344
  // фонового прогона, т.е. уже после старта).
298
345
  let backgroundNotifier = null;
346
+ /**
347
+ * ADR-111/ADR-113: идёт ли ход в сессии (одна функция на нотификатор и
348
+ * матрицу ретрансляции результата из дочерней сессии).
349
+ */
350
+ const isBackgroundTurnActive = async (sid) => {
351
+ if (queueManager.isRunning(sid))
352
+ return true;
353
+ const current = await sessionManager.getSession(sid);
354
+ const stream = current?.currentStream;
355
+ if (!stream || stream.cancelled)
356
+ return false;
357
+ return current?.status?.cancelRequested !== true;
358
+ };
359
+ /**
360
+ * Корень дерева сессий (обход `parentId` вверх, глубина ≤ 5, защита от
361
+ * циклов). Ошибка/нет сессии → `null` (fail-safe: доставим владельцу).
362
+ */
363
+ const resolveRootSession = async (sessionId) => {
364
+ let current = await sessionManager.getSession(sessionId);
365
+ if (!current)
366
+ return null;
367
+ const seen = new Set([current.id]);
368
+ for (let depth = 0; depth < 5 && current.parentId; depth += 1) {
369
+ if (seen.has(current.parentId))
370
+ break;
371
+ const parent = await sessionManager.getSession(current.parentId);
372
+ if (!parent)
373
+ break;
374
+ seen.add(parent.id);
375
+ current = parent;
376
+ }
377
+ return { id: current.id, ...(current.title ? { title: current.title } : {}) };
378
+ };
299
379
  const notifyBackgroundParent = async (sessionId, message) => {
300
380
  backgroundNotifier ??= createBackgroundParentNotifier({
301
381
  sessionManager,
302
382
  eventBus,
303
383
  processorManager: queueManager,
304
384
  processMessage,
385
+ isTurnActive: isBackgroundTurnActive,
305
386
  });
306
387
  await backgroundNotifier(sessionId, message);
307
388
  };
389
+ /**
390
+ * ADR-111/ADR-113 × ADR-104: остаток steer-очереди в конце хода возвращается
391
+ * в обычную очередь (`autostart` — нормальное завершение; после «Стопа» — нет).
392
+ */
393
+ /**
394
+ * ADR-104 × ADR-111/ADR-113: остаток steer-очереди в конце хода не теряется —
395
+ * **все** сообщения возвращаются в `pendingMessages`; `autostart` поднимает
396
+ * ход (нормальное завершение), при «Стопе» — нет.
397
+ * `processMessage` объявлен ниже — вызов происходит уже в рантайме.
398
+ */
399
+ const requeueSteerMessages = async (sessionId, messages, autostart) => {
400
+ return requeueMessages({
401
+ sessionManager,
402
+ eventBus,
403
+ sessionId,
404
+ messages,
405
+ ...(autostart
406
+ ? { autostart: { processorManager: queueManager, processMessage, eventBus } }
407
+ : {}),
408
+ });
409
+ };
308
410
  const backgroundService = storageDegraded
309
411
  ? undefined
310
412
  : new BackgroundRunService({
@@ -322,6 +424,13 @@ executionConfig) {
322
424
  // системное (автор `Subagent`/`Process`), а не пользовательский ввод;
323
425
  // секреты в исходящих LLM-запросах обфусцирует сам Gateway.
324
426
  onNotifyParent: notifyBackgroundParent,
427
+ // ADR-111/ADR-113: матрица доставки — прогон из дочерней сессии без
428
+ // активного хода ретранслируется в корень (дочернюю не будим).
429
+ isTurnActive: isBackgroundTurnActive,
430
+ resolveRootSessionId: resolveRootSession,
431
+ // «Стоп» сессии останавливает и живые прогоны детей (ADR-111 §detach,
432
+ // решение 2026-10-28): дерево обходит сам сервис (глубина ≤ 5).
433
+ getChildSessionIds: async (parentId) => (await sessionManager.getChildren(parentId, { light: true })).map((s) => s.id),
325
434
  });
326
435
  // Старт: прогоны прошлого процесса не пережили рестарт (хэндлы отмены — в
327
436
  // памяти) — помечаем их `orphaned`. Best-effort: ошибка не роняет старт.
@@ -333,6 +442,133 @@ executionConfig) {
333
442
  console.warn(`[background] восстановление фоновых прогонов не удалось: ${err instanceof Error ? err.message : String(err)}`);
334
443
  }
335
444
  }
445
+ /**
446
+ * Info-блок «ход продолжен после рестарта»: пишется в историю (роль INFO — в
447
+ * LLM-контекст не попадает) и публикуется `message.added`. Дубль для того же
448
+ * `stream_id` не пишется: recovery и автоскан очередей могут указывать на одно
449
+ * и то же сообщение.
450
+ */
451
+ const addRestartResumedNotice = async (sessionId, streamId) => {
452
+ const session = await sessionManager.getSession(sessionId);
453
+ const alreadyNotified = session?.messages.some((m) => m.metadata?.type === 'restart_resumed'
454
+ && m.metadata?.stream_id === streamId);
455
+ if (alreadyNotified)
456
+ return;
457
+ const info = {
458
+ id: generateId(),
459
+ role: MessageRole.INFO,
460
+ seq: 0,
461
+ origin: 'local',
462
+ parts: [makeTextPart(RESTART_RESUMED_TEXT)],
463
+ content: RESTART_RESUMED_TEXT,
464
+ createdAt: nowISO(),
465
+ disabled: false,
466
+ pinned: false,
467
+ hidden: false,
468
+ metadata: {
469
+ type: 'restart_resumed',
470
+ ...(streamId ? { stream_id: streamId } : {}),
471
+ i18n: { key: 'chat.notice.restartResumedText' },
472
+ },
473
+ };
474
+ let index = 0;
475
+ try {
476
+ const updated = await sessionManager.addMessage(sessionId, info);
477
+ if (updated)
478
+ index = Math.max(0, updated.messages.length - 1);
479
+ }
480
+ catch (err) {
481
+ console.warn(`[sessions] info-блок восстановления не записан: ${err instanceof Error ? err.message : String(err)}`);
482
+ }
483
+ eventBus.publish(sessionId, 'message.added', serializeMessage(info, index));
484
+ };
485
+ // Session-маркеры хода/блокировки переживают рестарт: процесс, убитый при
486
+ // rolling update, не успевает снять `currentStream`/`status.blocked`, а
487
+ // процессор очереди такую сессию считает занятой и не стартует — UI вечно
488
+ // показывает активность. Восстановление отложено на 60 с, чтобы старый под
489
+ // успел умереть, а живые маркеры работающего процесса не были сняты.
490
+ // В деградации хранилище read-only — ничего не пишем и не запускаем.
491
+ if (!storageDegraded) {
492
+ const bootRecovery = setTimeout(() => {
493
+ void sessionManager.recoverInterruptedSessions()
494
+ .then(async (recovered) => {
495
+ for (const r of recovered) {
496
+ eventBus.publish(r.sessionId, 'turn.finished', {
497
+ turn_id: r.turnId,
498
+ turnId: r.turnId,
499
+ stream_id: r.streamId,
500
+ status: 'stopped',
501
+ });
502
+ eventBus.publish(r.sessionId, 'session.updated', { session_id: r.sessionId });
503
+ if (!r.resumeMessage)
504
+ continue;
505
+ // Автопродолжение: info-блок в истории (в LLM-контекст не попадает —
506
+ // роль INFO исключена из промпта) и resume-сообщение процессору.
507
+ await addRestartResumedNotice(r.sessionId, r.streamId);
508
+ queueManager.createProcessor(r.sessionId, sessionManager, eventBus, processMessage, {
509
+ resumeMessage: r.resumeMessage,
510
+ });
511
+ }
512
+ if (recovered.length) {
513
+ console.log(`[sessions] сняты маркеры прерванных ходов: ${recovered.length}`);
514
+ }
515
+ // Автозапуск очередей, переживших рестарт: pending без активного хода
516
+ // и без осознанной остановки (`queueStopped`). Сессии саб-агентов не
517
+ // продолжаем — решение за родителем. `light`-список не подходит:
518
+ // он очищает `pendingMessages`.
519
+ try {
520
+ // `light`: без истории (`messages`/`checkpoints`) — полный список
521
+ // сессий с историями давал пик heap и OOM на инстансах с сотнями
522
+ // сессий. Очередь (`pendingMessages`) в light сохраняется.
523
+ const sessions = await sessionManager.listSessions(undefined, {
524
+ includeArchived: false,
525
+ });
526
+ let queueCandidates = 0;
527
+ let inFlightResumed = 0;
528
+ for (const s of sessions) {
529
+ if (s.archivedAt || s.sessionOrigin === 'subagent')
530
+ continue;
531
+ if (s.currentStream || s.status.blocked)
532
+ continue;
533
+ if (s.pendingMessages.length === 0)
534
+ continue;
535
+ queueCandidates += 1;
536
+ if (s.status.queueStopped) {
537
+ eventBus.publish(s.id, 'queue.stalled', {
538
+ pending_count: s.pendingMessages.length,
539
+ });
540
+ continue;
541
+ }
542
+ // Маркеры мог снять прошлый recovery, а сообщение осталось и в
543
+ // истории, и в очереди. Это прерванный in-flight ход: продолжаем
544
+ // его как resume (info-блок + метка `resumed`), а не как новую
545
+ // очередь — иначе сообщение материализуется в историю повторно.
546
+ const resume = await sessionManager.takePendingInFlight(s.id);
547
+ if (resume) {
548
+ inFlightResumed += 1;
549
+ await addRestartResumedNotice(s.id, resume.metadata?.stream_id);
550
+ queueManager.createProcessor(s.id, sessionManager, eventBus, processMessage, {
551
+ resumeMessage: resume,
552
+ });
553
+ continue;
554
+ }
555
+ queueManager.createProcessor(s.id, sessionManager, eventBus, processMessage);
556
+ }
557
+ if (queueCandidates > 0) {
558
+ // Только счётчики: ни id, ни содержимого сессий/сообщений.
559
+ console.log(`[sessions] автозапуск очередей: кандидатов ${queueCandidates}, in-flight продолжено ${inFlightResumed}`);
560
+ }
561
+ }
562
+ catch (err) {
563
+ console.warn(`[sessions] автозапуск очередей после рестарта: ${err instanceof Error ? err.message : String(err)}`);
564
+ }
565
+ })
566
+ .catch((err) => {
567
+ console.warn(`[sessions] восстановление прерванных ходов: ${err instanceof Error ? err.message : String(err)}`);
568
+ });
569
+ }, 60_000);
570
+ bootRecovery.unref?.();
571
+ }
336
572
  // Retention-очистка терминальных записей реестра (сразу + каждые 6 ч).
337
573
  const stopBackgroundRunPruner = storageDegraded
338
574
  ? () => { }
@@ -359,6 +595,15 @@ executionConfig) {
359
595
  gcDays: () => attachmentsSettings.getConfig().gcDays,
360
596
  ...(attachmentMetrics ? { metrics: attachmentMetrics } : {}),
361
597
  });
598
+ // ADR-115 × ADR-077: уборка временных каталогов медиа-раннера
599
+ // (`{workspacesRoot}/.synth-media/<uuid>`). После жёсткого kill раннер не
600
+ // успевает убрать каталог (`finally` не выполняется) — такие каталоги
601
+ // копятся на общем томе. TTL 1 ч, интервал 6 ч, best-effort: каталога нет —
602
+ // нечего убирать (создавать его не надо). В деградированном режиме
603
+ // хранилища уборка не нужна (медиа не обрабатывается).
604
+ const stopMediaTempPruner = storageDegraded
605
+ ? () => { }
606
+ : startMediaTempPruner({ workspacesRoot: config.workspacesRoot });
362
607
  // ADR-094: доменные коллекторы. `metrics` приходит только при
363
608
  // `metrics.enabled=true` — иначе реестр остаётся пустым (`/metrics` → 404).
364
609
  // Фоновые таймеры `unref`-ятся; остановка — `stopMetricsCollectors` на
@@ -440,7 +685,12 @@ executionConfig) {
440
685
  const providerLoader = (name) => {
441
686
  // При старте загружаем все конфиги — JsonStore.list() не подходит для быстрого lookup
442
687
  // поэтому кешируем провайдеров в Map
443
- return providerCache.get(name) ?? null;
688
+ const provider = providerCache.get(name);
689
+ // Fail-closed: отключённый администратором провайдер не создаётся ни в чате,
690
+ // ни в ретраях, ни в пайплайнах/эмбеддингах/суммаризации.
691
+ if (!provider || provider.enabled === false)
692
+ return null;
693
+ return provider;
444
694
  };
445
695
  // ADR-038: синхронизация провайдеров/моделей из переменных окружения (общая
446
696
  // core-реализация). Вызывается ПОСЛЕ создания providerStore/modelStore, но ДО
@@ -539,6 +789,22 @@ executionConfig) {
539
789
  // системного промпта на инстанс — композер добавляет блоки в промпт сессии,
540
790
  // фасад плагинов (`PluginRuntime` → `PluginHost`) их регистрирует.
541
791
  const promptBlocks = new PromptBlockRegistry();
792
+ // Набор ролей прежней поставки (`pm`/`developer`/`qa`/`analyst`/`auditor`)
793
+ // заменён на `leader`/`fixer`/`tester`/`researcher`/`security-auditor`, но в
794
+ // сторе остаются полные копии прежних встроенных агентов. Без миграции в
795
+ // списке живут две роли сразу, а старая несёт подменённый `contextFile` при
796
+ // прежней идентичности/правах (агент получает чужую роль с чужими правами).
797
+ // Переносим пользовательские настройки в целевого встроенного агента,
798
+ // устаревшую запись удаляем; идемпотентно.
799
+ try {
800
+ const migratedAgents = await migrateLegacyStoredAgents(agentStore);
801
+ if (migratedAgents.length > 0) {
802
+ console.info(`[agents] миграция устаревших агентов: ${migratedAgents.join(', ')}`);
803
+ }
804
+ }
805
+ catch (err) {
806
+ console.warn(`[agents] не удалось мигрировать устаревших агентов: ${err instanceof Error ? err.message : String(err)}`);
807
+ }
542
808
  // ADR-096 + ADR-086 §5: агенты из **стора** — в реестр при старте.
543
809
  // `createAgentRegistry` читает только файловый каталог `{dataDir}/agents`,
544
810
  // а при `storage.backend=postgres` стор агентов — это БД: агент, поставленный
@@ -621,7 +887,7 @@ executionConfig) {
621
887
  defaultWorkingDir,
622
888
  // Привязанная живая сессия — по полю `session.worktree` (ADR-114 §1.3).
623
889
  resolveAttachedSession: async (worktreeId) => {
624
- const sessions = await sessionManager.listSessions(undefined, { light: true });
890
+ const sessions = await sessionManager.listSessions(undefined);
625
891
  return sessions.find((s) => s.worktree?.worktreeId === worktreeId)?.id;
626
892
  },
627
893
  onUpdated: (projectId, detail) => {
@@ -708,6 +974,76 @@ executionConfig) {
708
974
  }
709
975
  return prefixMatch;
710
976
  };
977
+ /**
978
+ * Совместимость протокола по каталогу: `provider.compatibility` (JSON
979
+ * провайдера) + shorthand `ModelConfig.requiresReasoning` +
980
+ * `model.compatibility` (каталог/ручной override). Порядок слоёв —
981
+ * provider → shorthand → модель (модель перекрывает).
982
+ * `undefined` — явных значений нет, работают эвристики провайдера.
983
+ */
984
+ const resolveModelCompatibility = (providerName, modelId) => {
985
+ const providerCompat = providerCache.get(providerName)?.compatibility;
986
+ let model = modelCache.get(`${providerName}/${modelId}`) ?? modelCache.get(modelId);
987
+ if (!model) {
988
+ for (const candidate of modelCache.values()) {
989
+ if (candidate.provider !== providerName)
990
+ continue;
991
+ if (candidate.name === modelId) {
992
+ model = candidate;
993
+ break;
994
+ }
995
+ }
996
+ }
997
+ const shorthand = model?.requiresReasoning !== undefined
998
+ ? { requireReasoning: model.requiresReasoning }
999
+ : undefined;
1000
+ if (!providerCompat && !shorthand && !model?.compatibility)
1001
+ return undefined;
1002
+ return mergeModelCompatibility(providerCompat, shorthand, model?.compatibility);
1003
+ };
1004
+ /**
1005
+ * Лимит вывода модели из каталога (`ModelConfig.maxOutputTokens`): кап для
1006
+ * резолва `max_tokens` и источник значения при авто-лимите сессии.
1007
+ * `undefined` — у модели лимит неизвестен (или не положителен).
1008
+ */
1009
+ const resolveModelMaxOutputTokens = (providerName, modelId) => {
1010
+ let model = modelCache.get(`${providerName}/${modelId}`) ?? modelCache.get(modelId);
1011
+ if (!model) {
1012
+ for (const candidate of modelCache.values()) {
1013
+ if (candidate.provider !== providerName)
1014
+ continue;
1015
+ if (candidate.name === modelId) {
1016
+ model = candidate;
1017
+ break;
1018
+ }
1019
+ }
1020
+ }
1021
+ return typeof model?.maxOutputTokens === 'number' && model.maxOutputTokens > 0
1022
+ ? model.maxOutputTokens
1023
+ : undefined;
1024
+ };
1025
+ /** Доступность провайдера для понятной ошибки хода (`provider_disabled`). */
1026
+ const providerAvailability = (name) => {
1027
+ const provider = providerCache.get(name);
1028
+ if (!provider)
1029
+ return 'missing';
1030
+ return provider.enabled === false ? 'disabled' : 'ok';
1031
+ };
1032
+ /** Включена ли модель (`false` — отключена); нет записи — `undefined`. */
1033
+ const resolveModelEnabled = (providerName, modelId) => {
1034
+ let model = modelCache.get(`${providerName}/${modelId}`) ?? modelCache.get(modelId);
1035
+ if (!model) {
1036
+ for (const candidate of modelCache.values()) {
1037
+ if (candidate.provider !== providerName)
1038
+ continue;
1039
+ if (candidate.name === modelId) {
1040
+ model = candidate;
1041
+ break;
1042
+ }
1043
+ }
1044
+ }
1045
+ return model ? model.enabled !== false : undefined;
1046
+ };
711
1047
  const orchestrator = new ChatOrchestrator({
712
1048
  sessionManager,
713
1049
  eventBus,
@@ -738,6 +1074,21 @@ executionConfig) {
738
1074
  profilesStore,
739
1075
  // ADR-076 §T6: тот же store, что у git/ssh-роутов — без дублей инстансов.
740
1076
  sshKeyStore,
1077
+ // ADR-076: таймауты сетевых git-операций (`git.cloneTimeoutMs`/`fetchTimeoutMs`)
1078
+ // для git-сервиса тулов `project_repo_*`; git-роуты получают те же значения.
1079
+ ...(config.synth.git?.cloneTimeoutMs !== undefined
1080
+ ? { gitCloneTimeoutMs: config.synth.git.cloneTimeoutMs }
1081
+ : {}),
1082
+ ...(config.synth.git?.fetchTimeoutMs !== undefined
1083
+ ? { gitFetchTimeoutMs: config.synth.git.fetchTimeoutMs }
1084
+ : {}),
1085
+ // Таймауты git-тулов по классу операции: локальные изменяющие и сетевые.
1086
+ ...(config.synth.git?.localTimeoutMs !== undefined
1087
+ ? { gitLocalTimeoutMs: config.synth.git.localTimeoutMs }
1088
+ : {}),
1089
+ ...(config.synth.git?.networkTimeoutMs !== undefined
1090
+ ? { gitNetworkTimeoutMs: config.synth.git.networkTimeoutMs }
1091
+ : {}),
741
1092
  // ADR-096 (W2.4): словари классификации — порт из контекста хранения.
742
1093
  dictionaryStore,
743
1094
  // ADR-115/ADR-116: blob-порт гидратации вложений — из контекста хранения
@@ -746,9 +1097,21 @@ executionConfig) {
746
1097
  // ADR-115: модальности модели — из её конфига (общий резолвер инстанса,
747
1098
  // выше: им же пользуются шаги пайплайнов).
748
1099
  resolveModelModalities,
1100
+ // Совместимость протокола (provider+model) из каталога.
1101
+ resolveModelCompatibility,
1102
+ // Лимит вывода модели из каталога (кап `max_tokens`) + дефолт `llm.maxTokens`.
1103
+ resolveModelMaxOutputTokens,
1104
+ // Понятные ошибки движка: провайдер/модель отключены — fail-closed.
1105
+ providerAvailability,
1106
+ resolveModelEnabled,
1107
+ defaultMaxOutputTokens: config.synth.llm.maxTokens,
749
1108
  // ADR-115: `attachments.workspaceFallback` — материализация отброшенных
750
1109
  // вложений в workspace; live-конфиг (проверяется на каждый ход).
751
1110
  attachmentsConfig: () => attachmentsSettings.getConfig(),
1111
+ // Политика контекстного окна — live-геттер (перед каждым LLM-вызовом).
1112
+ contextWindowPolicy: () => contextWindowSettings.getPolicy(),
1113
+ // Бюджет промпта саб-агента — live-геттер (runtime-настройка из UI).
1114
+ getSubagentMaxInputTokens: () => subagentMaxInputTokensSettings.getValue(),
752
1115
  // ADR-115: каталог моделей инстанса для агента (тул `list_models`):
753
1116
  // тот же `modelStore`, что у `GET /api/v2/models` (каталог провайдеров +
754
1117
  // ручные override), поэтому модальности совпадают с UI.
@@ -767,6 +1130,8 @@ executionConfig) {
767
1130
  decisionConfig: effectiveDecisionSettings,
768
1131
  permissionConfig: config.synth.permission,
769
1132
  defaultPlanMode: config.synth.session.planMode,
1133
+ // Секция `session.autoTitle` — авто-именование сессии (ранний триггер).
1134
+ ...(config.synth.session?.autoTitle ? { autoTitle: config.synth.session.autoTitle } : {}),
770
1135
  securityConfig,
771
1136
  gatewayConfig,
772
1137
  gatewayAuditLogger,
@@ -821,6 +1186,8 @@ executionConfig) {
821
1186
  // `task` с `background: true` регистрирует фонового саб-агента и
822
1187
  // возвращает управление сразу (PROP-096).
823
1188
  ...(backgroundService ? { backgroundService } : {}),
1189
+ // ADR-104 × ADR-111/ADR-113: остаток steer-очереди в конце хода — в очередь.
1190
+ requeueSteerMessages: (sessionId, messages, opts) => requeueSteerMessages(sessionId, messages, opts.autostart),
824
1191
  // PROP-097: сервис фоновых шелл-процессов — тот же экземпляр, что у
825
1192
  // реестра и тула `execute_shell` (через `ctx.extra.processService`).
826
1193
  ...(processService ? { processService } : {}),
@@ -828,6 +1195,17 @@ executionConfig) {
828
1195
  // per-session рабочих каталогов проекта).
829
1196
  ...(worktreeService ? { worktreeService } : {}),
830
1197
  backgroundEnabled: config.synth.background.enabled,
1198
+ // Предохранитель по объёму промпта саб-агента (`agents.subagentMaxInputTokens`).
1199
+ subagentMaxInputTokens: config.synth.agents.subagentMaxInputTokens,
1200
+ // Лимит глубины вложенности саб-агентов (`agents.subagentDepth`): при
1201
+ // превышении тул `task` отказывает до создания дочерней сессии.
1202
+ subagentDepth: config.synth.agents.subagentDepth,
1203
+ // Общий предел вывода инструментов (`tools.outputMaxLines`/
1204
+ // `tools.outputMaxBytes`) — усечение результата тула с пояснением.
1205
+ toolOutputLimits: {
1206
+ maxLines: config.synth.tools.outputMaxLines ?? DEFAULT_TOOL_OUTPUT_MAX_LINES,
1207
+ maxBytes: config.synth.tools.outputMaxBytes ?? DEFAULT_TOOL_OUTPUT_MAX_BYTES,
1208
+ },
831
1209
  });
832
1210
  // ADR-090 (Ф5б-2): эффективный конфиг слоя = config.yaml (+env) поверх
833
1211
  // runtime-настроек (`settings.json`/PG): админка `/api/v2/settings/plugins`
@@ -869,7 +1247,7 @@ executionConfig) {
869
1247
  throw new PluginFacadeError('plugin.embedding_not_configured', `Провайдер «${providerName}» не найден в инстансе — эмбеддинги недоступны.`);
870
1248
  }
871
1249
  const model = opts?.model?.trim() || sharedConfig.defaultModel || '';
872
- const provider = orchestrator.wrapProviderWithGateway(ProviderFactory.create(providerName, toCoreProviderConfig(sharedConfig, model)));
1250
+ const provider = orchestrator.wrapProviderWithGateway(ProviderFactory.create(providerName, toCoreProviderConfig(sharedConfig, model, undefined, resolveModelCompatibility(providerName, model))));
873
1251
  const vectors = [];
874
1252
  for (const text of texts) {
875
1253
  vectors.push(await provider.embed(text));
@@ -1099,9 +1477,27 @@ executionConfig) {
1099
1477
  // ADR-115 × ADR-089: сервис вложений проверяет ссылки `attachments[]` события
1100
1478
  // (объект есть, метаданные совпадают со sidecar) и даёт лимиты
1101
1479
  // `attachments.maxFilesPerMessage`/`maxBytesPerFile` (runtime-настройки — живые).
1480
+ // ADR-115 × ADR-077: медиа-раннер — единая точка запуска ffmpeg. Inline —
1481
+ // локально, remote — на исполнителе в общем workspace (`requires: ['ffmpeg']`).
1482
+ const mediaRunner = createMediaRunner({
1483
+ blobs: storageContext.blobs,
1484
+ executionPort,
1485
+ workspacesRoot: config.workspacesRoot,
1486
+ log: (message) => console.warn(message),
1487
+ });
1488
+ // ADR-115: серверные миниатюры вложений (content-addressed `.thumbs`).
1489
+ // Настройки (`attachments.thumbnail`: enabled/maxWidthPx) — тот же live-резолвер,
1490
+ // что у `AttachmentService` (runtime-патч применяется без рестарта).
1491
+ const attachmentThumbnails = new ThumbnailService({
1492
+ blobs: storageContext.blobs,
1493
+ runner: mediaRunner,
1494
+ config: () => attachmentsSettings.getConfig().thumbnail,
1495
+ log: (message) => console.warn(message),
1496
+ });
1102
1497
  const eventAttachmentService = new AttachmentService({
1103
1498
  blobs: storageContext.blobs,
1104
1499
  config: () => attachmentsSettings.getConfig(),
1500
+ thumbnails: attachmentThumbnails,
1105
1501
  });
1106
1502
  const eventIngress = new EventIngress({
1107
1503
  requestSessionService,
@@ -1122,23 +1518,16 @@ executionConfig) {
1122
1518
  // ADR-036/ADR-101: провайдер шага — **всегда** через `GatewayProvider`
1123
1519
  // (обёртка оркестратора: та же точка, что у пула провайдеров). Провайдер
1124
1520
  // не кэшируется — обёртка подхватывает live-конфиг LLM Gateway.
1125
- const resolvePipelineProvider = async () => {
1126
- try {
1127
- const defaults = await resolveLlmDefaults();
1128
- const providerName = defaults.provider?.trim();
1129
- if (!providerName)
1130
- return null;
1131
- const sharedConfig = providerLoader(providerName);
1132
- if (!sharedConfig)
1133
- return null;
1134
- const coreConfig = toCoreProviderConfig(sharedConfig, defaults.model?.trim() || sharedConfig.defaultModel || '');
1135
- return orchestrator.wrapProviderWithGateway(ProviderFactory.create(providerName, coreConfig));
1136
- }
1137
- catch {
1138
- // Провайдер не собран — шаг упадёт с `pipeline.provider_not_found`.
1139
- return null;
1140
- }
1141
- };
1521
+ // ADR-101 §4 × `AgentDefinition`: провайдер/модель/температура/sampling
1522
+ // агента шага (`ctx.step.agent`) приоритетнее дефолтов инстанса — резолвер
1523
+ // общий с core-точкой сборки (`resolvePipelineStepProvider`).
1524
+ const resolvePipelineProvider = (ctx) => resolvePipelineStepProvider(ctx, {
1525
+ resolveLlmDefaults,
1526
+ loadProviderConfig: providerLoader,
1527
+ toProviderConfig: (shared, model) => toCoreProviderConfig(shared, model, undefined, resolveModelCompatibility(shared.name, model)),
1528
+ createProvider: (name, config, temperature, topP, topK) => ProviderFactory.create(name, config, temperature, topP, topK),
1529
+ wrapProvider: (provider) => orchestrator.wrapProviderWithGateway(provider),
1530
+ });
1142
1531
  // ADR-101 §9 / ADR-116: артефакты прогонов — байты в общем blob-порте
1143
1532
  // (отдельного хранилища артефактов нет). Тот же инстанс получают выход `file`
1144
1533
  // (запись) и HTTP-раздача артефактов прогона (`GET
@@ -1206,13 +1595,15 @@ executionConfig) {
1206
1595
  const sharedConfig = providerLoader(provider);
1207
1596
  if (!sharedConfig)
1208
1597
  return null;
1209
- return orchestrator.wrapProviderWithGateway(ProviderFactory.create(provider, toCoreProviderConfig(sharedConfig, model)));
1598
+ return orchestrator.wrapProviderWithGateway(ProviderFactory.create(provider, toCoreProviderConfig(sharedConfig, model, undefined, resolveModelCompatibility(provider, model))));
1210
1599
  }
1211
1600
  catch {
1212
1601
  return null;
1213
1602
  }
1214
1603
  },
1215
1604
  hasFfmpeg: () => isFfmpegAvailable(executionPort).catch(() => false),
1605
+ executionPort,
1606
+ workspacesRoot: config.workspacesRoot,
1216
1607
  promptTemplate: (language) => contextConfig.getMediaDeriveTemplate(language),
1217
1608
  language: 'ru',
1218
1609
  log: (message) => console.warn(message),
@@ -1384,6 +1775,8 @@ executionConfig) {
1384
1775
  // ADR-115 × ADR-101: сервис вложений — проверка `attachments[]` в теле
1385
1776
  // запуска прогона (тот же экземпляр, что у приёма событий).
1386
1777
  pipelineAttachments: eventAttachmentService,
1778
+ // ADR-115: провайдер серверных миниатюр (`?variant=thumb` в роутах вложений).
1779
+ attachmentThumbnails,
1387
1780
  // ADR-101: реестр активных прогонов — общий для HTTP-роута пайплайнов и
1388
1781
  // встроенных тулов агента (soft-lock + отмена идущего прогона).
1389
1782
  pipelineRunControl,
@@ -1402,8 +1795,17 @@ executionConfig) {
1402
1795
  stopProcessLogPruner,
1403
1796
  // ADR-115: GC осиротевших вложений сообщений.
1404
1797
  stopAttachmentPruner,
1798
+ // ADR-115 × ADR-077: уборка временных каталогов медиа-раннера.
1799
+ stopMediaTempPruner,
1405
1800
  // ADR-115: живое состояние настроек вложений (сервис/промпт/GC + админ-API).
1406
1801
  attachmentsSettings,
1802
+ // Политика ограничения контекстного окна (live, админ-API).
1803
+ contextWindowSettings,
1804
+ subagentMaxInputTokensSettings,
1805
+ // Дефолты оптимизации контекста новых сессий (live, админ-API).
1806
+ contextDefaultsSettings,
1807
+ // Instance-wide лимиты заметок сессии (live, админ-API).
1808
+ stickyNotesLimitsSettings,
1407
1809
  // ADR-114: сервис worktree'ов — HTTP-контур проектов и привязка сессии.
1408
1810
  worktreeService,
1409
1811
  webhookStore,