@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
@@ -1,6 +1,6 @@
1
1
  import { IncomingMessage } from 'node:http';
2
2
  import type { Hono } from 'hono';
3
- import type { EventBus, SessionManager, QueueProcessorManager, ChatOrchestrator, ProjectRepository, MetricsRegistry } from '@itphx/synth-core';
3
+ import type { EventBus, SessionManager, QueueProcessorManager, ChatOrchestrator, ProjectRepository, MetricsRegistry, ApprovalRegistry } from '@itphx/synth-core';
4
4
  import type { AuthKit } from '../auth/middleware.js';
5
5
  import type { EventHub } from '../events/hub.js';
6
6
  export interface BackendListenDeps {
@@ -15,6 +15,12 @@ export interface BackendListenDeps {
15
15
  orchestrator: ChatOrchestrator;
16
16
  /** Порт по умолчанию (`backendConfig.port`). */
17
17
  defaultPort: number;
18
+ /**
19
+ * ADR-106 Ф3: реестр подтверждений. Задан — ответ на `permission_reply`
20
+ * принимает только **носитель покрывающего гранта** (не «кто видит сессию»).
21
+ * Не задан — поведение прежнее (слой Authority выключен/в shadow).
22
+ */
23
+ approvalRegistry?: ApprovalRegistry;
18
24
  /**
19
25
  * ADR-094: реестр метрик (задан только при `metrics.enabled`). WS-апгрейд не
20
26
  * проходит через Hono-middleware — активные соединения учитываются здесь.
@@ -4,8 +4,10 @@
4
4
  import { createServer } from 'node:http';
5
5
  import { Readable } from 'node:stream';
6
6
  import { WebSocketServer } from 'ws';
7
- import { enqueueUserMessage, isSessionVisible } from '@itphx/synth-core';
8
- import { nowISO, MessageRole, generateStreamId } from '@itphx/synth-shared';
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';
9
+ import { nowISO, MessageRole, generateStreamId, isSteerMode, DEFAULT_STEER_MODE, MAX_STEER_INJECTIONS_PER_TURN, STEERING_ERROR_CODES } from '@itphx/synth-shared';
10
+ import { t } from '../lib/i18n.js';
9
11
  /**
10
12
  * Вспомогательная функция для конвертации Node Request в Web Request.
11
13
  */
@@ -115,6 +117,21 @@ export function createBackendListen(deps) {
115
117
  const allSessions = user.id.startsWith('service:') || auth.hasRole({ get: () => user }, 'ADMIN', 'LEAD');
116
118
  wss.handleUpgrade(request, socket, head, (ws) => {
117
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'));
118
135
  // ADR-094: активное WS-соединение — в streams_active (не в гистограмме).
119
136
  const streams = deps.metrics?.gauge('synth_http_streams_active', 'Number of active long-lived streams (SSE/WebSocket).');
120
137
  streams?.inc();
@@ -125,19 +142,42 @@ export function createBackendListen(deps) {
125
142
  streamReleased = true;
126
143
  streams?.dec();
127
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
+ };
128
171
  const client = {
129
172
  userId: user.id,
130
173
  username: user.username,
131
174
  allSessions,
132
175
  send(event) {
133
- try {
134
- if (ws.readyState === ws.OPEN) {
135
- ws.send(JSON.stringify(event));
136
- }
137
- }
138
- catch {
139
- // ignore send errors
176
+ if (replaying) {
177
+ pending.push(event);
178
+ return;
140
179
  }
180
+ writeEvent(event);
141
181
  },
142
182
  };
143
183
  eventHub.registerClient(client).then(() => {
@@ -146,6 +186,16 @@ export function createBackendListen(deps) {
146
186
  type: 'connected',
147
187
  client_id: clientId,
148
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;
149
199
  }).catch(() => {
150
200
  ws.send(JSON.stringify({
151
201
  type: 'error',
@@ -180,6 +230,13 @@ export function createBackendListen(deps) {
180
230
  if (!sid || !msg.content?.trim())
181
231
  return;
182
232
  const streamId = msg.stream_id || generateStreamId();
233
+ // ADR-104: режим отправки. `steer` — вмешательство в активный
234
+ // ход, `interrupt` — прерывание текущей генерации (ход при этом
235
+ // НЕ завершается).
236
+ const mode = isSteerMode(msg.mode) ? msg.mode : DEFAULT_STEER_MODE;
237
+ // Для `steer`/`interrupt` подтверждение уходит после приёма
238
+ // сообщения (иначе «queued» означало бы принятое, но отброшенное).
239
+ const steerMode = mode !== 'queue';
183
240
  (async () => {
184
241
  const session = await loadVisibleSession(sid);
185
242
  if (!session) {
@@ -191,12 +248,18 @@ export function createBackendListen(deps) {
191
248
  }));
192
249
  return;
193
250
  }
194
- ws.send(JSON.stringify({
195
- type: 'queued',
196
- session_id: sid,
197
- stream_id: streamId,
198
- timestamp: nowISO(),
199
- }));
251
+ if (!steerMode) {
252
+ ws.send(JSON.stringify({
253
+ type: 'queued',
254
+ session_id: sid,
255
+ stream_id: streamId,
256
+ mode,
257
+ // ADR-104 (этап 3): единый контракт режима — клиенту
258
+ // видно, какой режим применён и применился ли он.
259
+ mode_applied: true,
260
+ timestamp: nowISO(),
261
+ }));
262
+ }
200
263
  const message = {
201
264
  id: streamId,
202
265
  role: MessageRole.USER,
@@ -214,7 +277,54 @@ export function createBackendListen(deps) {
214
277
  model: msg.model || session.settings.model,
215
278
  metadata: { stream_id: streamId },
216
279
  };
217
- const result = await enqueueUserMessage(sessionManager, eventBus, sid, message, queueManager, processMessage, (msgSid, msg) => orchestrator.obfuscateUserMessageForHistory(msgSid, msg));
280
+ // ADR-106 Ф4: принципал ввода фиксируется **при приёме ввода**
281
+ // (постановка в очередь) — не пересчитывается при исполнении.
282
+ // service-key (`service:<keyId>`) — отдельный вид принципала.
283
+ const turnPrincipal = resolveUserPrincipal(user.id);
284
+ // ADR-104: `steer` — вмешательство в активный ход, `interrupt` —
285
+ // прерывание текущей генерации (ход НЕ завершается). Если хода
286
+ // нет — обычная очередь (сообщение начнёт новый ход).
287
+ if (steerMode && (session.status?.blocked || queueManager.isRunning(sid))) {
288
+ const interruptMode = mode === 'interrupt';
289
+ const steerResult = await enqueueSteerMessage(sessionManager, eventBus, sid, message, MAX_STEER_INJECTIONS_PER_TURN, (msgSid, steerMsg) => orchestrator.obfuscateUserMessageForHistory(msgSid, steerMsg),
290
+ // ADR-106 Ф4: принципал ввода; инъекция не создаёт новый
291
+ // ход (ADR-104) — принципал текущего хода не меняется.
292
+ {
293
+ interrupt: interruptMode,
294
+ ...(turnPrincipal ? { principal: turnPrincipal } : {}),
295
+ });
296
+ if (!steerResult.accepted) {
297
+ ws.send(JSON.stringify({
298
+ type: 'error',
299
+ session_id: sid,
300
+ data: {
301
+ error: t('errors.chat.steerLimitExceeded', { max: MAX_STEER_INJECTIONS_PER_TURN }),
302
+ code: STEERING_ERROR_CODES.limitExceeded,
303
+ },
304
+ timestamp: nowISO(),
305
+ }));
306
+ return;
307
+ }
308
+ if (interruptMode) {
309
+ // Прерываем текущую генерацию (ход продолжается) — сообщение
310
+ // уже в очереди инъекций, поэтому инъекция гарантированно
311
+ // попадёт в ход на ближайшей границе шага.
312
+ const liveStreamId = session.currentStream?.streamId;
313
+ if (liveStreamId)
314
+ orchestrator.interrupt(liveStreamId);
315
+ }
316
+ ws.send(JSON.stringify({
317
+ type: 'queued',
318
+ session_id: sid,
319
+ stream_id: streamId,
320
+ mode,
321
+ // ADR-104 (этап 3): локальная сторона применила режим сама.
322
+ mode_applied: true,
323
+ timestamp: nowISO(),
324
+ }));
325
+ return;
326
+ }
327
+ const result = await enqueueUserMessage(sessionManager, eventBus, sid, message, queueManager, processMessage, (msgSid, msg) => orchestrator.obfuscateUserMessageForHistory(msgSid, msg), turnPrincipal ? { principal: turnPrincipal } : undefined);
218
328
  if (!result) {
219
329
  ws.send(JSON.stringify({
220
330
  type: 'queue.stalled',
@@ -246,17 +356,73 @@ export function createBackendListen(deps) {
246
356
  const action = msg.action === 'allow' || msg.action === 'deny' ? msg.action : undefined;
247
357
  const approved = action !== undefined ? action === 'allow' : msg.approved === true;
248
358
  const once = typeof msg.once === 'boolean' ? msg.once : undefined;
359
+ // ADR-106 Ф0: аддитивные поля `principal`/`turn_id`.
360
+ const principal = parsePermissionPrincipal(msg.principal);
361
+ const turnId = typeof msg.turn_id === 'string' && msg.turn_id.trim() !== '' ? msg.turn_id : undefined;
249
362
  (async () => {
250
363
  // ADR-089 (P0): подтверждать права можно только в своей сессии.
251
364
  const session = await loadVisibleSession(sid);
252
365
  if (!session)
253
366
  return;
367
+ // ADR-106 Ф3: ответ принимает только **носитель покрывающего
368
+ // гранта**, а не «кто видит сессию» (дыра «`VIEWER`
369
+ // подтверждает мутирующий тул»). Реестр не задан — слой
370
+ // Authority выключен/в shadow, поведение прежнее.
371
+ const registry = deps.approvalRegistry;
372
+ if (!registry) {
373
+ eventBus.publish(sid, 'permission.replied', {
374
+ approval_id: approvalId,
375
+ session_id: sid,
376
+ approved,
377
+ ...(action ? { action } : {}),
378
+ ...(once !== undefined ? { once } : {}),
379
+ ...(principal ? { principal } : {}),
380
+ ...(turnId ? { turn_id: turnId } : {}),
381
+ });
382
+ return;
383
+ }
384
+ // Принципал-отвечающий — **аутентифицированный** (клиенту не
385
+ // доверяем): подтверждать может только носитель гранта.
386
+ const responder = {
387
+ kind: 'user',
388
+ id: user.id,
389
+ roles: user.roles ?? [],
390
+ };
391
+ const claim = await registry.claim(approvalId, sid, responder, {
392
+ ...(turnId ? { turnId } : {}),
393
+ ...(typeof msg.digest === 'string' && msg.digest !== '' ? { digest: msg.digest } : {}),
394
+ });
395
+ if (!claim.ok) {
396
+ // Отказ: подтверждение не принимается (нет гранта / повторный
397
+ // ответ / чужой ход) — действие не выполняется.
398
+ eventBus.publish(sid, 'permission.replied', {
399
+ approval_id: approvalId,
400
+ session_id: sid,
401
+ approved: false,
402
+ action: 'deny',
403
+ reason: claim.reason,
404
+ });
405
+ ws.send(JSON.stringify({
406
+ type: 'error',
407
+ session_id: sid,
408
+ data: {
409
+ error: t('errors.chat.approvalDenied', { reason: claim.reason }),
410
+ code: 'APPROVAL_DENIED',
411
+ },
412
+ timestamp: nowISO(),
413
+ }));
414
+ return;
415
+ }
254
416
  eventBus.publish(sid, 'permission.replied', {
255
417
  approval_id: approvalId,
256
418
  session_id: sid,
257
419
  approved,
258
420
  ...(action ? { action } : {}),
259
421
  ...(once !== undefined ? { once } : {}),
422
+ // Привязка — из реестра (серверный источник истины).
423
+ principal: responder,
424
+ turn_id: claim.binding?.turnId,
425
+ digest: claim.binding?.digest,
260
426
  });
261
427
  })().catch(() => { });
262
428
  }