@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/main.js CHANGED
@@ -16,7 +16,7 @@ catch (err) {
16
16
  console.error(err instanceof Error ? err.message : String(err));
17
17
  process.exit(1);
18
18
  }
19
- const { app, dataDir, port, config, auth, eventHub, queueManager, sessionManager, stopEphemeralSweeper, stopEventJournalPruner, stopAnalyticsRollupPruner, stopScheduler, stopWebhookService, stopWebhookDeliveryPruner, stopMetrics, stopQuestionPruner, stopBackgroundRunPruner, stopProcessLogPruner, stopAttachmentPruner } = handle;
19
+ const { app, dataDir, port, config, auth, eventHub, queueManager, sessionManager, stopEphemeralSweeper, stopEventJournalPruner, stopAnalyticsRollupPruner, stopScheduler, stopWebhookService, stopWebhookDeliveryPruner, stopMetrics, stopQuestionPruner, stopBackgroundRunPruner, stopProcessLogPruner, stopAttachmentPruner, stopMediaTempPruner } = handle;
20
20
  // ADR-090 (Ф5б-1): старт-активация установленных плагинов.
21
21
  // `plugins.lock.json` — источник истины; `plugins.executionEnabled=false`
22
22
  // (дефолт) → no-op. Ошибка плагина/рантайма **не роняет старт** (только
@@ -83,6 +83,8 @@ async function gracefulShutdown(signal, exitCode = 0) {
83
83
  stopProcessLogPruner();
84
84
  // ADR-115: остановить GC осиротевших вложений сообщений.
85
85
  stopAttachmentPruner();
86
+ // ADR-115 × ADR-077: остановить уборку временных каталогов медиа-раннера.
87
+ stopMediaTempPruner();
86
88
  // ADR-094: остановить процессные метрики и фоновые доменные коллекторы
87
89
  // (таймеры сессий/хранилища, подписка шины, decision/journal).
88
90
  stopMetrics();
@@ -27,6 +27,7 @@ export function createAgentRoutes(kit, agentStore, agentRegistry, getDefaultAgen
27
27
  idRequired: (c) => t('errors.validation.idRequired', undefined, c),
28
28
  invalidAgentId: (c) => t('errors.validation.invalidAgentId', undefined, c),
29
29
  invalidRoleFile: (c) => t('errors.validation.invalidRoleFile', undefined, c),
30
+ invalidEffort: (c) => t('errors.validation.invalidEffort', undefined, c),
30
31
  agentNotFound: (c) => t('errors.notFound.agent', undefined, c),
31
32
  agentOverrideNotFound: (c) => t('errors.notFound.agentOverride', undefined, c),
32
33
  },
@@ -9,12 +9,32 @@ import { join, resolve, sep } from 'node:path';
9
9
  const OIDC_STATE_COOKIE = 'oidc_state';
10
10
  // Встроенные умолчания оформления (совпадают с тем, что использует UI
11
11
  // по умолчанию: packages/ui/src/lib/defaults.ts + uiScale.ts).
12
+ // `null` — «умолчание не задано»: UI берёт встроенный дефолт.
12
13
  const BUILT_IN_DEFAULTS = {
13
14
  themeMode: 'system',
14
15
  theme: 'synthesis',
15
16
  uiScaleMobile: null,
16
17
  uiScaleDesktop: null,
18
+ chatViewMode: null,
19
+ chatDensity: null,
20
+ chatScaleMobile: null,
21
+ chatScaleDesktop: null,
17
22
  };
23
+ /**
24
+ * Поля умолчаний оформления, которые принимает `PUT /defaults`.
25
+ * Whitelist на границе: тело запроса не должно попадать в стор целиком
26
+ * (запись валидирует store, но лишние ключи там не нужны).
27
+ */
28
+ const DEFAULT_FIELDS = [
29
+ 'themeMode',
30
+ 'theme',
31
+ 'uiScaleMobile',
32
+ 'uiScaleDesktop',
33
+ 'chatViewMode',
34
+ 'chatDensity',
35
+ 'chatScaleMobile',
36
+ 'chatScaleDesktop',
37
+ ];
18
38
  export function createAuthRoutes(kit, config, profiles, dataDir, defaultsStore,
19
39
  /**
20
40
  * ADR-090 Ф7: сигнал о серверной политике плагинов для публичного
@@ -404,7 +424,15 @@ pluginPolicySignal) {
404
424
  setDefaultLang(locale);
405
425
  }
406
426
  if (defaultsStore) {
407
- const patch = { ...body };
427
+ // Whitelist полей: остальное тело запроса игнорируется, а валидация
428
+ // значений (enum/диапазоны) — в `DefaultsStore.sanitize`.
429
+ const patch = {};
430
+ const rest = body;
431
+ for (const field of DEFAULT_FIELDS) {
432
+ if (field in rest) {
433
+ patch[field] = rest[field];
434
+ }
435
+ }
408
436
  if (patch.locale === undefined && (locale === 'en' || locale === 'ru')) {
409
437
  patch.locale = locale;
410
438
  }
@@ -1,7 +1,8 @@
1
1
  import { Hono } from 'hono';
2
2
  import { z } from 'zod';
3
3
  import { scopeGuard } from '../auth/service-scope.js';
4
- import { ContextLengthExceededError, deobfuscateSecrets, GatewayProvider, ProviderError, ProviderFactory, RateLimitError, createLlmCallRecorder, } from '@itphx/synth-core';
4
+ import { EFFORT_LEVELS, mergeModelCompatibility } from '@itphx/synth-shared';
5
+ import { buildChatOptions, ContextLengthExceededError, deobfuscateSecrets, GatewayProvider, ProviderError, ProviderFactory, RateLimitError, createLlmCallRecorder, } from '@itphx/synth-core';
5
6
  /**
6
7
  * LLM Proxy endpoint (гибридный режим, Часть 5).
7
8
  * OpenAI-совместимый POST /api/v2/llm/chat/completions, через который локальный
@@ -29,12 +30,22 @@ const chatCompletionsSchema = z.object({
29
30
  temperature: z.number().optional(),
30
31
  max_tokens: z.number().int().positive().optional(),
31
32
  top_p: z.number().optional(),
33
+ /**
34
+ * ADR-117: тир усилия модели в OpenAI-совместимом поле (`EffortLevel`).
35
+ * Прокидывается провайдеру как `ChatOptions.effort`; отправляется он только
36
+ * при `compatibility.supportsEffortUpdates` (guard остаётся в провайдере).
37
+ * Невалидное значение — 400 (контракт запроса, а не «тихий» игнор).
38
+ */
39
+ reasoning_effort: z.enum(EFFORT_LEVELS).optional(),
32
40
  stream: z.boolean().optional(),
33
41
  // ADR-070: remote-зеркала (RemoteProvider) просят usage в стриме. Внутренний
34
42
  // OpenAIProvider всегда шлёт stream_options.include_usage, но поле принимаем
35
43
  // явно, чтобы Zod его не срезал (контракт запроса).
36
44
  stream_options: z.object({ include_usage: z.boolean().optional() }).optional(),
37
45
  tools: z.array(z.record(z.string(), z.unknown())).optional(),
46
+ // Управление вызовом инструментов на шаге: `none` — финальный шаг-отчёт по
47
+ // лимиту шагов (инструменты остаются в запросе ради кэшированного префикса).
48
+ tool_choice: z.enum(['auto', 'none', 'required']).optional(),
38
49
  session_id: z.string().optional(),
39
50
  // Имя серверного провайдера (шлют remote-зеркала RemoteProvider в гибриде).
40
51
  // Опционально — старые клиенты без поля работают как раньше (резолв по модели).
@@ -156,6 +167,10 @@ export function createLlmRoutes(kit, deps) {
156
167
  }, 400);
157
168
  }
