@itphx/synth-backend 0.12.4 → 0.13.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/app/deps.d.ts +15 -1
  2. package/dist/app/deps.js +553 -34
  3. package/dist/app/listen.js +56 -7
  4. package/dist/app/mount-routes.js +273 -32
  5. package/dist/app/public-routes.d.ts +2 -0
  6. package/dist/app/public-routes.js +11 -0
  7. package/dist/app/sse-events.d.ts +4 -0
  8. package/dist/app/sse-events.js +53 -6
  9. package/dist/app.d.ts +3 -1
  10. package/dist/app.js +33 -0
  11. package/dist/auth/api-key.d.ts +19 -0
  12. package/dist/auth/api-key.js +56 -0
  13. package/dist/auth/middleware.js +7 -3
  14. package/dist/events/hub.d.ts +17 -0
  15. package/dist/events/hub.js +50 -15
  16. package/dist/init.d.ts +1 -0
  17. package/dist/init.js +96 -0
  18. package/dist/lib/app-config.d.ts +4 -0
  19. package/dist/lib/app-config.js +16 -3
  20. package/dist/lib/bind-host.d.ts +10 -0
  21. package/dist/lib/bind-host.js +32 -0
  22. package/dist/lib/defaults-store.d.ts +1 -1
  23. package/dist/lib/defaults-store.js +1 -1
  24. package/dist/lib/i18n.js +26 -0
  25. package/dist/lib/recalc-can-summarize.js +8 -3
  26. package/dist/main.js +7 -2
  27. package/dist/middleware/rate-limiter.d.ts +4 -1
  28. package/dist/middleware/rate-limiter.js +15 -2
  29. package/dist/routes/agents.js +1 -0
  30. package/dist/routes/auth.js +29 -16
  31. package/dist/routes/llm.js +92 -12
  32. package/dist/routes/mcp-remote.d.ts +23 -0
  33. package/dist/routes/mcp-remote.js +152 -0
  34. package/dist/routes/mcp.d.ts +11 -6
  35. package/dist/routes/mcp.js +35 -6
  36. package/dist/routes/messages.js +2 -0
  37. package/dist/routes/projects.d.ts +9 -3
  38. package/dist/routes/projects.js +32 -3
  39. package/dist/routes/providers.d.ts +4 -1
  40. package/dist/routes/providers.js +19 -99
  41. package/dist/routes/queue.d.ts +4 -1
  42. package/dist/routes/queue.js +4 -1
  43. package/dist/routes/sessions.d.ts +49 -9
  44. package/dist/routes/sessions.js +299 -256
  45. package/package.json +6 -6
  46. package/dist/routes/audit.d.ts +0 -17
  47. package/dist/routes/audit.js +0 -64
  48. package/dist/routes/context.d.ts +0 -4
  49. package/dist/routes/context.js +0 -93
  50. package/dist/routes/debug.d.ts +0 -3
  51. package/dist/routes/debug.js +0 -30
  52. package/dist/routes/gateway-patterns.d.ts +0 -9
  53. package/dist/routes/gateway-patterns.js +0 -57
  54. package/dist/routes/logs.d.ts +0 -24
  55. package/dist/routes/logs.js +0 -100
  56. package/dist/routes/mcp-registry.d.ts +0 -28
  57. package/dist/routes/mcp-registry.js +0 -483
@@ -5,6 +5,7 @@ import { createServer } from 'node:http';
5
5
  import { Readable } from 'node:stream';
6
6
  import { WebSocketServer } from 'ws';
7
7
  import { enqueueUserMessage, enqueueSteerMessage, isSessionVisible, parsePermissionPrincipal, resolveUserPrincipal } from '@itphx/synth-core';
8
+ import { MESSAGE_MODEL_QUERY_PARAM, MESSAGE_MODEL_UNSUPPORTED_CLOSE_CODE, MESSAGE_MODEL_UNSUPPORTED_REASON, isSupportedMessageModelParam, parseSinceParam, } from '@itphx/synth-core';
8
9
  import { nowISO, MessageRole, generateStreamId, isSteerMode, DEFAULT_STEER_MODE, MAX_STEER_INJECTIONS_PER_TURN, STEERING_ERROR_CODES } from '@itphx/synth-shared';
9
10
  import { t } from '../lib/i18n.js';
