@itphx/synth-backend 0.11.3 → 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.
Files changed (40) hide show
  1. package/dist/app/deps.d.ts +37 -5
  2. package/dist/app/deps.js +1172 -37
  3. package/dist/app/listen.d.ts +7 -1
  4. package/dist/app/listen.js +182 -16
  5. package/dist/app/mount-routes.js +493 -12
  6. package/dist/app/sse-events.d.ts +4 -0
  7. package/dist/app/sse-events.js +53 -6
  8. package/dist/app.d.ts +30 -2
  9. package/dist/app.js +54 -8
  10. package/dist/auth/guards.d.ts +15 -0
  11. package/dist/auth/guards.js +37 -1
  12. package/dist/auth/plugin-scope.d.ts +10 -0
  13. package/dist/auth/plugin-scope.js +69 -0
  14. package/dist/events/hub.d.ts +17 -0
  15. package/dist/events/hub.js +46 -14
  16. package/dist/lib/app-config.d.ts +4 -0
  17. package/dist/lib/app-config.js +4 -2
  18. package/dist/lib/defaults-store.d.ts +1 -1
  19. package/dist/lib/defaults-store.js +2 -2
  20. package/dist/lib/i18n.js +123 -2
  21. package/dist/lib/recalc-can-summarize.js +8 -3
  22. package/dist/main.js +52 -3
  23. package/dist/routes/agents.d.ts +11 -2
  24. package/dist/routes/agents.js +15 -2
  25. package/dist/routes/auth.d.ts +11 -1
  26. package/dist/routes/auth.js +45 -3
  27. package/dist/routes/llm.js +29 -7
  28. package/dist/routes/mcp-registry.d.ts +13 -1
  29. package/dist/routes/mcp-registry.js +120 -19
  30. package/dist/routes/messages.d.ts +4 -2
  31. package/dist/routes/messages.js +7 -1
  32. package/dist/routes/processes.d.ts +34 -0
  33. package/dist/routes/processes.js +26 -0
  34. package/dist/routes/projects.d.ts +14 -2
  35. package/dist/routes/projects.js +28 -1
  36. package/dist/routes/queue.d.ts +4 -1
  37. package/dist/routes/queue.js +4 -1
  38. package/dist/routes/sessions.d.ts +74 -6
  39. package/dist/routes/sessions.js +85 -93
  40. package/package.json +6 -6
@@ -3,10 +3,16 @@
3
3
  // определяет приоритеты маршрутов (статические сегменты раньше параметрических,
4
4
  // SSE-хаб `/api/v2/events` после роутов событий, но до admin-роутов).
5
5
  // Вынесено из `app.ts` (ADR-095, шаг 4b) — «вынос по швам», без изменения поведения.
6
- import { isAbsolute, normalize, resolve } from 'node:path';
6
+ import { isAbsolute, join, normalize, resolve } from 'node:path';
7
+ import { randomUUID } from 'node:crypto';
7
8
  import { DEFAULT_LLM_GATEWAY_RATE_LIMIT, ProjectRole, SYNTH_VERSION, resolveSecretKey, resolveStorageBackend, resolvePostgresConfig, resolvePostgresPassword } from '@itphx/synth-shared';
8
- import { DEFAULT_AGENT_ID, RateLimiter, getPublicOpenApiDocument, createFsRoutes, createGitRoutes, createSshKeyRoutes, createAgentSshKeyRoutes, createEventRoutes, createSchedulerRoutes, createServiceKeyRoutes, createWebhookRoutes, mergeLlmGatewayConfig, mergeSecurityConfig, createSkillRoutes, createCommandRoutes, createSkillBundleRoutes, createSessionSkillScopeRoutes, createProjectSkillScopeRoutes, createSkillSettingsRoutes, createIdentityRoutes, createMaintenanceRoutes, createAnalyticsRoutes, AnalyticsService, createProjectPortableRoutes, createStorageContextAsync, ProjectInstructionsResolver, createInstructionsInfoResolver, createSettingsRoutes, createDictionaryRoutes, createAuditRoutes as createSecurityAuditRoutes, currentEgressLog, createContextRoutes as createCoreContextRoutes, createMetricsSettingsRoutes, resolveProjectWorkspace, } from '@itphx/synth-core';
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,
10
+ // ADR-115: админ-раздел «Вложения» — runtime-настройки мультимодального ввода.
11
+ createAttachmentsSettingsRoutes, createModalityModelLookup, createContextWindowSettingsRoutes, createAgentsLimitsSettingsRoutes, createContextDefaultsSettingsRoutes, createStickyNotesSettingsRoutes, createStagingAttachmentRoutes, AttachmentService, createPacksRoutes, createPipelinesRoutes, createPipelineProjectRoutes, createProcessRoutes, createPluginsRoutes, createPluginSettingsRoutes, createMemoryRoutes, MEMORY_PLUGIN_NAME, MemoryProviderUnavailableError, executeToolDef,
12
+ // ADR-118 §8: возможности инстанса (`GET /api/v2/meta`).
13
+ createMetaRoutes, createOAuthRoutes, bindCredentialToConnector, syncMcpManagerFromRegistry, resolveProjectWorkspace, resolvePluginServerPolicy, } from '@itphx/synth-core';
9
14
  import { createProjectRoutes, createProjectAccess } from '../routes/projects.js';
15
+ import { createBackendProcessAccess } from '../routes/processes.js';
10
16
  import { createSessionRoutes } from '../routes/sessions.js';
11
17
  import { createMessageRoutes } from '../routes/messages.js';
12
18
  import { createQueueRoutes } from '../routes/queue.js';
@@ -23,7 +29,7 @@ import { createGatewayPatternsRoutes } from '../routes/gateway-patterns.js';
23
29
  import { createLlmRoutes } from '../routes/llm.js';
24
30
  import { createRateLimiter } from '../middleware/rate-limiter.js';
25
31
  import { scopeGuard, serviceProjectProjection } from '../auth/service-scope.js';