158
169
  // 2. Создаём провайдер (модель из ModelConfig.name — реальное имя для LLM API).
170
+ // ADR-117: совместимость протокола собирается теми же слоями, что и в
171
+ // сессионном вызове — провайдер → shorthand модели (`requiresReasoning`) →
172
+ // модель. Без этого у прокси не работали `requireReasoning`,
173
+ // `maxTokensField`, `cacheFormat`, `supportsEffortUpdates`.
159
174
  let inner;
160
175
  try {
161
176
  inner = ProviderFactory.create(providerName, {
@@ -167,6 +182,9 @@ export function createLlmRoutes(kit, deps) {
167
182
  timeout: providerConfig.timeout ?? 120,
168
183
  maxTokens: body.max_tokens,
169
184
  numCtx: providerConfig.numCtx,
185
+ compatibility: mergeModelCompatibility(providerConfig.compatibility, modelConfig.requiresReasoning !== undefined
186
+ ? { requireReasoning: modelConfig.requiresReasoning }
187
+ : undefined, modelConfig.compatibility),
170
188
  }, body.temperature, body.top_p);
171
189
  }
172
190
  catch (e) {
@@ -201,12 +219,16 @@ export function createLlmRoutes(kit, deps) {
201
219
  });
202
220
  const messages = toLlmMessages(body.messages);
203
221
  const tools = body.tools && body.tools.length > 0 ? body.tools : undefined;
222
+ // `tool_choice` уходит провайдеру только когда задан в теле (иначе поведение
223
+ // прежнее — решение за моделью); `reasoning_effort` — тем же объектом опций
224
+ // (`buildChatOptions` не создаёт пустой `{}`).
225
+ const chatOptions = buildChatOptions(body.reasoning_effort, body.tool_choice);
204
226
  if (body.stream) {
205
- return streamCompletions(c, provider, messages, tools, body.model, transientMap);
227
+ return streamCompletions(c, provider, messages, tools, body.model, transientMap, chatOptions);
206
228
  }
207
229
  // 4. Non-stream: полный ответ в OpenAI-формате.
208
230
  try {
209
- const response = await provider.chat(messages, undefined, tools, false);
231
+ const response = await provider.chat(messages, undefined, tools, false, undefined, chatOptions);
210
232
  const map = transientMap.get('proxy') ?? {};
211
233
  const content = deobfuscateSecrets(response.content, map);
212
234
  // Симметрично OpenAIProvider._parseResponse: tool_calls → message.tool_calls,
@@ -240,7 +262,7 @@ export function createLlmRoutes(kit, deps) {
240
262
  * Ошибки провайдера в середине стрима (статус уже 200) шлём объектом error
241
263
  * в потоке, затем [DONE] и закрываем.
242
264
  */
243
- function streamCompletions(c, provider, messages, tools, model, transientMap) {
265
+ function streamCompletions(c, provider, messages, tools, model, transientMap, chatOptions) {
244
266
  const signal = c.req.raw.signal;
245
267
  const cancellationToken = {
246
268
  cancelled: false,
@@ -269,7 +291,7 @@ function streamCompletions(c, provider, messages, tools, model, transientMap) {
269
291
  // отдаём дельту, чтобы клиент (RemoteProvider) накапливал как content.
270
292
  let sentReasoningLen = 0;
271
293
  try {
272
- for await (const chunk of provider.chatAsync(messages, undefined, tools, undefined, cancellationToken)) {
294
+ for await (const chunk of provider.chatAsync(messages, undefined, tools, undefined, cancellationToken, chatOptions)) {
273
295
  if (chunk.usage)
274
296
  finalUsage = chunk.usage;
275
297
  if (chunk.toolCalls && chunk.toolCalls.length > 0)
@@ -24,6 +24,8 @@ blobRefs) {
24
24
  forbidden: (c) => t('auth.forbidden', undefined, c),
25
25
  },
26
26
  onMessagesChanged: (sessionId) => recalcCanSummarize(sessionId),
27
+ // ADR-118 §4/§7: удаление сообщения публикует `message.deleted` в канал сессии.
28
+ eventBus,
27
29
  // ADR-115: ссылки на объекты вложений снимаются при удалении сообщения.
28
30
  ...(blobRefs ? { blobRefs } : {}),
29
31
  resolveUserId: async (c) => (await kit.getCurrentUser(c))?.id ?? '',
@@ -1,6 +1,6 @@
1
1
  import { Hono } from 'hono';
2
2
  import type { AuthKit } from '../auth/middleware.js';
3
- import type { ProjectRepository, SessionManager, McpManager, SkillService, SettingsRepository, McpRegistryRepository } from '@itphx/synth-core';
3
+ import type { ProjectRepository, SessionManager, McpManager, SkillService, SettingsRepository, McpRegistryRepository, EventBus } from '@itphx/synth-core';
4
4
  import type { WorktreeService } from '@itphx/synth-core';
5
5
  import type { Project } from '@itphx/synth-shared';
6
6
  /**
@@ -34,4 +34,10 @@ skillService?: SkillService, settingsStore?: SettingsRepository, mcpRegistryStor
34
34
  * ADR-114: сервис worktree'ов проекта — контур `/projects/:id/worktrees*`
35
35
  * (список/создание/удаление/prune). Не задан — роутов нет.
36
36
  */
37
- worktreeService?: WorktreeService): Hono;
37
+ worktreeService?: WorktreeService,
38
+ /**
39
+ * ADR-118 §4: шина событий — `PUT /:id`/`DELETE /:id` публикуют
40
+ * `project.updated`/`project.deleted` в канал каждой сессии проекта.
41
+ * Не задана — публикации нет (поведение прежнее).
42
+ */
43
+ eventBus?: EventBus): Hono;
@@ -38,7 +38,13 @@ skillService, settingsStore, mcpRegistryStore,
38
38
  * ADR-114: сервис worktree'ов проекта — контур `/projects/:id/worktrees*`
39
39
  * (список/создание/удаление/prune). Не задан — роутов нет.
40
40
  */
41
- worktreeService) {
41
+ worktreeService,
42
+ /**
43
+ * ADR-118 §4: шина событий — `PUT /:id`/`DELETE /:id` публикуют
44
+ * `project.updated`/`project.deleted` в канал каждой сессии проекта.
45
+ * Не задана — публикации нет (поведение прежнее).
46
+ */
47
+ eventBus) {
42
48
  const { canManageProject, canEditProjectContent, canReadProject } = createProjectAccess(kit);
43
49
  return createCoreProjectRoutes({ requireAuth: kit.requireAuth }, store, undefined, {
44
50
  canManage: canManageProject,
@@ -75,5 +81,19 @@ worktreeService) {
75
81
  getOutsideRootPolicy: () => 'deny',
76
82
  // ADR-114: контур worktree'ов проекта.
77
83
  ...(worktreeService ? { worktrees: worktreeService } : {}),
84
+ // ADR-118 §4: изменение/удаление проекта — в канал каждой сессии проекта.
85
+ ...(eventBus
86
+ ? {
87
+ sessionManager,
88
+ onProjectChanged: async (projectId, kind) => {
89
+ const sessions = await sessionManager.listSessions({ projectId });
90
+ for (const s of sessions) {
91
+ eventBus.publish(s.id, kind === 'deleted' ? 'project.deleted' : 'project.updated', {
92
+ project_id: projectId,
93
+ });
94
+ }
95
+ },
96
+ }
97
+ : {}),
78
98
  });
79
99
  }
@@ -1,9 +1,12 @@
1
1
  import { Hono } from 'hono';
2
2
  import type { AuthKit } from '../auth/middleware.js';
3
3
  import type { SessionManager, QueueProcessorManager, ChatOrchestrator, EventBus, ProjectRepository } from '@itphx/synth-core';
4
+ import type { Message } from '@itphx/synth-shared';
4
5
  /**
5
6
  * Backend-обёртка над core-фабрикой очереди: добавляет i18n-сообщения и RBAC
6
7
  * доступа к сессии (владелец/ADMIN/участник проекта/LEAD). Логика роутов
7
8
  * (clear/return/resume/retry-now/cancel-retry) — в core-фабрике.
8
9
  */
9
- export declare function createQueueRoutes(kit: AuthKit, sessionManager: SessionManager, queueManager: QueueProcessorManager, eventBus: EventBus, processMessage: ReturnType<ChatOrchestrator['createProcessMessage']>, projectStore?: ProjectRepository): Hono;
10
+ export declare function createQueueRoutes(kit: AuthKit, sessionManager: SessionManager, queueManager: QueueProcessorManager, eventBus: EventBus, processMessage: ReturnType<ChatOrchestrator['createProcessMessage']>, projectStore?: ProjectRepository,
11
+ /** ADR-036: обфускация user-сообщения (та же, что у `POST /sessions/:id/prompt`). */
12
+ obfuscate?: (sessionId: string, message: Message) => Promise<Message>): Hono;
@@ -7,7 +7,9 @@ import { createProjectAccess } from './projects.js';
7
7
  * доступа к сессии (владелец/ADMIN/участник проекта/LEAD). Логика роутов
8
8
  * (clear/return/resume/retry-now/cancel-retry) — в core-фабрике.
9
9
  */
10
- export function createQueueRoutes(kit, sessionManager, queueManager, eventBus, processMessage, projectStore) {
10
+ export function createQueueRoutes(kit, sessionManager, queueManager, eventBus, processMessage, projectStore,
11
+ /** ADR-036: обфускация user-сообщения (та же, что у `POST /sessions/:id/prompt`). */
12
+ obfuscate) {
11
13
  const app = new Hono();
12
14
  const { canReadProject, canEditProjectContent } = createProjectAccess(kit);
13
15
  // ADR-071 §2.4: владелец сессии — обычный пользователь.
@@ -39,6 +41,7 @@ export function createQueueRoutes(kit, sessionManager, queueManager, eventBus, p
39
41
  ? canReadProject(ctx, project, userId)
40
42
  : canEditProjectContent(ctx, project, userId);
41
43
  },
44
+ ...(obfuscate ? { obfuscate } : {}),
42
45
  }));
43
46
  return app;
44
47
  }
@@ -12,19 +12,23 @@ import type { EventHub } from '../events/hub.js';
12
12
  import type { ProjectRepository } from '@itphx/synth-core';
13
13
  import type { MemoryFactRepository, MemoryIndexRepository } from '@itphx/synth-core';
14
14
  import type { BlobRefRepository, BlobStore } from '@itphx/synth-core';
15
- import type { AttachmentsConfig } from '@itphx/synth-shared';
15
+ import type { AttachmentThumbnailProvider } from '@itphx/synth-core';
16
+ import type { AttachmentsConfig, StickyNotesLimits } from '@itphx/synth-shared';
16
17
  import type { QuestionService } from '@itphx/synth-core';
17
18
  import type { WorktreeService } from '@itphx/synth-core';
19
+ import type { BackgroundRunService } from '@itphx/synth-core';
20
+ import type { ApprovalRegistry } from '@itphx/synth-core';
18
21
  /**
19
22
  * Backend-обёртка над core-фабрикой сессий (ТД-1, фаза B2). Здесь остаются только
20
23
  * backend-специфичные роуты (MCP-скоуп сессии, секреты, export/import, отладка,
21
- * оптимизация контекста, sticky notes). Общая логика (список/создание/чтение/
22
- * изменение/удаление, status/prompt/stats, очередь+SSE, children/tree/fork,
23
- * references, merge) — в `createSessionRoutes` из `@itphx/synth-core`.
24
+ * оптимизация контекста). Общая логика (список/создание/чтение/изменение/
25
+ * удаление, status/prompt/stats, заметки (`notes`), очередь+SSE, children/tree/
26
+ * fork, references, merge) — в `createSessionRoutes` из `@itphx/synth-core`.
24
27
  *
25
28
  * RBAC: core-фабрика параметризуется `resolveUserId`/`resolveOwner`/`resolveAuthor`,
26
29
  * `canAccess` (владелец|ADMIN) и EventHub-хуками; remote/hybrid-ветки отключены
27
- * (getRemoteClient не передаётся). `GET /:id/events` на backend не регистрируется.
30
+ * (getRemoteClient не передаётся). Сессионного SSE нет: наблюдение за ходом —
31
+ * единственный глобальный канал `GET /api/v2/events` (ADR-118).
28
32
  *
29
33
  * Исключения из общего prefix-guard'а (собственные правила, роуты зарегистрированы
30
34
  * до guard'а): `/:id/mcp` (владелец|ADMIN, ADR-071 §2.4) и `/:id/secrets`
@@ -76,4 +80,31 @@ attachments?: {
76
80
  * из админки (`/api/v2/settings/attachments`) применяются на каждый вызов.
77
81
  */
78
82
  config: AttachmentsConfig | (() => AttachmentsConfig);
83
+ /** ADR-115: провайдер серверных миниатюр (`?variant=thumb`). */
84
+ thumbnails?: AttachmentThumbnailProvider;
85
+ },
86
+ /**
87
+ * ADR-111/ADR-113: единый реестр фоновых прогонов — «Стоп» сессии
88
+ * останавливает и живые дочерние прогоны (фоновые саб-агенты и их процессы),
89
+ * решение 2026-10-28. Не задан — прежнее поведение (только свой стрим/очередь).
90
+ */
91
+ backgroundService?: BackgroundRunService,
92
+ /**
93
+ * ADR-106 Ф3: реестр подтверждений — HTTP-ответ на подтверждение
94
+ * (`POST /:id/permissions/:approvalId`) принимает решение через него, как и
95
+ * WS-кадр `permission_reply`. Не задан — слой Authority выключен/в shadow.
96
+ */
97
+ approvalRegistry?: ApprovalRegistry,
98
+ /**
99
+ * Instance-wide лимиты заметок сессии (`context.stickyNotes`, live-резолвер)
100
+ * — прокидывается в core-фабрику: роуты заметок живут там (единая реализация).
101
+ */
102
+ getStickyNoteLimits?: () => StickyNotesLimits,
103
+ /**
104
+ * Доступность пары провайдер/модель **до постановки в очередь** (каталог
105
+ * инстанса). Не задана — проверка выключена.
106
+ */
107
+ llmAvailability?: {
108
+ isProviderEnabled?: (name: string) => boolean | undefined;
109
+ isModelEnabled?: (provider: string, model: string) => boolean | undefined;
79
110
  }): Hono;
@@ -8,13 +8,14 @@ import { createProjectAccess } from './projects.js';
8
8
  /**
9
9
  * Backend-обёртка над core-фабрикой сессий (ТД-1, фаза B2). Здесь остаются только
10
10
  * backend-специфичные роуты (MCP-скоуп сессии, секреты, export/import, отладка,
11
- * оптимизация контекста, sticky notes). Общая логика (список/создание/чтение/
12
- * изменение/удаление, status/prompt/stats, очередь+SSE, children/tree/fork,
13
- * references, merge) — в `createSessionRoutes` из `@itphx/synth-core`.
11
+ * оптимизация контекста). Общая логика (список/создание/чтение/изменение/
12
+ * удаление, status/prompt/stats, заметки (`notes`), очередь+SSE, children/tree/
13
+ * fork, references, merge) — в `createSessionRoutes` из `@itphx/synth-core`.
14
14
  *
15
15
  * RBAC: core-фабрика параметризуется `resolveUserId`/`resolveOwner`/`resolveAuthor`,
16
16
  * `canAccess` (владелец|ADMIN) и EventHub-хуками; remote/hybrid-ветки отключены
17
- * (getRemoteClient не передаётся). `GET /:id/events` на backend не регистрируется.
17
+ * (getRemoteClient не передаётся). Сессионного SSE нет: наблюдение за ходом —
18
+ * единственный глобальный канал `GET /api/v2/events` (ADR-118).
18
19
  *
19
20
  * Исключения из общего prefix-guard'а (собственные правила, роуты зарегистрированы
20
21
  * до guard'а): `/:id/mcp` (владелец|ADMIN, ADR-071 §2.4) и `/:id/secrets`
@@ -54,7 +55,29 @@ worktreeService,
54
55
  * ADR-115: вложения сообщений — blob-порт, учёт ссылок и лимиты
55
56
  * (прокидывается в core-фабрику: загрузка/раздача + `attachments` в промпте).
56
57
  */
57
- attachments) {
58
+ attachments,
59
+ /**
60
+ * ADR-111/ADR-113: единый реестр фоновых прогонов — «Стоп» сессии
61
+ * останавливает и живые дочерние прогоны (фоновые саб-агенты и их процессы),
62
+ * решение 2026-10-28. Не задан — прежнее поведение (только свой стрим/очередь).
63
+ */
64
+ backgroundService,
65
+ /**
66
+ * ADR-106 Ф3: реестр подтверждений — HTTP-ответ на подтверждение
67
+ * (`POST /:id/permissions/:approvalId`) принимает решение через него, как и
68
+ * WS-кадр `permission_reply`. Не задан — слой Authority выключен/в shadow.
69
+ */
70
+ approvalRegistry,
71
+ /**
72
+ * Instance-wide лимиты заметок сессии (`context.stickyNotes`, live-резолвер)
73
+ * — прокидывается в core-фабрику: роуты заметок живут там (единая реализация).
74
+ */
75
+ getStickyNoteLimits,
76
+ /**
77
+ * Доступность пары провайдер/модель **до постановки в очередь** (каталог
78
+ * инстанса). Не задана — проверка выключена.
79
+ */
80
+ llmAvailability) {
58
81
  const app = new Hono();
59
82
  const agentRegistry = orchestrator.agentRegistry;
60
83
  const { canReadProject, canEditProjectContent } = createProjectAccess(kit);
@@ -427,6 +450,9 @@ attachments) {
427
450
  summarize_token_threshold: session.settings.summarizeTokenThreshold,
428
451
  summarization_head_messages: session.settings.summarizationHeadMessages,
429
452
  summarization_tail_messages: session.settings.summarizationTailMessages,
453
+ summarization_keep_tokens: session.settings.summarizationKeepTokens,
454
+ compaction_keep_tokens: session.settings.compactionKeepTokens,
455
+ compaction_token_threshold: session.settings.compactionTokenThreshold,
430
456
  });