10
11
  /**
@@ -116,6 +117,21 @@ export function createBackendListen(deps) {
116
117
  const allSessions = user.id.startsWith('service:') || auth.hasRole({ get: () => user }, 'ADMIN', 'LEAD');
117
118
  wss.handleUpgrade(request, socket, head, (ws) => {
118
119
  const clientId = `ws-events-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
120
+ // ADR-118 §8: гейт минимальной версии клиента (fail-closed) —
121
+ // клиент обязан заявить модель сообщений (`messageModel=2`), иначе
122
+ // соединение не устанавливается.
123
+ if (!isSupportedMessageModelParam(url.searchParams.get(MESSAGE_MODEL_QUERY_PARAM))) {
124
+ try {
125
+ ws.close(MESSAGE_MODEL_UNSUPPORTED_CLOSE_CODE, MESSAGE_MODEL_UNSUPPORTED_REASON);
126
+ }
127
+ catch {
128
+ // ignore
129
+ }
130
+ return;
131
+ }
132
+ // ADR-118 §6: догон — клиент передаёт номер последнего виденного
133
+ // события (`since`).
134
+ const sinceSeq = parseSinceParam(url.searchParams.get('since'));
119
135
  // ADR-094: активное WS-соединение — в streams_active (не в гистограмме).
120
136
  const streams = deps.metrics?.gauge('synth_http_streams_active', 'Number of active long-lived streams (SSE/WebSocket).');
121
137
  streams?.inc();
@@ -126,19 +142,42 @@ export function createBackendListen(deps) {
126
142
  streamReleased = true;
127
143
  streams?.dec();
128
144
  };
145
+ /**
146
+ * ADR-118 §6: порядок «сначала журнал, потом живое». Пока идёт
147
+ * воспроизведение журнала, живые события копятся в буфере; уже
148
+ * отправленные номера (`sentSeq`) отсекают дубли.
149
+ */
150
+ let replaying = sinceSeq !== null;
151
+ const pending = [];
152
+ const sentSeq = new Map();
153
+ /** Отправить событие, если оно ещё не было отправлено (дедуп по `eventSeq`). */
154
+ const writeEvent = (event) => {
155
+ const seq = event.eventSeq;
156
+ if (typeof seq === 'number') {
157
+ const last = sentSeq.get(event.sessionId) ?? 0;
158
+ if (seq <= last)
159
+ return;
160
+ sentSeq.set(event.sessionId, seq);
161
+ }
162
+ try {
163
+ if (ws.readyState === ws.OPEN) {
164
+ ws.send(JSON.stringify(event));
165
+ }
166
+ }
167
+ catch {
168
+ // ignore send errors
169
+ }
170
+ };
129
171
  const client = {
130
172
  userId: user.id,
131
173
  username: user.username,
132
174
  allSessions,
133
175
  send(event) {
134
- try {
135
- if (ws.readyState === ws.OPEN) {
136
- ws.send(JSON.stringify(event));
137
- }
138
- }
139
- catch {
140
- // ignore send errors
176
+ if (replaying) {
177
+ pending.push(event);
178
+ return;
141
179
  }
180
+ writeEvent(event);
142
181
  },
143
182
  };
144
183
  eventHub.registerClient(client).then(() => {
@@ -147,6 +186,16 @@ export function createBackendListen(deps) {
147
186
  type: 'connected',
148
187
  client_id: clientId,
149
188
  }));
189
+ // ADR-118 §6: догон — журнал строго после `since`, затем живые
190
+ // события (буфер), без разрыва и без дублей.
191
+ if (sinceSeq !== null) {
192
+ for (const event of eventHub.replayForClient(client, sinceSeq))
193
+ writeEvent(event);
194
+ }
195
+ replaying = false;
196
+ for (const event of pending)
197
+ writeEvent(event);
198
+ pending.length = 0;
150
199
  }).catch(() => {
151
200
  ws.send(JSON.stringify({
152
201
  type: 'error',
@@ -6,9 +6,18 @@
6
6
  import { isAbsolute, join, normalize, resolve } from 'node:path';
7
7
  import { randomUUID } from 'node:crypto';
8
8
  import { DEFAULT_LLM_GATEWAY_RATE_LIMIT, ProjectRole, SYNTH_VERSION, resolveSecretKey, resolveStorageBackend, resolvePostgresConfig, resolvePostgresPassword } from '@itphx/synth-shared';
9
- import { DEFAULT_AGENT_ID, RateLimiter, getPublicOpenApiDocument, createFsRoutes, createGitRoutes, createSshKeyRoutes, createAgentSshKeyRoutes, createEventRoutes, createSchedulerRoutes, createServiceKeyRoutes, createWebhookRoutes, mergeLlmGatewayConfig, mergeSecurityConfig, mergePluginsConfig, createSkillRoutes, createCommandRoutes, createSkillBundleRoutes, createSessionSkillScopeRoutes, createProjectSkillScopeRoutes, createSkillSettingsRoutes, createIdentityRoutes, createMaintenanceRoutes, createAnalyticsRoutes, AnalyticsService, createProjectPortableRoutes, createStorageContextAsync, ProjectInstructionsResolver, createInstructionsInfoResolver, createSettingsRoutes, createDictionaryRoutes, createAuditRoutes as createSecurityAuditRoutes, currentEgressLog, createContextRoutes as createCoreContextRoutes, createMetricsSettingsRoutes,
9
+ import { DEFAULT_AGENT_ID, RateLimiter, resolveAgentRoleAlias, getPublicOpenApiDocument, createFsRoutes, createGitRoutes, createSshKeyRoutes, createAgentSshKeyRoutes, createEventRoutes, createSchedulerRoutes, createServiceKeyRoutes, createWebhookRoutes, mergeLlmGatewayConfig, mergeSecurityConfig, mergePluginsConfig, createSkillRoutes, createCommandRoutes, createSkillBundleRoutes, createSessionSkillScopeRoutes, createProjectSkillScopeRoutes, createSkillSettingsRoutes, createIdentityRoutes, createMaintenanceRoutes, createAnalyticsRoutes, AnalyticsService, createProjectPortableRoutes, createStorageContextAsync, ProjectInstructionsResolver, createInstructionsInfoResolver, createSettingsRoutes, createDictionaryRoutes, createAuditRoutes, currentEgressLog,
10
+ // ADR-036/ADR-095: логи, аудит LLM Gateway, regex-паттерны, файлы контекста
11
+ // и группы логирования — core-фабрики (backend передаёт RBAC/i18n через opts).
12
+ createLogsRoutes, resolveLogDir, createGatewayPatternsRoutes, createContextFileRoutes, createDebugRoutes, createContextRoutes as createCoreContextRoutes, createMetricsSettingsRoutes,
13
+ // ADR-133: обновления — проверка по каналам, SSE-установка и тумблер автопроверки.
14
+ createUpdateRoutes, createUpdatesSettingsRoutes,
10
15
  // ADR-115: админ-раздел «Вложения» — runtime-настройки мультимодального ввода.
11
- createAttachmentsSettingsRoutes, createModalityModelLookup, createStagingAttachmentRoutes, AttachmentService, createPacksRoutes, createPipelinesRoutes, createPipelineProjectRoutes, createProcessRoutes, createPluginsRoutes, createPluginSettingsRoutes, createMemoryRoutes, MEMORY_PLUGIN_NAME, MemoryProviderUnavailableError, executeToolDef, createOAuthRoutes, bindCredentialToConnector, syncMcpManagerFromRegistry, resolveProjectWorkspace, resolvePluginServerPolicy, } from '@itphx/synth-core';
16
+ createAttachmentsSettingsRoutes, createModalityModelLookup, createContextWindowSettingsRoutes, createAgentsLimitsSettingsRoutes,
17
+ // Лимит тяжёлых операций с сессиями (`limits.sessionOpsPerMinute`).
18
+ createRequestLimitsSettingsRoutes, createContextDefaultsSettingsRoutes, createStickyNotesSettingsRoutes, createSshSettingsRoutes, createStagingAttachmentRoutes, AttachmentService, createPacksRoutes, createPipelinesRoutes, createPipelineProjectRoutes, createProcessRoutes, createPluginsRoutes, createPluginSettingsRoutes, createMemoryRoutes, MEMORY_PLUGIN_NAME, MemoryProviderUnavailableError, executeToolDef,
19
+ // ADR-118 §8: возможности инстанса (`GET /api/v2/meta`).
20
+ createMetaRoutes, createOAuthRoutes, bindCredentialToConnector, syncMcpManagerFromRegistry, createProjectPlanRoutes, createProjectLogRoutes, resolveProjectWorkspace, resolvePluginServerPolicy, } from '@itphx/synth-core';
12
21
  import { createProjectRoutes, createProjectAccess } from '../routes/projects.js';
13
22
  import { createBackendProcessAccess } from '../routes/processes.js';
14
23
  import { createSessionRoutes } from '../routes/sessions.js';
@@ -18,12 +27,7 @@ import { createProviderRoutes } from '../routes/providers.js';
18
27
  import { createModelRoutes } from '../routes/models.js';
19
28
  import { createAgentRoutes } from '../routes/agents.js';
20
29
  import { createMcpRoutes } from '../routes/mcp.js';
21
- import { createContextRoutes as createContextFileRoutes } from '../routes/context.js';
22
- import { createDebugRoutes } from '../routes/debug.js';
23
30
  import { createUserRoutes } from '../routes/users.js';
24
- import { createAuditRoutes } from '../routes/audit.js';
25
- import { createLogsRoutes, resolveLogDir } from '../routes/logs.js';
26
- import { createGatewayPatternsRoutes } from '../routes/gateway-patterns.js';
27
31
  import { createLlmRoutes } from '../routes/llm.js';
28
32
  import { createRateLimiter } from '../middleware/rate-limiter.js';
29
33
  import { scopeGuard, serviceProjectProjection } from '../auth/service-scope.js';
@@ -57,8 +61,43 @@ export function mountBackendRoutes(app, auth, ctx) {
57
61
  // ADR-052 (этап I): публичный OpenAPI-документ (spike) за requireAuth;
58
62
  // публичную выдачу без auth согласуем отдельно.
59
63
  app.get('/api/v2/openapi.json', auth.requireAuth, (c) => c.json(getPublicOpenApiDocument()));
64
+ // RBAC-хелперы проекта (ADR-089 §5.5/§5.8): владелец/участник/LEAD/ADMIN.
65
+ // Объявлены до монтирования проектов — их используют и контур плана/журнала
66
+ // (PROP-054), и FS/git-роуты.
67
+ const projectAccess = createProjectAccess(auth);
60
68
  // Projects routes
61
- app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore, deps.worktreeService));
69
+ app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore, deps.worktreeService, eventBus));
70
+ // PROP-054: точечные операции плана проекта (`/projects/:id/plan*`) —
71
+ // core-фабрика, RBAC — те же правила проекта (чтение — право чтения,
72
+ // мутации — право изменения содержимого; `VIEWER` читает, но не мутирует).
73
+ app.route('/api/v2/projects', createProjectPlanRoutes({ requireAuth: auth.requireAuth }, projectStore, {
74
+ canRead: async (c, project, userId) => projectAccess.canReadProject(c, project, userId),
75
+ canEditContent: async (c, project, userId) => projectAccess.canEditProjectContent(c, project, userId),
76
+ getCurrentUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
77
+ messages: {
78
+ notFound: (c) => t('errors.notFound.project', undefined, c),
79
+ forbidden: (c) => t('auth.forbidden', undefined, c),
80
+ invalidBody: (c) => t('errors.validation.invalidPlanBody', undefined, c),
81
+ remoteUnavailable: (c) => t('errors.unavailable.remoteProject', undefined, c),
82
+ },
83
+ sessionManager,
84
+ eventBus,
85
+ }));
86
+ // PROP-054: журнал проекта и инварианты (`/projects/:id/log*`,
87
+ // `/projects/:id/invariants`). Журнал вынесен из детали проекта.
88
+ app.route('/api/v2/projects', createProjectLogRoutes({ requireAuth: auth.requireAuth }, projectStore, {
89
+ canRead: async (c, project, userId) => projectAccess.canReadProject(c, project, userId),
90
+ canEditContent: async (c, project, userId) => projectAccess.canEditProjectContent(c, project, userId),
91
+ getCurrentUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
92
+ messages: {
93
+ notFound: (c) => t('errors.notFound.project', undefined, c),
94
+ forbidden: (c) => t('auth.forbidden', undefined, c),
95
+ invalidBody: (c) => t('errors.validation.invalidLogBody', undefined, c),
96
+ remoteUnavailable: (c) => t('errors.unavailable.remoteProject', undefined, c),
97
+ },
98
+ sessionManager,
99
+ eventBus,
100
+ }));
62
101
  // ADR-091 (этап 2): портативный экспорт/импорт проекта (скачать/загрузить архив).
63
102
  // Managed RBAC: скачивание — право чтения проекта (owner/участник/LEAD/ADMIN),
64
103
  // импорт в существующий проект (`mergeInto`) — право редактирования; создание
@@ -122,7 +161,7 @@ export function mountBackendRoutes(app, auth, ctx) {
122
161
  },
123
162
  // Этап 1 roadmap 0.13 (блок 3): сервис «вопрос пользователю» (`ask_user`).
124
163
  deps.questionService,
125
- // ADR-114: сервис worktree'ов — привязка сессии к worktree
164
+ // ADR-114: сервис worktree — привязка сессии к worktree
126
165
  // (`PATCH /api/v2/sessions/:id { worktreeId }`).
127
166
  deps.worktreeService,
128
167
  // ADR-115: вложения сообщений — blob-порт, учёт ссылок; лимиты читаются
@@ -131,23 +170,64 @@ export function mountBackendRoutes(app, auth, ctx) {
131
170
  blobs: deps.storageContext.blobs,
132
171
  blobRefs: deps.storageContext.blobRefs,
133
172
  config: () => deps.attachmentsSettings.getConfig(),
134
- }));
173
+ // ADR-115: серверные миниатюры (`?variant=thumb`).
174
+ thumbnails: deps.attachmentThumbnails,
175
+ },
176
+ // ADR-111 §detach: «Стоп» останавливает и живые дочерние прогоны
177
+ // (фоновые саб-агенты и их процессы) — решение 2026-10-28.
178
+ deps.backgroundService,
179
+ // ADR-106 Ф3: HTTP-ответ на подтверждение проходит через тот же реестр,
180
+ // что и WS-кадр `permission_reply`.
181
+ deps.approvalRegistry,
182
+ // Instance-wide лимиты заметок сессии (`context.stickyNotes`) — live-резолвер
183
+ // для core-фабрики (роуты заметок живут там).
184
+ () => deps.stickyNotesLimitsSettings.getLimits(),
185
+ // Отключённые провайдер/модель отклоняются до постановки в очередь
186
+ // (каталог — те же `providerCache`/`modelCache`, что у движка).
187
+ {
188
+ isProviderEnabled: (name) => {
189
+ const provider = providerCache.get(name);
190
+ return provider ? provider.enabled !== false : undefined;
191
+ },
192
+ isModelEnabled: (providerName, modelName) => {
193
+ let model = modelCache.get(`${providerName}/${modelName}`) ?? modelCache.get(modelName);
194
+ if (!model) {
195
+ for (const candidate of modelCache.values()) {
196
+ if (candidate.provider !== providerName)
197
+ continue;
198
+ if (candidate.name === modelName) {
199
+ model = candidate;
200
+ break;
201
+ }
202
+ }
203
+ }
204
+ return model ? model.enabled !== false : undefined;
205
+ },
206
+ },
207
+ // Лимит тяжёлых операций ресурса сессий (`limits.sessionOpsPerMinute`) —
208
+ // live-геттер: резолвится на каждый запрос (0 — без лимита).
209
+ () => deps.sessionOpsPerMinuteSettings.getValue()));
135
210
  // Messages routes
