@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.
@@ -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',
@@ -8,7 +8,9 @@ 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
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
10
  // 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';
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';
12
14
  import { createProjectRoutes, createProjectAccess } from '../routes/projects.js';
13
15
  import { createBackendProcessAccess } from '../routes/processes.js';
14
16
  import { createSessionRoutes } from '../routes/sessions.js';
@@ -58,7 +60,7 @@ export function mountBackendRoutes(app, auth, ctx) {
58
60
  // публичную выдачу без auth согласуем отдельно.
59
61
  app.get('/api/v2/openapi.json', auth.requireAuth, (c) => c.json(getPublicOpenApiDocument()));
60
62
  // Projects routes
61
- app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore, deps.worktreeService));
63
+ app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore, deps.worktreeService, eventBus));
62
64
  // ADR-091 (этап 2): портативный экспорт/импорт проекта (скачать/загрузить архив).
63
65
  // Managed RBAC: скачивание — право чтения проекта (owner/участник/LEAD/ADMIN),
64
66
  // импорт в существующий проект (`mergeInto`) — право редактирования; создание
@@ -131,13 +133,48 @@ export function mountBackendRoutes(app, auth, ctx) {
131
133
  blobs: deps.storageContext.blobs,
132
134
  blobRefs: deps.storageContext.blobRefs,
133
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
+ },
134
169
  }));
135
170
  // Messages routes
136
171
  app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus, projectStore,
137
172
  // ADR-115: удаление сообщения снимает ссылки на объекты вложений.
138
173
  deps.storageContext.blobRefs));
139
174
  // Queue routes
140
- 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)));
141
178
  // FS routes (ADR-075): core-фабрика, managed поверх workspace проекта.
142
179
  // ADR-089 (P0): доступ к проекту обязателен — иначе любой USER читал/писал бы
143
180
  // файлы чужого проекта по id (IDOR). Чтение — canRead, мутации — canEditContent.
@@ -148,6 +185,10 @@ export function mountBackendRoutes(app, auth, ctx) {
148
185
  getProtectedPathsPolicy: () => protectedPathsStore.getPolicy(),
149
186
  // Лимит загрузки: config/env (resolveMaxUploadBytes), иначе дефолт фабрики.
150
187
  maxUploadBytes: config.maxUploadBytes,
188
+ // Лимит чтения файла: config/env (resolveMaxReadBytes), иначе дефолт фабрики.
189
+ maxReadBytes: config.maxReadBytes,
190
+ // Лимит предпросмотра файла (GET /raw): config/env (resolveMaxPreviewBytes).
191
+ maxPreviewBytes: config.maxPreviewBytes,
151
192
  authorizeProject: async (c, projectId) => {
152
193
  const user = await auth.getCurrentUser(c);
153
194
  if (!user)
@@ -165,6 +206,22 @@ export function mountBackendRoutes(app, auth, ctx) {
165
206
  outsideRootPolicy: () => 'deny',
166
207
  strict: true,
167
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
+ },
168
225
  }));
169
226
  // Providers routes