431
457
  });
432
458
  // PATCH /api/v2/sessions/:id/optimization — обновить настройки
@@ -459,6 +485,12 @@ attachments) {
459
485
  s.settings.summarizationHeadMessages = body.summarization_head_messages;
460
486
  if (body.summarization_tail_messages !== undefined)
461
487
  s.settings.summarizationTailMessages = body.summarization_tail_messages;
488
+ if (body.summarization_keep_tokens !== undefined)
489
+ s.settings.summarizationKeepTokens = body.summarization_keep_tokens;
490
+ if (body.compaction_keep_tokens !== undefined)
491
+ s.settings.compactionKeepTokens = body.compaction_keep_tokens;
492
+ if (body.compaction_token_threshold !== undefined)
493
+ s.settings.compactionTokenThreshold = body.compaction_token_threshold;
462
494
  await sessionManager.saveSession(s);
463
495
  });
464
496
  const updated = await sessionManager.getSession(c.req.param('id'));
@@ -473,13 +505,17 @@ attachments) {
473
505
  }
474
506
  // Доступ — у единого prefix-guard'а выше (владелец/elevated/роль в проекте).
475
507
  if (!contextOptimizer) {
476
- return c.json({ sliding_window: { triggered: false }, summarization: { triggered: false } });
508
+ return c.json({ sliding_window: { triggered: false }, summarization: { triggered: false }, compression: { triggered: false, reason: 'none', mode: null } });
477
509
  }