26
- import { requireAdminOrScope } from '../auth/guards.js';
32
+ import { requireAdminOrScope, requireAdminRoleOrScope } from '../auth/guards.js';
27
33
  import { t, getTranslations } from '../lib/i18n.js';
28
34
  import { registerEventsSse } from './sse-events.js';
29
35
  /**
@@ -32,7 +38,7 @@ import { registerEventsSse } from './sse-events.js';
32
38
  */
33
39
  export function mountBackendRoutes(app, auth, ctx) {
34
40
  const { config, deps } = ctx;
35
- const { dataDir, projectStore, sessionManager, eventBus, queueManager, processMessage, orchestrator, profilesStore, getDefaultAgentId, requestSessionService, contextOptimizer, protectedPathsStore, providerStore, providerCache, modelStore, modelCache, agentStore, agentRegistry, contextConfig, sshKeyStore, commandService, bundleStore, dictionaries, serviceApiKeyStore, eventIngress, eventBindingStore, eventJournal, routeRuleStore, eventApiKeyStore, schedulerService, scheduleStore, jobStore, webhookStore, webhookDeliveryStore, webhookService, webhooksConfig, eventHub, mcpManager, mcpRegistryStore, skillService, settingsStore, egressResolver, securityAudit, egressRequests, defaultWorkingDir, patternStore, toolRegistry, gatewayAuditLogger, gatewayPayloadLogPath, gatewayConfig, providerLoader, modelLoader, modelWindowLoader, resolveAgentTemplate, identityClaimStore, live, maintenanceAudit, analyticsRollups, analytics, metrics, } = deps;
41
+ const { dataDir, projectStore, sessionManager, eventBus, queueManager, processMessage, orchestrator, profilesStore, getDefaultAgentId, requestSessionService, contextOptimizer, protectedPathsStore, providerStore, providerCache, modelStore, modelCache, agentStore, agentRegistry, contextConfig, sshKeyStore, commandService, bundleStore, dictionaries, serviceApiKeyStore, eventIngress, eventBindingStore, eventJournal, routeRuleStore, eventApiKeyStore, schedulerService, scheduleStore, jobStore, webhookStore, webhookDeliveryStore, webhookService, webhooksConfig, eventHub, mcpManager, mcpRegistryStore, skillService, settingsStore, egressResolver, securityAudit, egressRequests, defaultWorkingDir, patternStore, toolRegistry, gatewayAuditLogger, gatewayPayloadLogPath, gatewayConfig, providerLoader, modelLoader, modelWindowLoader, resolveAgentTemplate, identityClaimStore, live, maintenanceAudit, analyticsRollups, analytics, metrics, pipelines, packs, } = deps;
36
42
  /**
37
43
  * Fallback-пара «модель по умолчанию» из config (`llm.defaultProvider` +
38
44
  * `llm.defaultModel`) — только если заданы оба.
@@ -54,7 +60,7 @@ export function mountBackendRoutes(app, auth, ctx) {
54
60
  // публичную выдачу без auth согласуем отдельно.
55
61
  app.get('/api/v2/openapi.json', auth.requireAuth, (c) => c.json(getPublicOpenApiDocument()));
56
62
  // Projects routes
57
- app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore));
63
+ app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore, deps.worktreeService, eventBus));
58
64
  // ADR-091 (этап 2): портативный экспорт/импорт проекта (скачать/загрузить архив).
59
65
  // Managed RBAC: скачивание — право чтения проекта (owner/участник/LEAD/ADMIN),
60
66
  // импорт в существующий проект (`mergeInto`) — право редактирования; создание
@@ -63,7 +69,7 @@ export function mountBackendRoutes(app, auth, ctx) {
63
69
  // (ADR-089, инвариант 18).
64
70
  app.route('/api/v2/projects', createProjectPortableRoutes({ requireAuth: auth.requireAuth }, {
65
71
  dataDir,
66
- // PROP-032: экспорт/импорт проекта работают через контекст хранения
72
+ // ADR-096: экспорт/импорт проекта работают через контекст хранения
67
73
  // инстанса (иначе — свой файловый контекст, а на `backend=postgres`
68
74
  // проект не найден бы).
69
75
  storage: deps.storageContext,
@@ -109,11 +115,66 @@ export function mountBackendRoutes(app, auth, ctx) {
109
115
  },
110
116
  }));
111
117
  // Sessions routes
112
- app.route('/api/v2/sessions', createSessionRoutes(auth, sessionManager, eventBus, queueManager, processMessage, orchestrator, eventHub, contextOptimizer, projectStore, profilesStore, getDefaultAgentId, requestSessionService, analytics));
118
+ app.route('/api/v2/sessions', createSessionRoutes(auth, sessionManager, eventBus, queueManager, processMessage, orchestrator, eventHub, contextOptimizer, projectStore, profilesStore, getDefaultAgentId, requestSessionService, analytics,
119
+ // ADR-107: агрегаты памяти сессии для вкладки «Память».
120
+ {
121
+ facts: deps.storageContext.memoryFacts,
122
+ indexes: deps.storageContext.memoryIndexes,
123
+ isPluginActive: () => deps.pluginRuntime.host.isActive(MEMORY_PLUGIN_NAME),
124
+ },
125
+ // Этап 1 roadmap 0.13 (блок 3): сервис «вопрос пользователю» (`ask_user`).
126
+ deps.questionService,
127
+ // ADR-114: сервис worktree'ов — привязка сессии к worktree
128
+ // (`PATCH /api/v2/sessions/:id { worktreeId }`).
129
+ deps.worktreeService,
130
+ // ADR-115: вложения сообщений — blob-порт, учёт ссылок; лимиты читаются
131
+ // резолвером на каждый запрос (runtime-настройки из админки без рестарта).
132
+ {
133
+ blobs: deps.storageContext.blobs,
134
+ blobRefs: deps.storageContext.blobRefs,
135
+ config: () => deps.attachmentsSettings.getConfig(),
136
+ // ADR-115: серверные миниатюры (`?variant=thumb`).
137
+ thumbnails: deps.attachmentThumbnails,
138
+ },
139
+ // ADR-111 §detach: «Стоп» останавливает и живые дочерние прогоны
140
+ // (фоновые саб-агенты и их процессы) — решение 2026-10-28.
141
+ deps.backgroundService,
142
+ // ADR-106 Ф3: HTTP-ответ на подтверждение проходит через тот же реестр,
143
+ // что и WS-кадр `permission_reply`.
144
+ deps.approvalRegistry,
145
+ // Instance-wide лимиты заметок сессии (`context.stickyNotes`) — live-резолвер
146
+ // для core-фабрики (роуты заметок живут там).
147
+ () => deps.stickyNotesLimitsSettings.getLimits(),
148
+ // Отключённые провайдер/модель отклоняются до постановки в очередь
149
+ // (каталог — те же `providerCache`/`modelCache`, что у движка).
150
+ {
151
+ isProviderEnabled: (name) => {
152
+ const provider = providerCache.get(name);
153
+ return provider ? provider.enabled !== false : undefined;
154
+ },
155
+ isModelEnabled: (providerName, modelName) => {
156
+ let model = modelCache.get(`${providerName}/${modelName}`) ?? modelCache.get(modelName);
157
+ if (!model) {
158
+ for (const candidate of modelCache.values()) {
159
+ if (candidate.provider !== providerName)
160
+ continue;
161
+ if (candidate.name === modelName) {
162
+ model = candidate;
163
+ break;
164
+ }
165
+ }
166
+ }
167
+ return model ? model.enabled !== false : undefined;
168
+ },
169
+ }));
113
170
  // Messages routes
114
- app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus, projectStore));
171
+ app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus, projectStore,
172
+ // ADR-115: удаление сообщения снимает ссылки на объекты вложений.
173
+ deps.storageContext.blobRefs));
115
174
  // Queue routes
116
- app.route('/api/v2/queue', createQueueRoutes(auth, sessionManager, queueManager, eventBus, processMessage, projectStore));
175
+ app.route('/api/v2/queue', createQueueRoutes(auth, sessionManager, queueManager, eventBus, processMessage, projectStore,
176
+ // ADR-036: обфускация user-сообщения при /queue/:sessionId/steer.
177
+ (sessionId, message) => orchestrator.obfuscateUserMessageForHistory(sessionId, message)));
117
178
  // FS routes (ADR-075): core-фабрика, managed поверх workspace проекта.
118
179
  // ADR-089 (P0): доступ к проекту обязателен — иначе любой USER читал/писал бы
119
180
  // файлы чужого проекта по id (IDOR). Чтение — canRead, мутации — canEditContent.
@@ -124,6 +185,10 @@ export function mountBackendRoutes(app, auth, ctx) {
124
185
  getProtectedPathsPolicy: () => protectedPathsStore.getPolicy(),
125
186
  // Лимит загрузки: config/env (resolveMaxUploadBytes), иначе дефолт фабрики.
126
187
  maxUploadBytes: config.maxUploadBytes,
188
+ // Лимит чтения файла: config/env (resolveMaxReadBytes), иначе дефолт фабрики.
189
+ maxReadBytes: config.maxReadBytes,
190
+ // Лимит предпросмотра файла (GET /raw): config/env (resolveMaxPreviewBytes).
191
+ maxPreviewBytes: config.maxPreviewBytes,
127
192
  authorizeProject: async (c, projectId) => {
128
193
  const user = await auth.getCurrentUser(c);
129
194
  if (!user)
@@ -141,6 +206,22 @@ export function mountBackendRoutes(app, auth, ctx) {
141
206
  outsideRootPolicy: () => 'deny',
142
207
  strict: true,
143
208
  }),
209
+ // ADR-118 §4: HTTP-мутация workspace — `fs.changed` в канал сессий проекта.
210
+ onFsChanged: async (projectId, change) => {
211
+ const sessions = await sessionManager.listSessions({ projectId });
212
+ for (const s of sessions) {
213
+ eventBus.publish(s.id, 'fs.changed', {
214
+ session_id: s.id,
215
+ project_id: projectId,
216
+ scope: change.scope,
217
+ ...(change.paths ? { paths: change.paths } : {}),
218
+ ...(change.op ? { op: change.op } : {}),
219
+ ...(change.from ? { from: change.from } : {}),
220
+ ...(change.to ? { to: change.to } : {}),
221
+ source: 'http',
222
+ });
223
+ }
224
+ },
144
225
  }));
145
226
  // Providers routes
146
227
  app.route('/api/v2/providers', createProviderRoutes(auth, providerStore, providerCache, {
@@ -153,7 +234,9 @@ export function mountBackendRoutes(app, auth, ctx) {
153
234
  setDefaultModel: (pair) => settingsStore.setDefaultModel(pair),
154
235
  }));
155
236
  // Agents routes
156
- app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, agentRegistry, getDefaultAgentId));
237
+ // ADR-046/ADR-089: ролевой промпт агента (`role_prompt` в теле POST)
238
+ // пишется портом файлов контекста — `{dataDir}/context/roles/<contextFile>`.
239
+ app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, agentRegistry, getDefaultAgentId, contextConfig));
157
240
  // Context routes (глобальные identity-файлы; админ-мутации)
158
241
  app.route('/api/v2/context', createContextFileRoutes(auth, contextConfig));
159
242
  // User admin routes
@@ -166,6 +249,14 @@ export function mountBackendRoutes(app, auth, ctx) {
166
249
  // читал бы git-данные чужого проекта по его id.
167
250
  app.route('/api/v2/git', createGitRoutes(auth, projectStore, config.workspacesRoot, {
168
251
  sshKeyStore,
252
+ execution: deps.executionPort,
253
+ // ADR-076: таймауты сетевых git-операций (`git.*` конфига; 0 — без таймаута).
254
+ ...(config.synth.git?.cloneTimeoutMs !== undefined
255
+ ? { cloneTimeoutMs: config.synth.git.cloneTimeoutMs }
256
+ : {}),
257
+ ...(config.synth.git?.fetchTimeoutMs !== undefined
258
+ ? { fetchTimeoutMs: config.synth.git.fetchTimeoutMs }
259
+ : {}),
169
260
  authorizeProject: async (c, projectId) => {
170
261
  const user = await auth.getCurrentUser(c);
171
262
  if (!user)
@@ -253,6 +344,329 @@ export function mountBackendRoutes(app, auth, ctx) {
253
344
  serviceProjectProjection,
254
345
  resolveSessionProject: async (id) => (await sessionManager.getSession(id))?.projectId,
255
346
  }));
347
+ // ADR-051/ADR-100: API пайплайнов — определения (ставит установщик пакета),
348
+ // экземпляры и ручной запуск. Чтение — ADMIN (реестр автоматов инстанса),
349
+ // ручной запуск — ADMIN или service-key со scope `automation:install`.
350
+ app.route('/api/v2/pipelines', createPipelinesRoutes({ requireAuth: auth.requireAuth }, { pipelines }, {
351
+ readGuard: auth.requirePermission('ADMIN'),
352
+ writeGuard: requireAdminRoleOrScope('automation:install'),
353
+ scopeGuard,
354
+ }));
355
+ // ADR-101 (Э6): пайплайны проекта (черновик/публикация), прогоны и журнал,
356
+ // HITL-действия и шаблоны инстанса (инстанцирование в проект).
357
+ // Права — по правилам проекта (ADR-089 §5.5/§5.8): читать — владелец/
358
+ // участник/LEAD/ADMIN, изменять — OWNER/EDITOR/LEAD/ADMIN (VIEWER читает,
359
+ // но не мутирует — инвариант 21). Шаблоны инстанса — ADMIN.
360
+ app.route('/api/v2', createPipelineProjectRoutes({ requireAuth: auth.requireAuth }, {
361
+ pipelines: deps.storageContext.projectPipelines,
362
+ runs: deps.storageContext.pipelineRuns,
363
+ engine: deps.pipelineEngine,
364
+ projects: projectStore,
365
+ templates: pipelines,
366
+ // ADR-101: общий реестр активных прогонов (soft-lock + отмена) —
367
+ // тот же экземпляр, что у встроенных тулов агента.
368
+ runControl: deps.pipelineRunControl,
369
+ // ADR-116: раздача артефактов прогона (blob-порт) — тот же store, что у
370
+ // выхода `file` движка пайплайнов (без него route всегда 404).
371
+ artifacts: deps.pipelineArtifacts,
372
+ // ADR-115 × ADR-101: вложения прогона — проверка ссылок в теле запуска
373
+ // (тот же сервис вложений, что у приёма событий) и учёт в `blob_refs`.
374
+ attachments: deps.pipelineAttachments,
375
+ blobRefs: deps.storageContext.blobRefs,
376
+ }, {
377
+ writeGuard: auth.requireAuth,
378
+ adminGuard: auth.requirePermission('ADMIN'),
379
+ canReadProject: async (c, project, userId) => projectAccess.canReadProject(c, project, userId),
380
+ canEditProject: async (c, project, userId) => projectAccess.canEditProjectContent(c, project, userId),
381
+ getCurrentUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
382
+ scopeGuard,
383
+ serviceProjectProjection,
384
+ messages: {
385
+ pipelineNotFound: (c) => t('errors.notFound.pipeline', undefined, c),
386
+ runNotFound: (c) => t('errors.notFound.pipelineRun', undefined, c),
387
+ projectNotFound: (c) => t('errors.notFound.project', undefined, c),
388
+ templateNotFound: (c) => t('errors.notFound.pipelineTemplate', undefined, c),
389
+ forbidden: (c) => t('auth.forbidden', undefined, c),
390
+ invalidBody: (c) => t('errors.validation.invalidPipelineBody', undefined, c),
391
+ invalidSpec: (c) => t('errors.validation.invalidPipelineSpec', undefined, c),
392
+ notPublished: (c) => t('errors.conflict.pipelineNotPublished', undefined, c),
393
+ invalidState: (c) => t('errors.conflict.pipelineInvalidState', undefined, c),
394
+ nothingToPublish: (c) => t('errors.conflict.pipelineNothingToPublish', undefined, c),
395
+ runFinished: (c) => t('errors.conflict.pipelineRunFinished', undefined, c),
396
+ templateNotInstantiable: (c) => t('errors.conflict.pipelineTemplateUnsupported', undefined, c),
397
+ projectIdRequired: (c) => t('errors.validation.projectIdRequired', undefined, c),
398
+ },
399
+ }));
400
+ // PROP-096/097: HTTP-контур единого реестра фоновых прогонов (список,
401
+ // деталь, лог, остановка, удаление). Право на прогон — право на его
402
+ // сессию-владельца: владелец|ADMIN, участник проекта (read — любая роль,
403
+ // write — OWNER/EDITOR/LEAD/ADMIN; `VIEWER` читает, но не мутирует —
404
+ // инвариант 21). Проверка — граничный guard core-фабрики (инвариант 16),
405
+ // в обработчиках проверок нет. Сервисы фоновой работы в деградированном
406
+ // режиме хранилища не создаются — тогда контура нет.
407
+ if (deps.backgroundService && deps.processService) {
408
+ app.route('/api/v2/processes', createProcessRoutes({ requireAuth: auth.requireAuth }, {
409
+ backgroundRuns: deps.storageContext.backgroundRuns,
410
+ background: deps.backgroundService,
411
+ processes: deps.processService,
412
+ sessionManager,
413
+ }, {
414
+ isAllowed: createBackendProcessAccess({ auth, projectStore }),
415
+ resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
416
+ messages: {
417
+ runNotFound: (c) => t('errors.notFound.backgroundRun', undefined, c),
418
+ sessionNotFound: (c) => t('errors.notFound.backgroundRunSession', undefined, c),
419
+ forbidden: (c) => t('auth.forbidden', undefined, c),
420
+ invalidQuery: (c) => t('errors.validation.invalidBackgroundRunQuery', undefined, c),
421
+ invalidKind: (c) => t('errors.validation.backgroundRunLogKind', undefined, c),
422
+ logNotFound: (c) => t('errors.notFound.processLog', undefined, c),
423
+ alreadyFinished: (c) => t('errors.conflict.backgroundRunFinished', undefined, c),
424
+ notStoppable: (c) => t('errors.conflict.backgroundRunNotStoppable', undefined, c),
425
+ runActive: (c) => t('errors.conflict.backgroundRunActive', undefined, c),
426
+ },
427
+ }));
428
+ }
429
+ // ADR-086 §5: установка пакетов расширений (скиллы/MCP/агенты/пайплайны) и
430
+ // реестр установок. Managed RBAC: установка — ADMIN или service-key со
431
+ // scope `automation:install`; одобрение и снятие — **только ADMIN** (снимают
432
+ // чужие артефакты инстанса).
433
+ app.route('/api/v2/packs', createPacksRoutes({ requireAuth: auth.requireAuth }, {
434
+ packs,
435
+ pipelines,
436
+ skills: skillService,
437
+ mcpRegistry: mcpRegistryStore,
438
+ agents: agentStore,
439
+ roleFiles: contextConfig,
440
+ routes: routeRuleStore,
441
+ // ADR-106 Ф5: контент полномочий пакета активируется в политике
442
+ // инстанса при одобрении и снимается при снятии установки.
443
+ authorityPolicy: deps.storageContext.authorityPolicy,
444
+ registerAgent: (agent) => agentRegistry.register(agent),
445
+ unregisterAgent: (id) => agentRegistry.unregister(id),
446
+ resolveUserId: (c) => {
447
+ const user = c.get('user');
448
+ return user?.id;
449
+ },
450
+ }, {
451
+ readGuard: auth.requirePermission('ADMIN'),
452
+ writeGuard: requireAdminRoleOrScope('automation:install'),
453
+ approveGuard: auth.requirePermission('ADMIN'),
454
+ uninstallGuard: auth.requirePermission('ADMIN'),
455
+ scopeGuard,
456
+ }));
457
+ // ADR-090 (Ф5б-2): управление плагинами инстанса. Managed RBAC:
458
+ // чтение — ADMIN (реестр инстанса), установка/активация/деактивация —
459
+ // ADMIN или service-key со scope `addons:install` (установка аддонов —
460
+ // зонтичный scope реестра расширений), подтверждение карантина и снятие —
461
+ // **только ADMIN** (снятие гасит код в процессе ядра). Установка из
462
+ // локального каталога/архива запрещена (`localInstall: false` → 403
463
+ // `LOCAL_INSTALL_DISABLED`): путь с ФС хоста в managed не принимается.
464
+ // Сетевые источники (`npm`/`url`) разрешены — это не локальный путь, а
465
+ // доставка бандла с проверкой целостности (SRI/sha256).
466
+ app.route('/api/v2/plugins', createPluginsRoutes({ requireAuth: auth.requireAuth }, {
467
+ runtime: deps.pluginRuntime,
468
+ config: mergePluginsConfig(config.synth.plugins, {}),
469
+ settings: settingsStore,
470
+ localInstall: false,
471
+ // Ф7 (ADR-090): реестр service-key — для выдачи server-scoped токена
472
+ // плагину (`POST /api/v2/plugins/token`).
473
+ serviceKeys: serviceApiKeyStore,
474
+ // Ф7: серверная политика (allow-list) из работающего рантайма.
475
+ serverPolicy: () => resolvePluginServerPolicy(deps.pluginRuntime.config),
476
+ resolveUserId: (c) => {
477
+ const user = c.get('user');
478
+ return user?.id;
479
+ },
480
+ }, {
481
+ readGuard: auth.requirePermission('ADMIN'),
482
+ writeGuard: requireAdminRoleOrScope('addons:install'),
483
+ approveGuard: auth.requirePermission('ADMIN'),
484
+ uninstallGuard: auth.requirePermission('ADMIN'),
485
+ // Ф7 (Уровень 2): выдача server-scoped токена — только ADMIN (токен даёт
486
+ // плагину машинный доступ к серверу).
487
+ tokenGuard: auth.requirePermission('ADMIN'),
488
+ }));
489
+ // ADR-090 (Ф5б-2): runtime-настройки слоя плагинов. Managed RBAC —
490
+ // ADMIN (чтение и запись): политика доверия/скана/исполнения — инстанс-уровневая.
491
+ // `restartRequired` — всегда true (рантайм собирается при старте, инвариант 24).
492
+ app.route('/api/v2/settings', createPluginSettingsRoutes({ requireAuth: auth.requireAuth }, {
493
+ config: mergePluginsConfig(config.synth.plugins, {}),
494
+ settings: settingsStore,
495
+ running: deps.pluginRuntime.config,
496
+ // Долги Д3: бюджеты (`promptBlockMaxChars`, `llmFilterTimeoutMs`) —
497
+ // живые; остальные ключи — после рестарта (инвариант 24).
498
+ onPluginsChange: (effective) => {
499
+ deps.orchestrator.setPromptBlockMaxChars(effective.promptBlockMaxChars);
500
+ deps.orchestrator.setLlmFilterTimeoutMs(effective.llmFilterTimeoutMs);
501
+ },
502
+ }, {
503
+ readGuard: auth.requirePermission('ADMIN'),
504
+ writeGuard: auth.requirePermission('ADMIN'),
505
+ }));
506
+ // ADR-115: админ-раздел «Вложения» — runtime-настройки мультимодального
507
+ // ввода. Managed RBAC — **ADMIN** (чтение и запись): мастер-выключатель,
508
+ // семейства MIME и лимиты — политика инстанса. Применяется сразу
509
+ // (`restartRequired: false`): сервис вложений, промпт и GC читают резолвер
510
+ // на каждый вызов.
511
+ app.route('/api/v2/settings', createAttachmentsSettingsRoutes({ requireAuth: auth.requireAuth }, {
512
+ settingsStore,
513
+ config: config.synth.attachments,
514
+ live: deps.attachmentsSettings,
515
+ securityAudit,
516
+ env: process.env,
517
+ // ADR-115: проверка `modalityModels` по каталогу (провайдер + модель +
518
+ // модальности модели) — до записи runtime-патча.
519
+ lookupModel: createModalityModelLookup({ providers: providerStore, models: modelStore }),
520
+ }, {
521
+ readGuard: auth.requirePermission('ADMIN'),
522
+ writeGuard: auth.requirePermission('ADMIN'),
523
+ }));
524
+ // Политика ограничения контекстного окна (`context.windowPolicy`):
525
+ // instance-wide (`off` | `warn` | `enforce`), применяется сразу. Managed
526
+ // RBAC — ADMIN (чтение и запись): это политика инстанса.
527
+ app.route('/api/v2/settings', createContextWindowSettingsRoutes({ requireAuth: auth.requireAuth }, {
528
+ settingsStore,
529
+ config: config.synth.context?.windowPolicy,
530
+ live: deps.contextWindowSettings,
531
+ securityAudit,
532
+ env: process.env,
533
+ }, {
534
+ readGuard: auth.requirePermission('ADMIN'),
535
+ writeGuard: auth.requirePermission('ADMIN'),
536
+ }));
537
+ // Бюджет промпта саб-агента (`agents.subagentMaxInputTokens`): instance-wide,
538
+ // 0 — без лимита; применяется к следующим прогонам без рестарта. Managed — ADMIN.
539
+ app.route('/api/v2/settings', createAgentsLimitsSettingsRoutes({ requireAuth: auth.requireAuth }, {
540
+ settingsStore,
541
+ config: config.synth.agents.subagentMaxInputTokens,
542
+ live: deps.subagentMaxInputTokensSettings,
543
+ securityAudit,
544
+ env: process.env,
545
+ }, {
546
+ readGuard: auth.requirePermission('ADMIN'),
547
+ writeGuard: auth.requirePermission('ADMIN'),
548
+ }));
549
+ // Дефолты оптимизации контекста для новых сессий (`context.defaults`):
550
+ // instance-wide, применяются при создании сессии. Managed RBAC — ADMIN
551
+ // (чтение и запись): это настройка инстанса.
552
+ app.route('/api/v2/settings', createContextDefaultsSettingsRoutes({ requireAuth: auth.requireAuth }, {
553
+ settingsStore,
554
+ config: config.synth.context?.defaults,
555
+ live: deps.contextDefaultsSettings,
556
+ securityAudit,
557
+ }, {
558
+ readGuard: auth.requirePermission('ADMIN'),
559
+ writeGuard: auth.requirePermission('ADMIN'),
560
+ }));
561
+ // Instance-wide лимиты заметок сессии (`context.stickyNotes`): instance-wide
562
+ // ограничения, применяются сразу (резолвер читается на операцию). Managed
563
+ // RBAC — ADMIN (чтение и запись): это настройка инстанса.
564
+ app.route('/api/v2/settings', createStickyNotesSettingsRoutes({ requireAuth: auth.requireAuth }, {
565
+ settingsStore,
566
+ config: config.synth.context?.stickyNotes,
567
+ live: deps.stickyNotesLimitsSettings,
568
+ securityAudit,
569
+ }, {
570
+ readGuard: auth.requirePermission('ADMIN'),
571
+ writeGuard: auth.requirePermission('ADMIN'),
572
+ }));
573
+ // ADR-115: staging-загрузка без сессии — `POST /api/v2/attachments`
574
+ // (шлюзы принимают файл из внешнего канала, пайплайны — из шага). Managed:
575
+ // `requireAuth` + scope-гейт service-key `events:ingest` (у шлюзов он уже
576
+ // есть; для интерактивных кред — no-op). Объект не привязан к сессии: без
577
+ // ссылки `blob_refs` живёт `attachments.gcDays` до GC.
578
+ app.route('/api/v2/attachments', createStagingAttachmentRoutes({ requireAuth: auth.requireAuth, getCurrentUser: auth.getCurrentUser }, {
579
+ service: new AttachmentService({
580
+ blobs: deps.storageContext.blobs,
581
+ config: () => deps.attachmentsSettings.getConfig(),
582
+ thumbnails: deps.attachmentThumbnails,
583
+ }),
584
+ config: () => deps.attachmentsSettings.getConfig(),
585
+ }, { guard: scopeGuard('events:ingest') }));
586
+ // ADR-107 / PROP-047 §2.1: портал памяти в ядре — чтение фактов и индексов
587
+ // через доменные порты памяти. Managed RBAC: **только ADMIN** — портал
588
+ // админский (данные памяти видны целиком, без проектной проекции).
589
+ // Namespace плагина памяти подставляет сервер — клиент его не задаёт.
590
+ app.route('/api/v2/memory', createMemoryRoutes({ requireAuth: auth.requireAuth }, {
591
+ memory: {
592
+ facts: deps.storageContext.memoryFacts,
593
+ indexes: deps.storageContext.memoryIndexes,
594
+ },
595
+ guard: auth.requirePermission('ADMIN'),
596
+ // Проектная авторизация (инвариант 16, ADR-089 §5.8): проверка прав на
597
+ // границе — до обращения к порту/тулу. `read` — право чтения проекта
598
+ // (владелец/участник/`LEAD`/`ADMIN`), `write` — право изменения
599
+ // содержимого (владелец/`EDITOR`/`LEAD`/`ADMIN`; `VIEWER` только
600
+ // читает, инвариант 21). Нет проекта/прав → отказ (fail-closed).
601
+ authorizeProject: async (c, projectId, mode) => {
602
+ const user = await auth.getCurrentUser(c);
603
+ if (!user)
604
+ return false;
605
+ const project = await projectStore.load(projectId);
606
+ if (!project)
607
+ return false;
608
+ return mode === 'read'
609
+ ? projectAccess.canReadProject(c, project, user.id)
610
+ : projectAccess.canEditProjectContent(c, project, user.id);
611
+ },
612
+ // Активен ли плагин памяти в процессе — реестр активаций хоста (ADR-090).
613
+ isPluginActive: () => deps.pluginRuntime.host.isActive(MEMORY_PLUGIN_NAME),
614
+ // М2: мутации индексов — через админ-тул плагина памяти (реестр тулов).
615
+ // Контекст вызова (sessionId/messageId) создаёт вызывающая сторона:
616
+ // сессии у портала нет — это служебный вызов инстанса.
617
+ invokeTool: async ({ tool, params, projectId, workingDir }) => {
618
+ const def = toolRegistry.get(tool);
619
+ if (!def)
620
+ throw new MemoryProviderUnavailableError(tool);
621
+ return executeToolDef(def, params, {
622
+ sessionId: `system:memory-portal:${randomUUID()}`,
623
+ messageId: `system:memory-portal:${randomUUID()}`,
624
+ workingDir,
625
+ ...(projectId ? { projectId } : {}),
626
+ }, tool);
627
+ },
628
+ // Проект и его workspace (ADR-075): относительный workspace резолвится
629
+ // от `workspacesRoot`, абсолютный — как есть.
630
+ resolveProject: async (projectId) => {
631
+ const project = await deps.storageContext.projects.load(projectId);
632
+ if (!project)
633
+ return null;
634
+ if (!project.workspace)
635
+ return { id: project.id };
636
+ const root = config.workspacesRoot ?? join(dataDir, 'workspaces');
637
+ const workspace = isAbsolute(project.workspace)
638
+ ? normalize(project.workspace)
639
+ : resolve(root, project.workspace);
640
+ return { id: project.id, workspace };
641
+ },
642
+ // Каталог данных — рабочий каталог для источника `facts` (нет workspace).
643
+ dataDir,
644
+ messages: {
645
+ invalidStatus: (c) => t('errors.validation.invalidMemoryStatus', undefined, c),
646
+ invalidState: (c) => t('errors.validation.invalidMemoryState', undefined, c),
647
+ invalidLimit: (c) => t('errors.validation.invalidMemoryLimit', undefined, c),
648
+ invalidOffset: (c) => t('errors.validation.invalidMemoryOffset', undefined, c),
649
+ factNotFound: (c) => t('errors.notFound.memoryFact', undefined, c),
650
+ unavailable: (c) => t('errors.unavailable.memory', undefined, c),
651
+ invalidBody: (c) => t('errors.validation.invalidMemoryBody', undefined, c),
652
+ invalidSource: (c) => t('errors.validation.invalidMemorySource', undefined, c),
653
+ projectRequired: (c) => t('errors.validation.memoryProjectRequired', undefined, c),
654
+ projectNotFound: (c) => t('errors.notFound.memoryProject', undefined, c),
655
+ workspaceRequired: (c) => t('errors.validation.memoryWorkspaceRequired', undefined, c),
656
+ providerUnavailable: (c) => t('errors.unavailable.memoryProvider', undefined, c),
657
+ indexNotFound: (c) => t('errors.notFound.memoryIndex', undefined, c),
658
+ indexFailed: (c) => t('errors.failed.memoryIndex', undefined, c),
659
+ indexCreated: (c) => t('memory.indexCreated', undefined, c),
660
+ invalidThreshold: (c) => t('errors.validation.invalidMemoryThreshold', undefined, c),
661
+ consolidationFailed: (c) => t('errors.failed.memoryConsolidation', undefined, c),
662
+ consolidated: (c) => t('memory.consolidated', undefined, c),
663
+ invalidGraphDepth: (c) => t('errors.validation.invalidMemoryGraphDepth', undefined, c),
664
+ invalidGraphLimit: (c) => t('errors.validation.invalidMemoryGraphLimit', undefined, c),
665
+ invalidGraphEntity: (c) => t('errors.validation.invalidMemoryGraphEntity', undefined, c),
666
+ graphFailed: (c) => t('errors.failed.memoryGraph', undefined, c),
667
+ forbidden: (c) => t('auth.forbidden', undefined, c),
668
+ },
669
+ }));
256
670
  // ADR-052 (этап I): CRUD service-key инстанса (`synth_svc_…`). Managed RBAC:
257
671
  // только ADMIN (ключи дают машинный доступ — управление админское), i18n.
258
672
  app.route('/api/v2/service-keys', createServiceKeyRoutes({ requireAuth: auth.requireAuth }, { store: serviceApiKeyStore }, {
@@ -293,7 +707,7 @@ export function mountBackendRoutes(app, auth, ctx) {
293
707
  // ADR-091/ADR-092: обслуживание инстанса (backup/restore/doctor/migrate).
294
708
  // Managed RBAC: только ADMIN — операции меняют/отдают данные всего инстанса
295
709
  // (архивы могут содержать секреты), i18n.
296
- // PROP-032: при backend=postgres doctor/migrations ходят в БД через read-only
710
+ // ADR-097: при backend=postgres doctor/migrations ходят в БД через read-only
297
711
  // пробу (контекст в режиме `skip` — миграции не применяются).
298
712
  const maintenanceBackend = resolveStorageBackend(config.synth, process.env);
299
713
  const withPostgresContext = maintenanceBackend === 'postgres'
@@ -353,6 +767,67 @@ export function mountBackendRoutes(app, auth, ctx) {
353
767
  registry: mcpRegistryStore,
354
768
  // Политика резолвится на каждый запрос (live; исключения/режим — из стора).
355
769
  getNetworkPolicy: () => egressResolver.resolveMcp(),
770
+ // ADR-105 (Ф3): порт слоя внешних доступов — право привязать доступ
771
+ // к коннектору проверяется на границе (инвариант 16).
772
+ credentials: deps.storageContext.externalCredentials,
773
+ // ADR-105 (Ф3): проектный доступ привязывает участник проекта с правом
774
+ // изменения содержимого (OWNER/EDITOR + LEAD/ADMIN; VIEWER — нет).
775
+ canEditProject: async (c, projectId) => {
776
+ const user = c.get('user');
777
+ if (!user?.id)
778
+ return false;
779
+ const project = await projectStore.load(projectId);
780
+ return project ? projectAccess.canEditProjectContent(c, project, user.id) : false;
781
+ },
782
+ }));
783
+ // ADR-105 (Ф4): HTTP-контур слоя внешних доступов. Managed RBAC:
784
+ // чтение — свои доступы (владелец/участник проекта), `ADMIN`/`LEAD` — все;
785
+ // мутации — владелец доступа (инстансные — `ADMIN`/`LEAD`); право
786
+ // распоряжения доступом проверяется на границе (инвариант 16).
787
+ app.route('/api/v2/oauth', createOAuthRoutes({ requireAuth: auth.requireAuth }, {
788
+ credentials: deps.storageContext.externalCredentials,
789
+ service: deps.oauthCredentialService,
790
+ providers: deps.oauthProviders,
791
+ // ADR-105 (Ф4): журнал операций со слоем доступов (привязка к коннектору).
792
+ audit: deps.storageContext.credentialAudit,
793
+ ownerKind: 'user',
794
+ resolveActor: (c) => {
795
+ const user = c.get('user');
796
+ return { userId: user?.id ?? '', roles: user?.roles ?? [] };
797
+ },
798
+ canReadProject: async (c, projectId) => {
799
+ const user = await auth.getCurrentUser(c);
800
+ if (!user)
801
+ return false;
802
+ const project = await projectStore.load(projectId);
803
+ return project ? projectAccess.canReadProject(c, project, user.id) : false;
804
+ },
805
+ canEditProject: async (c, projectId) => {
806
+ const user = await auth.getCurrentUser(c);
807
+ if (!user)
808
+ return false;
809
+ const project = await projectStore.load(projectId);
810
+ return project ? projectAccess.canEditProjectContent(c, project, user.id) : false;
811
+ },
812
+ bindConnector: async ({ connectorId, credentialId, actor, c }) => {
813
+ await bindCredentialToConnector({
814
+ registry: deps.mcpRegistryStore,
815
+ connectorId,
816
+ credentialId,
817
+ // Запись реестра меняет автор записи или `ADMIN` (как в `mcp-registry`).
818
+ canModify: (entry) => {
819
+ const user = c.get('user');
820
+ if (auth.isAdmin(c))
821
+ return true;
822
+ if (entry.author?.userId && user?.id && entry.author.userId === user.id)
823
+ return true;
824
+ return actor.roles.includes('ADMIN') || actor.roles.includes('LEAD');
825
+ },
826
+ });
827
+ // Реестр — источник истины для конфигурации серверов (ADR-071 §2.5):
828
+ // без синхронизации менеджер остался бы со старым конфигом (без `auth`).
829
+ await syncMcpManagerFromRegistry(mcpManager, deps.mcpRegistryStore);
830
+ },
356
831
  }));
357
832
  // Скиллы (ADR-046 §9.1/§9.2): core-фабрика + RBAC ADMIN на запись.
358
833
  app.route('/api/v2/skills', createSkillRoutes(auth, {
@@ -639,7 +1114,7 @@ export function mountBackendRoutes(app, auth, ctx) {
639
1114
  }, {
640
1115
  readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
641
1116
  }));
642
- // PROP-102 (волна 1): отчёты аналитики — только чтение, данных без локализации.
1117
+ // ADR-102 (волна 1): отчёты аналитики — только чтение, данных без локализации.
643
1118
  // Managed RBAC (§7): ADMIN/LEAD — сквозной обзор; AUDITOR — чтение всех отчётов;
644
1119
  // обычный USER — принудительный фильтр оси `user` по себе (+ 403 на `decision`/`summary`).
645
1120
  app.route('/api/v2/analytics', createAnalyticsRoutes({ requireAuth: auth.requireAuth }, { service: new AnalyticsService({ repo: analyticsRollups }) }, {
@@ -671,6 +1146,8 @@ export function mountBackendRoutes(app, auth, ctx) {
671
1146
  trustedProjectDirs: config.synth.skills.trustedProjectDirs,
672
1147
  // ADR-069 R3: авто-trust workspace внутри workspacesRoot (managed-каталоги).
673
1148
  workspacesRoot: config.workspacesRoot,
1149
+ // ADR-077: `git rev-parse` — через порт исполнения (тот же, что у тулов).
1150
+ execution: deps.executionPort,
674
1151
  }), config.synth.instructions);
675
1152
  app.route('/api/v2/context', createCoreContextRoutes(auth, {
676
1153
  resolveInstructions: instructionsInfoResolver,
@@ -689,6 +1166,10 @@ export function mountBackendRoutes(app, auth, ctx) {
689
1166
  || project.ownerId === userId
690
1167
  || project.members?.[userId] === ProjectRole.OWNER,
691
1168
  }));
1169
+ // ADR-118 §8: возможности инстанса (`GET /api/v2/meta`) — **без
1170
+ // аутентификации** (как `GET /health`): публичная информация о протоколе,
1171
+ // по ней клиент сверяет модель сообщений (fail-closed гейт транспорта).
1172
+ app.route('/api/v2', createMetaRoutes({ getAttachments: () => deps.attachmentsSettings.getConfig() }));
692
1173
  // Глобальный SSE-хаб для всех сессий пользователя (ADR-052: `events:watch`).
693
1174
  registerEventsSse(app, { auth, eventHub, scopeGuard });
694
1175
  // Admin routes (кроме graceful shutdown — он живёт в main.ts, т.к. требует server)
@@ -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;