170
227
  app.route('/api/v2/providers', createProviderRoutes(auth, providerStore, providerCache, {
@@ -193,6 +250,13 @@ export function mountBackendRoutes(app, auth, ctx) {
193
250
  app.route('/api/v2/git', createGitRoutes(auth, projectStore, config.workspacesRoot, {
194
251
  sshKeyStore,
195
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
+ : {}),
196
260
  authorizeProject: async (c, projectId) => {
197
261
  const user = await auth.getCurrentUser(c);
198
262
  if (!user)
@@ -457,6 +521,55 @@ export function mountBackendRoutes(app, auth, ctx) {
457
521
  readGuard: auth.requirePermission('ADMIN'),
458
522
  writeGuard: auth.requirePermission('ADMIN'),
459
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
+ }));
460
573
  // ADR-115: staging-загрузка без сессии — `POST /api/v2/attachments`
461
574
  // (шлюзы принимают файл из внешнего канала, пайплайны — из шага). Managed:
462
575
  // `requireAuth` + scope-гейт service-key `events:ingest` (у шлюзов он уже
@@ -466,6 +579,7 @@ export function mountBackendRoutes(app, auth, ctx) {
466
579
  service: new AttachmentService({
467
580
  blobs: deps.storageContext.blobs,
468
581
  config: () => deps.attachmentsSettings.getConfig(),
582
+ thumbnails: deps.attachmentThumbnails,
469
583
  }),
470
584
  config: () => deps.attachmentsSettings.getConfig(),
471
585
  }, { guard: scopeGuard('events:ingest') }));
@@ -1052,6 +1166,10 @@ export function mountBackendRoutes(app, auth, ctx) {
1052
1166
  || project.ownerId === userId
1053
1167
  || project.members?.[userId] === ProjectRole.OWNER,
1054
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() }));
1055
1173
  // Глобальный SSE-хаб для всех сессий пользователя (ADR-052: `events:watch`).
1056
1174
  registerEventsSse(app, { auth, eventHub, scopeGuard });
1057
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;
@@ -1,7 +1,12 @@
1
1
  import { getServiceCredential } from '@itphx/synth-core';
2
+ import { MESSAGE_MODEL_QUERY_PARAM, MESSAGE_MODEL_UNSUPPORTED_REASON, isSupportedMessageModelParam, parseSinceParam, } from '@itphx/synth-core';
2
3
  /**
3
4
  * Зарегистрировать SSE-хаб (`GET /api/v2/events`): подписка на события сессий
4
5
  * пользователя (watch-all — для service-key и ADMIN/LEAD, ADR-052 этап IV).
6
+ *
7
+ * ADR-118 §6/§8: кадр несёт `id:` (глобальный номер события) — по нему
8
+ * работает догон (`Last-Event-ID` / `?since`); клиент обязан заявить модель
9
+ * сообщений (`messageModel=2`) — иначе поток не устанавливается (fail-closed).
5
10
  */
6
11
  export function registerEventsSse(app, deps) {
7
12
  const { auth, eventHub, scopeGuard } = deps;
@@ -10,6 +15,13 @@ export function registerEventsSse(app, deps) {
10
15
  app.get('/api/v2/events', auth.requireAuth, scopeGuard('events:watch'), async (c) => {
11
16
  const user = (await auth.getCurrentUser(c));
12
17
  const signal = c.req.raw.signal;
18
+ // ADR-118 §8: гейт минимальной версии клиента (fail-closed) — без
19
+ // `messageModel=2` поток не открывается (426 Upgrade Required).
20
+ if (!isSupportedMessageModelParam(c.req.query(MESSAGE_MODEL_QUERY_PARAM))) {
21
+ return c.json({ error: { code: 'UPGRADE_REQUIRED', message: MESSAGE_MODEL_UNSUPPORTED_REASON } }, 426);
22
+ }
23
+ // ADR-118 §6: догон — `Last-Event-ID` (заголовок) либо `?since=`.
24
+ const sinceSeq = parseSinceParam(c.req.header('last-event-id') ?? c.req.query('since'));
13
25
  // ADR-052 (этап IV) / ADR-089: машинный watcher (service-key со scope
14
26
  // `events:watch`) и роли сквозного обзора ADMIN/LEAD получают события ВСЕХ
15
27
  // сессий (паритет со standalone-core `subscribeAll`), обычный пользователь —
@@ -19,23 +31,58 @@ export function registerEventsSse(app, deps) {
19
31
  return new Response(new ReadableStream({
20
32
  async start(controller) {
21
33
  const encoder = new TextEncoder();
34
+ /**
35
+ * ADR-118 §6: порядок «сначала журнал, потом живое». Пока идёт
36
+ * воспроизведение журнала, живые события копятся в буфере; уже
37
+ * отправленные номера (`sentSeq`) отсекают дубли.
38
+ */
39
+ let replaying = sinceSeq !== null;
40
+ const pending = [];
41
+ const sentSeq = new Map();
42
+ const write = (event) => {
43
+ const seq = event.eventSeq;
44
+ if (typeof seq === 'number') {
45
+ const last = sentSeq.get(event.sessionId) ?? 0;
46
+ if (seq <= last)
47
+ return;
48
+ sentSeq.set(event.sessionId, seq);
49
+ }
50
+ try {
51
+ // `id:` — глобальный номер события (ADR-118 §6): по нему
52
+ // клиент продолжает ленту после переподключения (`Last-Event-ID`).
53
+ const id = typeof event.eventSeq === 'number' ? `id: ${event.eventSeq}\n` : '';
54
+ const line = `${id}data: ${JSON.stringify(event)}\n\n`;
55
+ controller.enqueue(encoder.encode(line));
56
+ }
57
+ catch {
58
+ // client disconnected
59
+ }
60
+ };
22
61
  const sseClient = {
23
62
  userId: user.id,
24
63
  username: user.username,
25
64
  allSessions,
26
65
  send(event) {
27
- try {
28
- const line = `data: ${JSON.stringify(event)}\n\n`;
29
- controller.enqueue(encoder.encode(line));
30
- }
31
- catch {
32
- // client disconnected
66
+ if (replaying) {
67
+ pending.push(event);
68
+ return;
33
69
  }
70
+ write(event);
34
71
  },
35
72
  };
36
73
  try {
37
74
  console.log(`[SSE /api/v2/events] Connected: user=${user.username} allSessions=${allSessions}`);
38
75
  await eventHub.registerClient(sseClient);
76
+ // ADR-118 §6: догон — журнал строго после `since`, затем живые
77
+ // события (буфер), без разрыва и без дублей.
78
+ if (sinceSeq !== null) {
79
+ for (const event of eventHub.replayForClient(sseClient, sinceSeq))
80
+ write(event);
81
+ }
82
+ replaying = false;
83
+ for (const event of pending)
84
+ write(event);
85
+ pending.length = 0;
39
86
  // Keepalive: раз в 30 секунд отправляем комментарий для предотвращения разрыва
40
87
  const keepalive = setInterval(() => {
41
88
  try {
package/dist/app.d.ts CHANGED
@@ -79,6 +79,8 @@ export interface BackendAppHandle {
79
79
  stopProcessLogPruner: () => void;
80
80
  /** ADR-115: остановка GC осиротевших вложений сообщений. */
81
81
  stopAttachmentPruner: () => void;
82
+ /** ADR-115 × ADR-077: остановка уборки временных каталогов медиа-раннера. */
83
+ stopMediaTempPruner: () => void;
82
84
  /** ADR-052 (этап II): реестр подписок webhooks (для тестов/диагностики). */
83
85
  webhookStore: WebhookRepository;
84
86
  /** ADR-052 (этап II): движок исходящих webhooks. */
package/dist/app.js CHANGED
@@ -308,6 +308,8 @@ export async function createBackendApp(opts = {}) {
308
308
  stopProcessLogPruner: () => deps.stopProcessLogPruner(),
309
309
  // ADR-115: GC осиротевших вложений сообщений.
310
310
  stopAttachmentPruner: () => deps.stopAttachmentPruner(),
311
+ // ADR-115 × ADR-077: уборка временных каталогов медиа-раннера.
312
+ stopMediaTempPruner: () => deps.stopMediaTempPruner(),
311
313
  // ADR-052 (этап II): реестр подписок и движок webhooks + остановка на shutdown.
312
314
  webhookStore: deps.webhookStore,
313
315
  webhookService: deps.webhookService,
@@ -31,6 +31,23 @@ export declare class EventHub {
31
31
  unsubscribeFromSession(userId: string, sessionId: string): void;
32
32
  /** Глобальная подписка all-клиента: события всех сессий без привязки к владельцу. */
33
33
  private _subscribeClientToAll;
34
+ /**
35
+ * ADR-118 §4: адресная доставка.
36
+ *
37
+ * Событие с `recipient` получает **только** клиент с совпадающим `userId`
38
+ * (broadcast — без `recipient` — получают все подписчики сессии).
39
+ */
40
+ private _deliver;
41
+ /**
42
+ * ADR-118 §6: догон — события журнала строго после `afterSeq` для сессий,
43
+ * на которые подписан клиент (`Last-Event-ID` / `?since`).
44
+ *
45
+ * Watch-all клиент (service-key / сквозной обзор) получает журнал всех
46
+ * сессий; обычный клиент — только своих. Номер события глобальный и
47
+ * монотонный в пределах инстанса, поэтому порядок между сессиями — точный
48
+ * (по номеру).
49
+ */
50
+ replayForClient(client: EventClient, afterSeq: number): BusEvent[];
34
51
  private _subscribeClientToSession;
35
52
  private _unsubscribeClientFromAll;
36
53
  }
@@ -29,7 +29,7 @@ export class EventHub {
29
29
  return;
30
30
  }
31
31
  // Нужны только id сессий владельца — лёгкая выборка (без истории сообщений).
32
- const sessions = await this.sessionManager.listSessions({ userId: client.userId }, { light: true });
32
+ const sessions = await this.sessionManager.listSessions({ userId: client.userId });
33
33
  console.log(`[EventHub] Register client: user=${client.username} clients=${arr.length} sessions=${sessions.length}`);
34
34
  for (const s of sessions) {
35
35
  this._subscribeClientToSession(client, s.id);
@@ -91,15 +91,50 @@ export class EventHub {
91
91
  if (!subs || subs.has(ALL_SESSIONS_KEY))
92
92
  return;
93
93
  const unsub = this.eventBus.subscribeAll((event) => {
94
- try {
95
- client.send(event);
96
- }
97
- catch {
98
- // ignore send errors
99
- }
94
+ this._deliver(client, event);
100
95
  });
101
96
  subs.set(ALL_SESSIONS_KEY, unsub);
102
97
  }
98
+ /**
99
+ * ADR-118 §4: адресная доставка.
100
+ *
101
+ * Событие с `recipient` получает **только** клиент с совпадающим `userId`
102
+ * (broadcast — без `recipient` — получают все подписчики сессии).
103
+ */
104
+ _deliver(client, event) {
105
+ if (event.recipient && event.recipient !== client.userId)
106
+ return;
107
+ try {
108
+ client.send(event);
109
+ }
110
+ catch {
111
+ // ignore send errors
112
+ }
113
+ }
114
+ /**
115
+ * ADR-118 §6: догон — события журнала строго после `afterSeq` для сессий,
116
+ * на которые подписан клиент (`Last-Event-ID` / `?since`).
117
+ *
118
+ * Watch-all клиент (service-key / сквозной обзор) получает журнал всех
119
+ * сессий; обычный клиент — только своих. Номер события глобальный и
120
+ * монотонный в пределах инстанса, поэтому порядок между сессиями — точный
121
+ * (по номеру).
122
+ */
123
+ replayForClient(client, afterSeq) {
124
+ const subs = this.clientSubs.get(client);
125
+ if (!subs)
126
+ return [];
127
+ const sessionIds = [...subs.keys()].filter((id) => id !== ALL_SESSIONS_KEY);
128
+ if (sessionIds.length === 0) {
129
+ return this.eventBus.journalSince(afterSeq);
130
+ }
131
+ const out = [];
132
+ for (const sessionId of sessionIds) {
133
+ out.push(...this.eventBus.since(sessionId, afterSeq));
134
+ }
135
+ out.sort((a, b) => (a.eventSeq ?? 0) - (b.eventSeq ?? 0));
136
+ return out;
137
+ }
103
138
  _subscribeClientToSession(client, sessionId) {
104
139
  // all-клиент покрыт глобальной подпиской — per-session подписки не нужны
105
140
  // (иначе дубли доставки).
@@ -111,12 +146,7 @@ export class EventHub {
111
146
  if (subs.has(sessionId))
112
147
  return;
113
148
  const unsub = this.eventBus.subscribe(sessionId, (event) => {
114
- try {
115
- client.send(event);
116
- }
117
- catch {
118
- // ignore send errors
119
- }
149
+ this._deliver(client, event);
120
150
  // Автоподписка на дочернюю сессию саб-агента. Раньше клиент получал
121
151
  // live-события (`stream.usage`/`stream.chunk`) только по сессиям из
122
152
  // `listSessions` и созданным/форкнутым через роуты; child-сессию тул
@@ -128,7 +158,9 @@ export class EventHub {
128
158
  if (childId && childId !== sessionId) {
129
159
  this._subscribeClientToSession(client, childId);
130
160
  }
131
- });
161
+ // ADR-118 §4: адресная доставка на уровне шины — подписчик сессии
162
+ // получает событие с `recipient` только при совпадении `userId`.
163
+ }, { userId: client.userId });
132
164
  subs.set(sessionId, unsub);
133
165
  }
134
166
  _unsubscribeClientFromAll(client) {
@@ -6,6 +6,10 @@ export interface BackendConfig {
6
6
  workspacesRoot: string;
7
7
  /** Максимальный размер загрузки файла (`POST /api/v2/fs/upload`), байт (config/env). */
8
8
  maxUploadBytes: number;
9
+ /** Максимальный размер файла, отдаваемого `GET /api/v2/fs/read`, байт (config/env). */
10
+ maxReadBytes: number;
11
+ /** Максимальный размер файла, отдаваемого `GET /api/v2/fs/raw` (предпросмотр), байт (config/env). */
12
+ maxPreviewBytes: number;
9
13
  port: number;
10
14
  auth: AuthConfig;
11
15
  }
@@ -1,4 +1,4 @@
1
- import { loadConfig, resolveDataDir, resolvePort, resolveWorkspacesRoot, resolveMaxUploadBytes } from '@itphx/synth-shared';
1
+ import { loadConfig, resolveDataDir, resolvePort, resolveWorkspacesRoot, resolveMaxUploadBytes, resolveMaxReadBytes, resolveMaxPreviewBytes } from '@itphx/synth-shared';
2
2
  const envStr = (key, fallback = '') => process.env[key] || fallback;
3
3
  const envBool = (key, fallback = false) => process.env[key] ? process.env[key] === 'true' : fallback;
4
4
  const envInt = (key, fallback) => {
@@ -60,6 +60,8 @@ export async function loadBackendConfig(options) {
60
60
  const dataDir = resolveDataDir(synth);
61
61
  const workspacesRoot = resolveWorkspacesRoot(synth);
62
62
  const maxUploadBytes = resolveMaxUploadBytes(synth);
63
+ const maxReadBytes = resolveMaxReadBytes(synth);
64
+ const maxPreviewBytes = resolveMaxPreviewBytes(synth);
63
65
  const port = resolvePort(synth, 'SYNTH_PORT', synth.server.port);
64
- return { synth, dataDir, workspacesRoot, maxUploadBytes, port, auth };
66
+ return { synth, dataDir, workspacesRoot, maxUploadBytes, maxReadBytes, maxPreviewBytes, port, auth };
65
67
  }
@@ -1,2 +1,2 @@
1
- export { DefaultsStore, UI_SCALE_MIN, UI_SCALE_MAX } from '@itphx/synth-core';
1
+ export { DefaultsStore, UI_SCALE_MIN, UI_SCALE_MAX, CHAT_SCALE_MIN, CHAT_SCALE_MAX } from '@itphx/synth-core';
2
2
  export type { AppearanceDefaults } from '@itphx/synth-core';
@@ -2,4 +2,4 @@
2
2
  // это просто `{dataDir}/defaults.json` + атомарная запись, без backend-специфики.
3
3
  // Здесь оставлен реэкспорт, чтобы существующие импорты (`../lib/defaults-store.js`)
4
4
  // не менялись. См. `@itphx/synth-core`.
5
- export { DefaultsStore, UI_SCALE_MIN, UI_SCALE_MAX } from '@itphx/synth-core';
5
+ export { DefaultsStore, UI_SCALE_MIN, UI_SCALE_MAX, CHAT_SCALE_MIN, CHAT_SCALE_MAX } from '@itphx/synth-core';
package/dist/lib/i18n.js CHANGED
@@ -20,6 +20,7 @@ const en = {
20
20
  'errors.validation.idRequired': 'id is required',
21
21
  'errors.validation.invalidAgentId': 'Agent ID may contain only Latin letters, digits, hyphen and underscore',
22
22
  'errors.validation.invalidRoleFile': 'Role file name must be a plain file name without paths and ".."',
23
+ 'errors.validation.invalidEffort': 'Invalid effort tier (allowed: low, medium, high, xhigh, max)',
23
24
  'errors.validation.urlRequired': 'url is required',
24
25
  'errors.validation.invalidUrl': 'Invalid URL',
25
26
  'errors.validation.apiKeyRequired': 'api_key is required',
@@ -152,9 +153,16 @@ const en = {
152
153
  'locales.ru.nativeName': 'Russian',
153
154
  // Chat
154
155
  'errors.chat.queueFull': 'Queue is full (max {max} messages)',
156
+ // Отключённые провайдер/модель — отказ до постановки в очередь.
157
+ 'errors.chat.providerDisabled': 'Provider "{provider}" is disabled — choose another model',
158
+ 'errors.chat.modelDisabled': 'Model {provider}/{model} is disabled — choose another model',
155
159
  'errors.chat.steerLimitExceeded': 'Steering limit reached (max {max} injected messages per turn)',
156
160
  // ADR-106 Ф3: подтверждение не принято (нет гранта / повторный ответ / чужой ход).
157
161
  'errors.chat.approvalDenied': 'Approval was not accepted: {reason}',
162
+ // Лимиты заметок сессии (`context.stickyNotes`).
163
+ 'errors.notFound.note': 'Note not found',
164
+ 'errors.validation.noteTooLong': 'Note text is too long (max {max} characters)',
165
+ 'errors.conflict.noteLimitReached': 'Session note limit reached (max {max})',
158
166
  // Stub
159
167
  'stub.llmNotConnected': '[Stub] You said: "{content}". LLM engine is not connected yet.',
160
168
  };
@@ -180,6 +188,7 @@ const ru = {
180
188
  'errors.validation.idRequired': 'id обязателен',
181
189
  'errors.validation.invalidAgentId': 'ID агента может содержать только латиницу, цифры, дефис и подчёркивание',
182
190
  'errors.validation.invalidRoleFile': 'Имя файла роли должно быть именем файла без путей и «..»',
191
+ 'errors.validation.invalidEffort': 'Некорректный тир усилия (effort): допустимые значения — low, medium, high, xhigh, max',
183
192
  'errors.validation.urlRequired': 'URL не указан',
184
193
  'errors.validation.invalidUrl': 'Некорректный URL',
185
194
  'errors.validation.apiKeyRequired': 'api_key обязателен',
@@ -313,9 +322,16 @@ const ru = {
313
322
  'locales.ru.nativeName': 'Русский',
314
323
  // Chat
315
324
  'errors.chat.queueFull': 'Очередь переполнена (максимум {max} сообщений)',
325
+ // Отключённые провайдер/модель — отказ до постановки в очередь.
326
+ 'errors.chat.providerDisabled': 'Провайдер «{provider}» отключён — выберите другую модель',
327
+ 'errors.chat.modelDisabled': 'Модель {provider}/{model} отключена — выберите другую модель',
316
328
  'errors.chat.steerLimitExceeded': 'Достигнут лимит вмешательств в ход (максимум {max} сообщений на ход)',
317
329
  // ADR-106 Ф3: подтверждение не принято (нет гранта / повторный ответ / чужой ход).
318
330
  'errors.chat.approvalDenied': 'Подтверждение не принято: {reason}',
331
+ // Лимиты заметок сессии (`context.stickyNotes`).
332
+ 'errors.notFound.note': 'Заметка не найдена',
333
+ 'errors.validation.noteTooLong': 'Текст заметки слишком длинный (максимум {max} символов)',
334
+ 'errors.conflict.noteLimitReached': 'Достигнут лимит заметок сессии (максимум {max})',
319
335
  // Stub
320
336
  'stub.llmNotConnected': '[Заглушка] Вы сказали: "{content}". LLM-движок ещё не подключён.',
321
337
  };
@@ -16,9 +16,14 @@ export function createRecalcCanSummarize({ sessionManager, contextOptimizer, eve
16
16
  const can = contextOptimizer.canSummarize(s);
17
17
  // Перепроверить флаг summarizationPending при toggle/pin/delete
18
18
  let shouldClearPending = false;
19
- if (s.summarizationPending && s.settings.summarizationEnabled) {
20
- const sumResult = contextOptimizer.shouldSummarize(s);
21
- if (!sumResult.triggered) {
19
+ if (s.summarizationPending) {
20
+ const compression = typeof contextOptimizer.shouldCompress === 'function'
21
+ ? contextOptimizer.shouldCompress(s)
22
+ : { ...contextOptimizer.shouldSummarize(s), mode: 'summarization' };
23
+ if (!compression.triggered || !compression.mode) {
24
+ shouldClearPending = true;
25
+ }
26
+ else if (typeof contextOptimizer.canCompress === 'function' && !contextOptimizer.canCompress(s)) {
22
27
  shouldClearPending = true;
23
28
  }
24
29
  }