478
510
  const swResult = contextOptimizer.shouldApplySlidingWindow(session);
479
511
  const sumResult = contextOptimizer.shouldSummarize(session);
512
+ const compression = typeof contextOptimizer.shouldCompress === 'function'
513
+ ? contextOptimizer.shouldCompress(session)
514
+ : { ...contextOptimizer.shouldSummarize(session), mode: 'summarization' };
480
515
  return c.json({
481
516
  sliding_window: swResult,
482
517
  summarization: sumResult,
518
+ compression,
483
519
  summarization_pending: session.summarizationPending,
484
520
  });
485
521
  });
@@ -506,90 +542,9 @@ attachments) {
506
542
  }
507
543
  return c.json({ success: true });
508
544
  });
509
- // ===== Sticky Notes =====
510
- // GET /api/v2/sessions/:id/notes — список заметок
511
- // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
512
- app.get('/:id/notes', kit.requireAuth, async (c) => {
513
- const session = await sessionManager.getSession(c.req.param('id'));
514
- if (!session) {
515
- return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
516
- }
517
- // Доступ — у единого prefix-guard'а выше (владелец/elevated/роль в проекте).
518
- return c.json({ notes: session.stickyNotes });
519
- });
520
- // POST /api/v2/sessions/:id/notes — создать заметку
521
- // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
522
- app.post('/:id/notes', kit.requireAuth, async (c) => {
523
- const session = await sessionManager.getSession(c.req.param('id'));
524
- if (!session) {
525
- return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
526
- }
527
- // Доступ — у единого prefix-guard'а выше (владелец/elevated/роль в проекте).
528
- const body = await c.req.json().catch(() => ({}));
529
- if (!body.content?.trim()) {
530
- return c.json({ error: { code: 'VALIDATION_ERROR', message: 'Content is required' } }, 400);
531
- }
532
- const now = nowISO();
533
- const note = {
534
- id: generateStreamId(),
535
- content: body.content.trim(),
536
- createdAt: now,
537
- updatedAt: now,
538
- disabled: false,
539
- };
540
- await sessionManager.withLock(c.req.param('id'), async (s) => {
541
- s.stickyNotes.push(note);
542
- await sessionManager.saveSession(s);
543
- });
544
- const updated = await sessionManager.getSession(c.req.param('id'));
545
- eventBus.publish(c.req.param('id'), 'context.sticky_note_added', { note_id: note.id });
546
- return c.json({ note, notes: updated.stickyNotes }, 201);
547
- });
548
- // PATCH /api/v2/sessions/:id/notes/:noteId — обновить заметку
549
- // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
550
- app.patch('/:id/notes/:noteId', kit.requireAuth, async (c) => {
551
- const session = await sessionManager.getSession(c.req.param('id'));
552
- if (!session) {
553
- return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
554
- }
555
- // Доступ — у единого prefix-guard'а выше (владелец/elevated/роль в проекте).
556
- const body = await c.req.json().catch(() => ({}));
557
- const noteId = c.req.param('noteId');
558
- await sessionManager.withLock(c.req.param('id'), async (s) => {
559
- const note = s.stickyNotes.find((n) => n.id === noteId);
560
- if (!note)
561
- throw new Error('Note not found');
562
- if (body.content !== undefined)
563
- note.content = body.content;
564
- if (body.disabled !== undefined)
565
- note.disabled = body.disabled;
566
- note.updatedAt = nowISO();
567
- await sessionManager.saveSession(s);
568
- });
569
- const updated = await sessionManager.getSession(c.req.param('id'));
570
- eventBus.publish(c.req.param('id'), 'context.sticky_note_updated', { note_id: noteId });
571
- return c.json({ notes: updated.stickyNotes });
572
- });
573
- // DELETE /api/v2/sessions/:id/notes/:noteId — удалить заметку
574
- // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
575
- app.delete('/:id/notes/:noteId', kit.requireAuth, async (c) => {
576
- const session = await sessionManager.getSession(c.req.param('id'));
577
- if (!session) {
578
- return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
579
- }
580
- // Доступ — у единого prefix-guard'а выше (владелец/elevated/роль в проекте).
581
- const noteId = c.req.param('noteId');
582
- await sessionManager.withLock(c.req.param('id'), async (s) => {
583
- s.stickyNotes = s.stickyNotes.filter((n) => n.id !== noteId);
584
- await sessionManager.saveSession(s);
585
- });
586
- const updated = await sessionManager.getSession(c.req.param('id'));
587
- eventBus.publish(c.req.param('id'), 'context.sticky_note_deleted', { note_id: noteId });
588
- return c.json({ notes: updated.stickyNotes });
589
- });
590
545
  // Общая логика — в core-фабрике (backend-специфика выше). Регистрируем её
