@itphx/synth-backend 0.11.3 → 0.12.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.
@@ -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,9 @@
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 { nowISO, MessageRole, generateStreamId, isSteerMode, DEFAULT_STEER_MODE, MAX_STEER_INJECTIONS_PER_TURN, STEERING_ERROR_CODES } from '@itphx/synth-shared';
9
+ import { t } from '../lib/i18n.js';
9
10
  /**
10
11
  * Вспомогательная функция для конвертации Node Request в Web Request.
11
12
  */
@@ -180,6 +181,13 @@ export function createBackendListen(deps) {
180
181
  if (!sid || !msg.content?.trim())
181
182
  return;
182
183
  const streamId = msg.stream_id || generateStreamId();
184
+ // ADR-104: режим отправки. `steer` — вмешательство в активный
185
+ // ход, `interrupt` — прерывание текущей генерации (ход при этом
186
+ // НЕ завершается).
187
+ const mode = isSteerMode(msg.mode) ? msg.mode : DEFAULT_STEER_MODE;
188
+ // Для `steer`/`interrupt` подтверждение уходит после приёма
189
+ // сообщения (иначе «queued» означало бы принятое, но отброшенное).
190
+ const steerMode = mode !== 'queue';
183
191
  (async () => {
184
192
  const session = await loadVisibleSession(sid);
185
193
  if (!session) {
@@ -191,12 +199,18 @@ export function createBackendListen(deps) {
191
199
  }));
192
200
  return;
193
201
  }
194
- ws.send(JSON.stringify({
195
- type: 'queued',
196
- session_id: sid,
197
- stream_id: streamId,
198
- timestamp: nowISO(),
199
- }));
202
+ if (!steerMode) {
203
+ ws.send(JSON.stringify({
204
+ type: 'queued',
205
+ session_id: sid,
206
+ stream_id: streamId,
207
+ mode,
208
+ // ADR-104 (этап 3): единый контракт режима — клиенту
209
+ // видно, какой режим применён и применился ли он.
210
+ mode_applied: true,
211
+ timestamp: nowISO(),
212
+ }));
213
+ }
200
214
  const message = {
201
215
  id: streamId,
202
216
  role: MessageRole.USER,
@@ -214,7 +228,54 @@ export function createBackendListen(deps) {
214
228
  model: msg.model || session.settings.model,
215
229
  metadata: { stream_id: streamId },
216
230
  };
217
- const result = await enqueueUserMessage(sessionManager, eventBus, sid, message, queueManager, processMessage, (msgSid, msg) => orchestrator.obfuscateUserMessageForHistory(msgSid, msg));
231
+ // ADR-106 Ф4: принципал ввода фиксируется **при приёме ввода**
232
+ // (постановка в очередь) — не пересчитывается при исполнении.
233
+ // service-key (`service:<keyId>`) — отдельный вид принципала.
234
+ const turnPrincipal = resolveUserPrincipal(user.id);
235
+ // ADR-104: `steer` — вмешательство в активный ход, `interrupt` —
236
+ // прерывание текущей генерации (ход НЕ завершается). Если хода
237
+ // нет — обычная очередь (сообщение начнёт новый ход).
238
+ if (steerMode && (session.status?.blocked || queueManager.isRunning(sid))) {
239
+ const interruptMode = mode === 'interrupt';
240
+ const steerResult = await enqueueSteerMessage(sessionManager, eventBus, sid, message, MAX_STEER_INJECTIONS_PER_TURN, (msgSid, steerMsg) => orchestrator.obfuscateUserMessageForHistory(msgSid, steerMsg),
241
+ // ADR-106 Ф4: принципал ввода; инъекция не создаёт новый
242
+ // ход (ADR-104) — принципал текущего хода не меняется.
243
+ {
244
+ interrupt: interruptMode,
245
+ ...(turnPrincipal ? { principal: turnPrincipal } : {}),
246
+ });
247
+ if (!steerResult.accepted) {
248
+ ws.send(JSON.stringify({
249
+ type: 'error',
250
+ session_id: sid,
251
+ data: {
252
+ error: t('errors.chat.steerLimitExceeded', { max: MAX_STEER_INJECTIONS_PER_TURN }),
253
+ code: STEERING_ERROR_CODES.limitExceeded,
254
+ },
255
+ timestamp: nowISO(),
256
+ }));
257
+ return;
258
+ }
259
+ if (interruptMode) {
260
+ // Прерываем текущую генерацию (ход продолжается) — сообщение
261
+ // уже в очереди инъекций, поэтому инъекция гарантированно
262
+ // попадёт в ход на ближайшей границе шага.
263
+ const liveStreamId = session.currentStream?.streamId;
264
+ if (liveStreamId)
265
+ orchestrator.interrupt(liveStreamId);
266
+ }
267
+ ws.send(JSON.stringify({
268
+ type: 'queued',
269
+ session_id: sid,
270
+ stream_id: streamId,
271
+ mode,
272
+ // ADR-104 (этап 3): локальная сторона применила режим сама.
273
+ mode_applied: true,
274
+ timestamp: nowISO(),
275
+ }));
276
+ return;
277
+ }
278
+ const result = await enqueueUserMessage(sessionManager, eventBus, sid, message, queueManager, processMessage, (msgSid, msg) => orchestrator.obfuscateUserMessageForHistory(msgSid, msg), turnPrincipal ? { principal: turnPrincipal } : undefined);
218
279
  if (!result) {
219
280
  ws.send(JSON.stringify({
220
281
  type: 'queue.stalled',
@@ -246,17 +307,73 @@ export function createBackendListen(deps) {
246
307
  const action = msg.action === 'allow' || msg.action === 'deny' ? msg.action : undefined;
247
308
  const approved = action !== undefined ? action === 'allow' : msg.approved === true;
248
309
  const once = typeof msg.once === 'boolean' ? msg.once : undefined;
310
+ // ADR-106 Ф0: аддитивные поля `principal`/`turn_id`.
311
+ const principal = parsePermissionPrincipal(msg.principal);
312
+ const turnId = typeof msg.turn_id === 'string' && msg.turn_id.trim() !== '' ? msg.turn_id : undefined;
249
313
  (async () => {
250
314
  // ADR-089 (P0): подтверждать права можно только в своей сессии.
251
315
  const session = await loadVisibleSession(sid);
252
316
  if (!session)
253
317
  return;
318
+ // ADR-106 Ф3: ответ принимает только **носитель покрывающего
319
+ // гранта**, а не «кто видит сессию» (дыра «`VIEWER`
320
+ // подтверждает мутирующий тул»). Реестр не задан — слой
321
+ // Authority выключен/в shadow, поведение прежнее.
322
+ const registry = deps.approvalRegistry;
323
+ if (!registry) {
324
+ eventBus.publish(sid, 'permission.replied', {
325
+ approval_id: approvalId,
326
+ session_id: sid,
327
+ approved,
328
+ ...(action ? { action } : {}),
329
+ ...(once !== undefined ? { once } : {}),
330
+ ...(principal ? { principal } : {}),
331
+ ...(turnId ? { turn_id: turnId } : {}),
332
+ });
333
+ return;
334
+ }
335
+ // Принципал-отвечающий — **аутентифицированный** (клиенту не
336
+ // доверяем): подтверждать может только носитель гранта.
337
+ const responder = {
338
+ kind: 'user',
339
+ id: user.id,
340
+ roles: user.roles ?? [],
341
+ };
342
+ const claim = await registry.claim(approvalId, sid, responder, {
343
+ ...(turnId ? { turnId } : {}),
344
+ ...(typeof msg.digest === 'string' && msg.digest !== '' ? { digest: msg.digest } : {}),
345
+ });
346
+ if (!claim.ok) {
347
+ // Отказ: подтверждение не принимается (нет гранта / повторный
348
+ // ответ / чужой ход) — действие не выполняется.
349
+ eventBus.publish(sid, 'permission.replied', {
350
+ approval_id: approvalId,
351
+ session_id: sid,
352
+ approved: false,
353
+ action: 'deny',
354
+ reason: claim.reason,
355
+ });
356
+ ws.send(JSON.stringify({
357
+ type: 'error',
358
+ session_id: sid,
359
+ data: {
360
+ error: t('errors.chat.approvalDenied', { reason: claim.reason }),
361
+ code: 'APPROVAL_DENIED',
362
+ },
363
+ timestamp: nowISO(),
364
+ }));
365
+ return;
366
+ }
254
367
  eventBus.publish(sid, 'permission.replied', {
255
368
  approval_id: approvalId,
256
369
  session_id: sid,
257
370
  approved,
258
371
  ...(action ? { action } : {}),
259
372
  ...(once !== undefined ? { once } : {}),
373
+ // Привязка — из реестра (серверный источник истины).
374
+ principal: responder,
375
+ turn_id: claim.binding?.turnId,
376
+ digest: claim.binding?.digest,
260
377
  });
261
378
  })().catch(() => { });
262
379
  }