136
211
  app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus, projectStore,
137
212
  // ADR-115: удаление сообщения снимает ссылки на объекты вложений.
138
213
  deps.storageContext.blobRefs));
139
214
  // Queue routes
140
- app.route('/api/v2/queue', createQueueRoutes(auth, sessionManager, queueManager, eventBus, processMessage, projectStore));
215
+ app.route('/api/v2/queue', createQueueRoutes(auth, sessionManager, queueManager, eventBus, processMessage, projectStore,
216
+ // ADR-036: обфускация user-сообщения при /queue/:sessionId/steer.
217
+ (sessionId, message) => orchestrator.obfuscateUserMessageForHistory(sessionId, message)));
141
218
  // FS routes (ADR-075): core-фабрика, managed поверх workspace проекта.
142
219
  // ADR-089 (P0): доступ к проекту обязателен — иначе любой USER читал/писал бы
143
220
  // файлы чужого проекта по id (IDOR). Чтение — canRead, мутации — canEditContent.
144
- const projectAccess = createProjectAccess(auth);
145
221
  app.route('/api/v2/fs', createFsRoutes(auth, config.workspacesRoot, undefined, {
146
222
  requireProjectId: true,
147
223
  getOutsideRootPolicy: () => 'deny',
148
224
  getProtectedPathsPolicy: () => protectedPathsStore.getPolicy(),
149
225
  // Лимит загрузки: config/env (resolveMaxUploadBytes), иначе дефолт фабрики.
150
226
  maxUploadBytes: config.maxUploadBytes,
227
+ // Лимит чтения файла: config/env (resolveMaxReadBytes), иначе дефолт фабрики.
228
+ maxReadBytes: config.maxReadBytes,
229
+ // Лимит предпросмотра файла (GET /raw): config/env (resolveMaxPreviewBytes).
230
+ maxPreviewBytes: config.maxPreviewBytes,
151
231
  authorizeProject: async (c, projectId) => {
152
232
  const user = await auth.getCurrentUser(c);
153
233
  if (!user)
@@ -165,6 +245,22 @@ export function mountBackendRoutes(app, auth, ctx) {
165
245
  outsideRootPolicy: () => 'deny',
166
246
  strict: true,
167
247
  }),
248
+ // ADR-118 §4: HTTP-мутация workspace — `fs.changed` в канал сессий проекта.
249
+ onFsChanged: async (projectId, change) => {
250
+ const sessions = await sessionManager.listSessions({ projectId });
251
+ for (const s of sessions) {
252
+ eventBus.publish(s.id, 'fs.changed', {
253
+ session_id: s.id,
254
+ project_id: projectId,
255
+ scope: change.scope,
256
+ ...(change.paths ? { paths: change.paths } : {}),
257
+ ...(change.op ? { op: change.op } : {}),
258
+ ...(change.from ? { from: change.from } : {}),
259
+ ...(change.to ? { to: change.to } : {}),
260
+ source: 'http',
261
+ });
262
+ }
263
+ },
168
264
  }));