591
546
  // последней: статические/backend-only сегменты должны матчиться раньше.
592
- app.route('/', createCoreSessionRoutes({ requireAuth: kit.requireAuth }, { sessionManager, eventBus, queueManager, processMessage, orchestrator, contextOptimizer, projectStore, profilesStore, requestSessionService, analytics, ...(memory ? { memory } : {}), ...(questionService ? { questionService } : {}), ...(worktreeService ? { worktreeService } : {}), ...(attachments ? { attachments } : {}) }, {
547
+ app.route('/', createCoreSessionRoutes({ requireAuth: kit.requireAuth }, { sessionManager, eventBus, queueManager, processMessage, orchestrator, contextOptimizer, projectStore, profilesStore, requestSessionService, analytics, ...(memory ? { memory } : {}), ...(questionService ? { questionService } : {}), ...(worktreeService ? { worktreeService } : {}), ...(attachments ? { attachments } : {}), ...(backgroundService ? { backgroundService } : {}), ...(approvalRegistry ? { approvalRegistry } : {}), ...(llmAvailability ? { llmAvailability } : {}) }, {
593
548
  resolveUserId: async (c) => (await kit.getCurrentUser(c)).id,
594
549
  resolveOwner: async (c) => (await kit.getCurrentUser(c)).id,
595
550
  forkWithOwner: true,
@@ -613,16 +568,23 @@ attachments) {
613
568
  return projects.map((p) => p.id);
614
569
  },
615
570
  resolveAuthor: async (c) => (await kit.getCurrentUser(c)).username,
616
- promptMessageId: 'stream',
571
+ // ADR-106 Ф3: принципал ответа на подтверждение — аутентифицированный
572
+ // пользователь запроса (клиенту не доверяем) и его роли инстанса.
573
+ resolvePermissionResponder: async (c) => {
574
+ const user = await kit.getCurrentUser(c);
575
+ return { kind: 'user', id: user?.id ?? '', roles: user?.roles ?? [] };
576
+ },
617
577
  publishRenamed: false,
618
578
  publishDeletedBefore: false,
579
+ // Instance-wide лимиты заметок сессии (`context.stickyNotes`): роуты
580
+ // заметок — в core-фабрике, лимиты читаются резолвером (live).
581
+ ...(getStickyNoteLimits ? { getStickyNoteLimits } : {}),
619
582
  onSessionCreated: (userId, sessionId) => { void eventHub.subscribeToSession(userId, sessionId).catch((e) => console.warn('subscribeToSession failed:', e)); },
620
583
  onSessionDeleted: (userId, sessionId) => { eventHub.unsubscribeFromSession(userId, sessionId); },
621
584
  onSessionForked: (userId, sessionId) => { void eventHub.subscribeToSession(userId, sessionId).catch((e) => console.warn('subscribeToSession failed:', e)); },
622
585
  promptMiddleware: [createRateLimiter(30, 60_000)],
623
586
  forkMiddleware: [forkRateLimit],
624
587
  mergeMiddleware: [mergeRateLimit],
625
- enableSessionEvents: false,
626
588
  resolveDefaultAgent,
627
589
  // ADR-036: право видеть РЕАЛЬНЫЕ значения секретов (плейсхолдер → значение)
628
590
  // в обычном чтении сессии (`GET /sessions/:id`, `GET /sessions/:id/messages`,
@@ -651,6 +613,13 @@ attachments) {
651
613
  contentRequired: (c) => t('errors.validation.contentRequired', undefined, c),
652
614
  queueFull: (c, max) => t('errors.chat.queueFull', { max }, c),
653
615
  steerLimitExceeded: (c, max) => t('errors.chat.steerLimitExceeded', { max }, c),
616
+ // Отключённые провайдер/модель — понятные 400 до постановки в очередь.
617
+ providerDisabled: (c, provider) => t('errors.chat.providerDisabled', { provider }, c),
618
+ modelDisabled: (c, provider, model) => t('errors.chat.modelDisabled', { provider, model }, c),
619
+ // Лимиты заметок сессии (`context.stickyNotes`) — instance-wide.
620
+ noteNotFound: (c) => t('errors.notFound.note', undefined, c),
621
+ noteLimitReached: (c, max) => t('errors.conflict.noteLimitReached', { max }, c),
622
+ noteTooLong: (c, max) => t('errors.validation.noteTooLong', { max }, c),
654
623
  },
655
624
  }));
656
625
  return app;
package/package.json CHANGED
@@ -1,19 +1,19 @@
1
1
  {
2
2
  "name": "@itphx/synth-backend",
3
- "version": "0.12.4",
3
+ "version": "0.13.4",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "files": [
7
7
  "dist"
8
8
  ],
9
9
  "dependencies": {
10
- "@hono/node-server": "^1.18.0",
11
- "@itphx/synth-core": "0.12.4",
12
- "@itphx/synth-shared": "0.12.4",
10
+ "@hono/node-server": "^2.1.3",
11
+ "@itphx/synth-core": "0.13.4",
12
+ "@itphx/synth-shared": "0.13.4",
13
13
  "hono": "^4.9.0",
14
14
  "hono-rate-limiter": "^0.5.3",
15
15
  "jose": "^6.2.3",
16
- "js-yaml": "^4.1.1",
16
+ "js-yaml": "^4.3.2",
17
17
  "ws": "^8.20.1",
18
18
  "zod": "^4.6.7"
19
19
  },