@itphx/synth-backend 0.10.1 → 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.
- package/dist/app/bootstrap.d.ts +2 -2
- package/dist/app/deps.d.ts +77 -33
- package/dist/app/deps.js +969 -102
- package/dist/app/listen.d.ts +13 -2
- package/dist/app/listen.js +138 -10
- package/dist/app/mount-routes.d.ts +16 -3
- package/dist/app/mount-routes.js +625 -32
- package/dist/app.d.ts +42 -7
- package/dist/app.js +149 -12
- package/dist/auth/guards.d.ts +17 -1
- package/dist/auth/guards.js +46 -2
- package/dist/auth/middleware.d.ts +2 -12
- package/dist/auth/middleware.js +20 -2
- package/dist/auth/oidc.d.ts +7 -0
- package/dist/auth/oidc.js +27 -6
- package/dist/auth/plugin-scope.d.ts +10 -0
- package/dist/auth/plugin-scope.js +69 -0
- package/dist/auth/service-scope.d.ts +7 -3
- package/dist/auth/service-scope.js +8 -4
- package/dist/events/hub.js +3 -38
- package/dist/lib/app-config.d.ts +2 -0
- package/dist/lib/app-config.js +3 -2
- package/dist/lib/defaults-store.d.ts +2 -25
- package/dist/lib/defaults-store.js +5 -87
- package/dist/lib/i18n.js +153 -0
- package/dist/main.js +67 -4
- package/dist/routes/agents.d.ts +12 -3
- package/dist/routes/agents.js +14 -2
- package/dist/routes/auth.d.ts +12 -2
- package/dist/routes/auth.js +16 -2
- package/dist/routes/context.d.ts +2 -2
- package/dist/routes/gateway-patterns.d.ts +2 -2
- package/dist/routes/llm.d.ts +8 -2
- package/dist/routes/llm.js +6 -3
- package/dist/routes/mcp-registry.d.ts +15 -3
- package/dist/routes/mcp-registry.js +122 -21
- package/dist/routes/messages.d.ts +7 -4
- package/dist/routes/messages.js +34 -3
- package/dist/routes/models.d.ts +7 -2
- package/dist/routes/models.js +3 -1
- package/dist/routes/processes.d.ts +34 -0
- package/dist/routes/processes.js +26 -0
- package/dist/routes/projects.d.ts +9 -3
- package/dist/routes/projects.js +8 -1
- package/dist/routes/providers.d.ts +15 -3
- package/dist/routes/providers.js +33 -21
- package/dist/routes/queue.d.ts +5 -4
- package/dist/routes/queue.js +30 -3
- package/dist/routes/sessions.d.ts +50 -3
- package/dist/routes/sessions.js +221 -74
- package/dist/test-helpers/close-server.d.ts +33 -0
- package/dist/test-helpers/close-server.js +50 -0
- package/package.json +4 -4
package/dist/app/listen.d.ts
CHANGED
|
@@ -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,
|
|
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 {
|
|
@@ -8,13 +8,24 @@ export interface BackendListenDeps {
|
|
|
8
8
|
auth: AuthKit;
|
|
9
9
|
eventHub: EventHub;
|
|
10
10
|
sessionManager: SessionManager;
|
|
11
|
-
projectStore:
|
|
11
|
+
projectStore: ProjectRepository;
|
|
12
12
|
eventBus: EventBus;
|
|
13
13
|
queueManager: QueueProcessorManager;
|
|
14
14
|
processMessage: ReturnType<ChatOrchestrator['createProcessMessage']>;
|
|
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;
|
|
24
|
+
/**
|
|
25
|
+
* ADR-094: реестр метрик (задан только при `metrics.enabled`). WS-апгрейд не
|
|
26
|
+
* проходит через Hono-middleware — активные соединения учитываются здесь.
|
|
27
|
+
*/
|
|
28
|
+
metrics?: MetricsRegistry;
|
|
18
29
|
}
|
|
19
30
|
/**
|
|
20
31
|
* Создать функцию `listen` хэндла приложения.
|
package/dist/app/listen.js
CHANGED
|
@@ -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
|
*/
|
|
@@ -115,6 +116,16 @@ export function createBackendListen(deps) {
|
|
|
115
116
|
const allSessions = user.id.startsWith('service:') || auth.hasRole({ get: () => user }, 'ADMIN', 'LEAD');
|
|
116
117
|
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
117
118
|
const clientId = `ws-events-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
119
|
+
// ADR-094: активное WS-соединение — в streams_active (не в гистограмме).
|
|
120
|
+
const streams = deps.metrics?.gauge('synth_http_streams_active', 'Number of active long-lived streams (SSE/WebSocket).');
|
|
121
|
+
streams?.inc();
|
|
122
|
+
let streamReleased = false;
|
|
123
|
+
const releaseStream = () => {
|
|
124
|
+
if (streamReleased)
|
|
125
|
+
return;
|
|
126
|
+
streamReleased = true;
|
|
127
|
+
streams?.dec();
|
|
128
|
+
};
|
|
118
129
|
const client = {
|
|
119
130
|
userId: user.id,
|
|
120
131
|
username: user.username,
|
|
@@ -135,7 +146,6 @@ export function createBackendListen(deps) {
|
|
|
135
146
|
ws.send(JSON.stringify({
|
|
136
147
|
type: 'connected',
|
|
137
148
|
client_id: clientId,
|
|
138
|
-
engine: 'synth',
|
|
139
149
|
}));
|
|
140
150
|
}).catch(() => {
|
|
141
151
|
ws.send(JSON.stringify({
|
|
@@ -171,6 +181,13 @@ export function createBackendListen(deps) {
|
|
|
171
181
|
if (!sid || !msg.content?.trim())
|
|
172
182
|
return;
|
|
173
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';
|
|
174
191
|
(async () => {
|
|
175
192
|
const session = await loadVisibleSession(sid);
|
|
176
193
|
if (!session) {
|
|
@@ -182,12 +199,18 @@ export function createBackendListen(deps) {
|
|
|
182
199
|
}));
|
|
183
200
|
return;
|
|
184
201
|
}
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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
|
+
}
|
|
191
214
|
const message = {
|
|
192
215
|
id: streamId,
|
|
193
216
|
role: MessageRole.USER,
|
|
@@ -205,7 +228,54 @@ export function createBackendListen(deps) {
|
|
|
205
228
|
model: msg.model || session.settings.model,
|
|
206
229
|
metadata: { stream_id: streamId },
|
|
207
230
|
};
|
|
208
|
-
|
|
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);
|
|
209
279
|
if (!result) {
|
|
210
280
|
ws.send(JSON.stringify({
|
|
211
281
|
type: 'queue.stalled',
|
|
@@ -237,17 +307,73 @@ export function createBackendListen(deps) {
|
|
|
237
307
|
const action = msg.action === 'allow' || msg.action === 'deny' ? msg.action : undefined;
|
|
238
308
|
const approved = action !== undefined ? action === 'allow' : msg.approved === true;
|
|
239
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;
|
|
240
313
|
(async () => {
|
|
241
314
|
// ADR-089 (P0): подтверждать права можно только в своей сессии.
|
|
242
315
|
const session = await loadVisibleSession(sid);
|
|
243
316
|
if (!session)
|
|
244
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
|
+
}
|
|
245
367
|
eventBus.publish(sid, 'permission.replied', {
|
|
246
368
|
approval_id: approvalId,
|
|
247
369
|
session_id: sid,
|
|
248
370
|
approved,
|
|
249
371
|
...(action ? { action } : {}),
|
|
250
372
|
...(once !== undefined ? { once } : {}),
|
|
373
|
+
// Привязка — из реестра (серверный источник истины).
|
|
374
|
+
principal: responder,
|
|
375
|
+
turn_id: claim.binding?.turnId,
|
|
376
|
+
digest: claim.binding?.digest,
|
|
251
377
|
});
|
|
252
378
|
})().catch(() => { });
|
|
253
379
|
}
|
|
@@ -276,9 +402,11 @@ export function createBackendListen(deps) {
|
|
|
276
402
|
});
|
|
277
403
|
ws.on('close', () => {
|
|
278
404
|
console.log(`[WS /ws/events] Disconnected: client=${clientId}`);
|
|
405
|
+
releaseStream();
|
|
279
406
|
eventHub.unregisterClient(client);
|
|
280
407
|
});
|
|
281
408
|
ws.on('error', () => {
|
|
409
|
+
releaseStream();
|
|
282
410
|
eventHub.unregisterClient(client);
|
|
283
411
|
});
|
|
284
412
|
});
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Hono } from 'hono';
|
|
2
|
-
import type {
|
|
2
|
+
import type { MetricsReadiness, MetricsRegistry } from '@itphx/synth-core';
|
|
3
3
|
import type { AuthKit } from '../auth/middleware.js';
|
|
4
4
|
import type { BackendConfig } from '../lib/app-config.js';
|
|
5
5
|
import type { BackendDeps } from './deps.js';
|
|
@@ -8,8 +8,21 @@ export interface BackendRoutesContext {
|
|
|
8
8
|
config: BackendConfig;
|
|
9
9
|
/** Зависимости backend (`createBackendDeps`). */
|
|
10
10
|
deps: BackendDeps;
|
|
11
|
-
/** ADR-
|
|
12
|
-
|
|
11
|
+
/** ADR-094: live-состояние метрик для админ-раздела «Наблюдаемость». */
|
|
12
|
+
metrics: BackendMetricsContext;
|
|
13
|
+
}
|
|
14
|
+
/** ADR-094: live-состояние метрик (паритет с core `StandaloneMetricsContext`). */
|
|
15
|
+
export interface BackendMetricsContext {
|
|
16
|
+
/** Фактический флаг старта процесса (`metricsEnabled`). */
|
|
17
|
+
runningEnabled: boolean;
|
|
18
|
+
/** Реестр метрик процесса (нет — экспорт выключен). */
|
|
19
|
+
getRegistry: () => MetricsRegistry | undefined;
|
|
20
|
+
/** Live-readiness (`GET /ready`). */
|
|
21
|
+
getReadiness: () => MetricsReadiness;
|
|
22
|
+
/** Физический backend хранения (`file`|`memory`|`postgres`). */
|
|
23
|
+
storageBackend: string;
|
|
24
|
+
/** Uptime процесса в секундах. */
|
|
25
|
+
getUptimeSec: () => number;
|
|
13
26
|
}
|
|
14
27
|
/**
|
|
15
28
|
* Смонтировать все `/api/v2/*`-роуты и служебные заглушки (`/api/config/themes`,
|