169
265
  // Providers routes
170
266
  app.route('/api/v2/providers', createProviderRoutes(auth, providerStore, providerCache, {
@@ -180,8 +276,14 @@ export function mountBackendRoutes(app, auth, ctx) {
180
276
  // ADR-046/ADR-089: ролевой промпт агента (`role_prompt` в теле POST)
181
277
  // пишется портом файлов контекста — `{dataDir}/context/roles/<contextFile>`.
182
278
  app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, agentRegistry, getDefaultAgentId, contextConfig));
183
- // Context routes (глобальные identity-файлы; админ-мутации)
184
- app.route('/api/v2/context', createContextFileRoutes(auth, contextConfig));
279
+ // Context routes (файлы контекста/промптов инстанца; админ-мутации) — core-фабрика.
280
+ app.route('/api/v2/context', createContextFileRoutes(auth, contextConfig, {
281
+ adminGuard: auth.requireAdmin,
282
+ messages: {
283
+ fileNotFound: (c) => t('errors.notFound.file', undefined, c),
284
+ expectedFilesArray: (c) => t('errors.validation.expectedFilesArray', undefined, c),
285
+ },
286
+ }));
185
287
  // User admin routes
186
288
  app.route('/api/v2/users', createUserRoutes(auth, profilesStore));
187
289
  // Git routes (ADR-076 §T4): core-фабрика + managed RBAC. Write-эндпоинты
@@ -193,6 +295,13 @@ export function mountBackendRoutes(app, auth, ctx) {
193
295
  app.route('/api/v2/git', createGitRoutes(auth, projectStore, config.workspacesRoot, {
194
296
  sshKeyStore,
195
297
  execution: deps.executionPort,
298
+ // ADR-076: таймауты сетевых git-операций (`git.*` конфига; 0 — без таймаута).
299
+ ...(config.synth.git?.cloneTimeoutMs !== undefined
300
+ ? { cloneTimeoutMs: config.synth.git.cloneTimeoutMs }
301
+ : {}),
302
+ ...(config.synth.git?.fetchTimeoutMs !== undefined
303
+ ? { fetchTimeoutMs: config.synth.git.fetchTimeoutMs }
304
+ : {}),
196
305
  authorizeProject: async (c, projectId) => {
197
306
  const user = await auth.getCurrentUser(c);
198
307
  if (!user)
@@ -457,6 +566,81 @@ export function mountBackendRoutes(app, auth, ctx) {
457
566
  readGuard: auth.requirePermission('ADMIN'),
458
567
  writeGuard: auth.requirePermission('ADMIN'),
459
568
  }));
569
+ // Политика ограничения контекстного окна (`context.windowPolicy`):
570
+ // instance-wide (`off` | `warn` | `enforce`), применяется сразу. Managed
571
+ // RBAC — ADMIN (чтение и запись): это политика инстанса.
572
+ app.route('/api/v2/settings', createContextWindowSettingsRoutes({ requireAuth: auth.requireAuth }, {
573
+ settingsStore,
574
+ config: config.synth.context?.windowPolicy,
575
+ live: deps.contextWindowSettings,
576
+ securityAudit,
577
+ env: process.env,
578
+ }, {
579
+ readGuard: auth.requirePermission('ADMIN'),
580
+ writeGuard: auth.requirePermission('ADMIN'),
581
+ }));
582
+ // Бюджет промпта саб-агента (`agents.subagentMaxInputTokens`): instance-wide,
583
+ // 0 — без лимита; применяется к следующим прогонам без рестарта. Managed — ADMIN.
584
+ app.route('/api/v2/settings', createAgentsLimitsSettingsRoutes({ requireAuth: auth.requireAuth }, {
585
+ settingsStore,
586
+ config: config.synth.agents.subagentMaxInputTokens,
587
+ live: deps.subagentMaxInputTokensSettings,
588
+ securityAudit,
589
+ env: process.env,
590
+ }, {
591
+ readGuard: auth.requirePermission('ADMIN'),
592
+ writeGuard: auth.requirePermission('ADMIN'),
593
+ }));
594
+ // Лимит тяжёлых операций с сессиями (`limits.sessionOpsPerMinute`):
595
+ // instance-wide, `0` — без лимита; лимитеры читают резолвер на каждый запрос,
596
+ // поэтому runtime-настройка применяется без рестарта. Managed — ADMIN.
597
+ app.route('/api/v2/settings', createRequestLimitsSettingsRoutes({ requireAuth: auth.requireAuth }, {
598
+ settingsStore,
599
+ config: config.synth.limits.sessionOpsPerMinute,
600
+ live: deps.sessionOpsPerMinuteSettings,
601
+ securityAudit,
602
+ env: process.env,
603
+ }, {
604
+ readGuard: auth.requirePermission('ADMIN'),
605
+ writeGuard: auth.requirePermission('ADMIN'),
606
+ }));
607
+ // Дефолты оптимизации контекста для новых сессий (`context.defaults`):
608
+ // instance-wide, применяются при создании сессии. Managed RBAC — ADMIN
609
+ // (чтение и запись): это настройка инстанса.
610
+ app.route('/api/v2/settings', createContextDefaultsSettingsRoutes({ requireAuth: auth.requireAuth }, {
611
+ settingsStore,
612
+ config: config.synth.context?.defaults,
613
+ live: deps.contextDefaultsSettings,
614
+ securityAudit,
615
+ }, {
616
+ readGuard: auth.requirePermission('ADMIN'),
617
+ writeGuard: auth.requirePermission('ADMIN'),
618
+ }));
619
+ // Instance-wide лимиты заметок сессии (`context.stickyNotes`): instance-wide
620
+ // ограничения, применяются сразу (резолвер читается на операцию). Managed
621
+ // RBAC — ADMIN (чтение и запись): это настройка инстанса.
622
+ app.route('/api/v2/settings', createStickyNotesSettingsRoutes({ requireAuth: auth.requireAuth }, {
623
+ settingsStore,
624
+ config: config.synth.context?.stickyNotes,
625
+ live: deps.stickyNotesLimitsSettings,
626
+ securityAudit,
627
+ }, {
628
+ readGuard: auth.requirePermission('ADMIN'),
629
+ writeGuard: auth.requirePermission('ADMIN'),
630
+ }));
631
+ // PROP-124: режим инстанса для SSH-ключей (`ssh.mode`): `tools`|`agent`.
632
+ // Runtime-override, применяется сразу. Managed RBAC — ADMIN (чтение и
633
+ // запись): это настройка инстанса.
634
+ app.route('/api/v2/settings', createSshSettingsRoutes({ requireAuth: auth.requireAuth }, {
635
+ settingsStore,
636
+ config: config.synth.ssh?.mode,
637
+ live: deps.sshModeSettings,
638
+ securityAudit,
639
+ env: process.env,
640
+ }, {
641
+ readGuard: auth.requirePermission('ADMIN'),
642
+ writeGuard: auth.requirePermission('ADMIN'),
643
+ }));
460
644
  // ADR-115: staging-загрузка без сессии — `POST /api/v2/attachments`
461
645
  // (шлюзы принимают файл из внешнего канала, пайплайны — из шага). Managed:
462
646
  // `requireAuth` + scope-гейт service-key `events:ingest` (у шлюзов он уже
@@ -466,6 +650,7 @@ export function mountBackendRoutes(app, auth, ctx) {
466
650
  service: new AttachmentService({
467
651
  blobs: deps.storageContext.blobs,
468
652
  config: () => deps.attachmentsSettings.getConfig(),
653
+ thumbnails: deps.attachmentThumbnails,
469
654
  }),
470
655
  config: () => deps.attachmentsSettings.getConfig(),
471
656
  }, { guard: scopeGuard('events:ingest') }));
@@ -651,6 +836,9 @@ export function mountBackendRoutes(app, auth, ctx) {
651
836
  // MCP routes (единый реестр; legacy /servers — адаптеры над ним)
652
837
  app.route('/api/v2/mcp', createMcpRoutes(auth, mcpManager, sessionManager, {
653
838
  registry: mcpRegistryStore,
839
+ // Переподключение сервера (`POST /servers/:name/reconnect`) — снять и
840
+ // заново зарегистрировать MCP-инструменты в общем реестре.
841
+ toolRegistry,
654
842
  // Политика резолвится на каждый запрос (live; исключения/режим — из стора).
655
843
  getNetworkPolicy: () => egressResolver.resolveMcp(),
656
844
  // ADR-105 (Ф3): порт слоя внешних доступов — право привязать доступ
@@ -766,6 +954,12 @@ export function mountBackendRoutes(app, auth, ctx) {
766
954
  sessionManager, skillService, settingsStore, projectStore,
767
955
  permissionConfig: config.synth.permission,
768
956
  resolveProjectWorkspace: resolveSkillWorkspace,
957
+ // ADR-046 §6.3: capability-гейт сессии — по capabilities её агента
958
+ // (legacy-роль резолвится алиасом, как в рантайме оркестратора).
959
+ resolveAgentCapabilities: (role) => {
960
+ const resolved = role ? (resolveAgentRoleAlias(role) ?? role) : undefined;
961
+ return resolved ? agentRegistry.get(resolved)?.capabilities : undefined;
962
+ },
769
963
  }, {
770
964
  writeGuard: auth.requireAuth,
771
965
  resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
@@ -804,7 +998,10 @@ export function mountBackendRoutes(app, auth, ctx) {
804
998
  || project.ownerId === userId
805
999
  || project.members?.[userId] === ProjectRole.OWNER,
806
1000
  }));
807
- app.route('/api/v2/settings', createSkillSettingsRoutes(auth, { settingsStore }, {
1001
+ app.route('/api/v2/settings', createSkillSettingsRoutes(auth, {
1002
+ settingsStore,
1003
+ trustedProjectDirsDefaults: config.synth.skills.trustedProjectDirs ?? [],
1004
+ }, {
808
1005
  writeGuard: auth.requireAdmin,
809
1006
  onSkillsDisabledChange: (disabled) => orchestrator.setSkillsDisabled(disabled),
810
1007
  }));
@@ -835,22 +1032,36 @@ export function mountBackendRoutes(app, auth, ctx) {
835
1032
  unauthorized: (c) => t('auth.unauthorized', undefined, c),
836
1033
  },
837
1034
  }));
838
- // LLM Gateway audit routes (ADR-036) — GET только ADMIN/AUDITOR, POST /revealed — все авторизованные
1035
+ // LLM Gateway audit routes (ADR-036) — GET только ADMIN/AUDITOR, POST /revealed — все авторизованные.
1036
+ // Одна core-фабрика на весь префикс `/api/v2/audit`: голый аудит Gateway (`/`),
1037
+ // `POST /revealed`, журнал безопасности (`/security`) и журнал egress (`/egress`).
839
1038
  app.route('/api/v2/audit', createAuditRoutes(auth, {
840
- auditLogPath: gatewayAuditLogger.logPath,
841
- sessionExists: async (sessionId) => {
842
- const session = await sessionManager.getSession(sessionId);
843
- return session !== null;
1039
+ securityAudit,
1040
+ egressRequests,
1041
+ gatewayAudit: {
1042
+ auditLogPath: gatewayAuditLogger.logPath,
1043
+ sessionExists: async (sessionId) => {
1044
+ const session = await sessionManager.getSession(sessionId);
1045
+ return session !== null;
1046
+ },
1047
+ logger: gatewayAuditLogger,
844
1048
  },
845
- logger: gatewayAuditLogger,
1049
+ }, {
1050
+ readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
1051
+ gatewayReadGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
1052
+ revealedGuard: auth.requireAuth,
846
1053
  }));
847
1054
  // Логи сервисов (core/ui/backend) + полный лог запросов/ответов LLM — чтение, только ADMIN/AUDITOR
848
1055
  app.route('/api/v2/logs', createLogsRoutes(auth, {
849
1056
  logDir: resolveLogDir(),
850
1057
  payloadLogPath: gatewayPayloadLogPath,
1058
+ }, {
1059
+ readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
851
1060
  }));
852
1061
  // LLM Gateway patterns routes (ADR-036) — управление regex-паттернами детекции секретов, только ADMIN
853
- app.route('/api/v2/gateway', createGatewayPatternsRoutes(auth, patternStore));
1062
+ app.route('/api/v2/gateway', createGatewayPatternsRoutes(auth, patternStore, {
1063
+ adminGuard: auth.requireAdmin,
1064
+ }));
854
1065
  // LLM Proxy (гибридный режим, Часть 5) — OpenAI-совместимый POST /api/v2/llm/chat/completions.
855
1066
  // Локальный core гоняет LLM-запросы централизованно через LLM Gateway (ADR-036):
856
1067
  // обфускация/блокировка секретов, rate limit, аудит, полный payload-лог.
@@ -975,6 +1186,23 @@ export function mountBackendRoutes(app, auth, ctx) {
975
1186
  // События/decision наследуют тот же guard (если не заданы отдельно).
976
1187
  settingsWriteGuard: auth.requirePermission('ADMIN'),
977
1188
  }));
1189
+ // ADR-133: обновления (`/api/v2/updates`) — проверка по каналам и SSE-установка.
1190
+ // Managed RBAC: проверка и применение — только ADMIN (как обслуживание инстанса).
1191
+ // Admission-гейт внутри роута: в managed/Docker/K8s self-update → 409
1192
+ // `UPDATE_UNSUPPORTED` (обновление выполняется образом/выпуском).
1193
+ app.route('/api/v2/updates', createUpdateRoutes(auth, dataDir, {
1194
+ updates: config.synth.updates,
1195
+ audit: maintenanceAudit,
1196
+ }, {
1197
+ readGuard: auth.requirePermission('ADMIN'),
1198
+ writeGuard: auth.requirePermission('ADMIN'),
1199
+ }));
1200
+ // ADR-133: админ-раздел «Обновления» — runtime-тумблер автопроверки.
1201
+ // Managed RBAC: чтение и запись — только ADMIN.
1202
+ app.route('/api/v2/settings', createUpdatesSettingsRoutes({ requireAuth: auth.requireAuth }, { settingsStore, config: config.synth.updates, env: process.env }, {
1203
+ readGuard: auth.requirePermission('ADMIN'),
1204
+ writeGuard: auth.requirePermission('ADMIN'),
1205
+ }));
978
1206
  // ADR-094: админ-раздел «Наблюдаемость» — runtime `metrics.enabled` (рестарт),
979
1207
  // live-статус и bearer-токен `/metrics` (write-only, применяется сразу).
980
1208
  // Managed RBAC: чтение и мутации — только ADMIN.
@@ -992,14 +1220,8 @@ export function mountBackendRoutes(app, auth, ctx) {
992
1220
  readGuard: auth.requirePermission('ADMIN'),
993
1221
  writeGuard: auth.requirePermission('ADMIN'),
994
1222
  }));
995
- // Журналы безопасности: аудит изменений политик + внешние запросы (egress).
996
- // Managed RBAC: чтение только ADMIN/AUDITOR.
997
- app.route('/api/v2/audit', createSecurityAuditRoutes(auth, {
998
- securityAudit,
999
- egressRequests,
1000
- }, {
1001
- readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
1002
- }));
1223
+ // Журналы безопасности (аудит политик + egress) и голый аудит LLM Gateway
1224
+ // смонтированы **одной** core-фабрикой выше (префикс `/api/v2/audit`).
1003
1225
  // ADR-102 (волна 1): отчёты аналитики — только чтение, данных без локализации.
1004
1226
  // Managed RBAC (§7): ADMIN/LEAD — сквозной обзор; AUDITOR — чтение всех отчётов;
1005
1227
  // обычный USER — принудительный фильтр оси `user` по себе (+ 403 на `decision`/`summary`).
@@ -1029,7 +1251,7 @@ export function mountBackendRoutes(app, auth, ctx) {
1029
1251
  config: config.synth.instructions,
1030
1252
  dictionaryStore: dictionaries,
1031
1253
  dataDir,
1032
- trustedProjectDirs: config.synth.skills.trustedProjectDirs,
1254
+ trustedProjectDirs: deps.skillsTrustedProjectDirs,
1033
1255
  // ADR-069 R3: авто-trust workspace внутри workspacesRoot (managed-каталоги).
1034
1256
  workspacesRoot: config.workspacesRoot,
1035
1257
  // ADR-077: `git rev-parse` — через порт исполнения (тот же, что у тулов).
@@ -1052,8 +1274,27 @@ export function mountBackendRoutes(app, auth, ctx) {
1052
1274
  || project.ownerId === userId
1053
1275
  || project.members?.[userId] === ProjectRole.OWNER,
1054
1276
  }));
1277
+ // ADR-118 §8: возможности инстанса (`GET /api/v2/meta`) — **без
1278
+ // аутентификации** (как `GET /health`): публичная информация о протоколе,
1279
+ // по ней клиент сверяет модель сообщений (fail-closed гейт транспорта).
1280
+ app.route('/api/v2', createMetaRoutes({
1281
+ getAttachments: () => deps.attachmentsSettings.getConfig(),
1282
+ // PROP-125: сервер гибрида умеет удалённый MCP (`/api/v2/mcp/remote/*`
1283
+ // и relay) — клиент читает признак из `/api/v2/meta`.
1284
+ // `users: true` — маршрут `/api/v2/users*` (управление пользователями)
1285
+ // смонтирован в backend (`src/routes/users.ts`), поэтому контур есть
1286
+ // всегда; в core standalone его нет, а в core в гибриде он есть лишь
1287
+ // пока подключён удалённый backend (там — прокси).
1288
+ getFeatures: () => ({ remoteMcp: true, users: true }),
1289
+ }));
1055
1290
  // Глобальный SSE-хаб для всех сессий пользователя (ADR-052: `events:watch`).
1056
1291
  registerEventsSse(app, { auth, eventHub, scopeGuard });
1057
1292
  // Admin routes (кроме graceful shutdown — он живёт в main.ts, т.к. требует server)
1058
- app.route('/api/v2/admin/debug', createDebugRoutes(auth));
1293
+ app.route('/api/v2/admin/debug', createDebugRoutes(auth, {
1294
+ adminGuard: auth.requireAdmin,
1295
+ messages: {
1296
+ groupsRequired: (c) => t('errors.validation.groupsRequired', undefined, c),
1297
+ generic: (c) => t('errors.generic', undefined, c),
1298
+ },
1299
+ }));
1059
1300
  }
@@ -0,0 +1,2 @@
1
+ export { PUBLIC_API_V2_PATHS, isPublicApiV2Path } from '@itphx/synth-core';
2
+ export type { PublicApiRoute } from '@itphx/synth-core';
@@ -0,0 +1,11 @@
1
+ // F6 (аудит §6.1): allowlist публичных эндпоинтов `/api/v2/*`.
2
+ //
3
+ // Реализация перенесена в core (`packages/core/src/server/app/public-routes.ts`):
4
+ // общая логика HTTP живёт в core (ADR-017/ADR-018), а allowlist должен быть
5
+ // **один** для обеих сборок (standalone и managed) — иначе публичность
6
+ // `/api/v2/meta`/`/api/v2/health` разъехалась бы между ними.
7
+ //
8
+ // Здесь оставлен тонкий реэкспорт, чтобы существующие импорты
9
+ // (`./app/public-routes.js` в `src/app.ts` и `src/app/route-access-census.test.ts`)
10
+ // не менялись. См. `@itphx/synth-core`.
11
+ export { PUBLIC_API_V2_PATHS, isPublicApiV2Path } from '@itphx/synth-core';
@@ -11,5 +11,9 @@ export interface EventsSseDeps {
11
11
  /**
12
12
  * Зарегистрировать SSE-хаб (`GET /api/v2/events`): подписка на события сессий
13
13
  * пользователя (watch-all — для service-key и ADMIN/LEAD, ADR-052 этап IV).
14
+ *
15
+ * ADR-118 §6/§8: кадр несёт `id:` (глобальный номер события) — по нему
16
+ * работает догон (`Last-Event-ID` / `?since`); клиент обязан заявить модель
17
+ * сообщений (`messageModel=2`) — иначе поток не устанавливается (fail-closed).
14
18
  */
15
19
  export declare function registerEventsSse(app: Hono, deps: EventsSseDeps): void;