@itphx/synth-backend 0.10.0 → 0.11.3

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 (62) hide show
  1. package/dist/app/bootstrap.d.ts +11 -0
  2. package/dist/app/bootstrap.js +19 -0
  3. package/dist/app/deps.d.ts +124 -0
  4. package/dist/app/deps.js +751 -0
  5. package/dist/app/listen.d.ts +34 -0
  6. package/dist/app/listen.js +309 -0
  7. package/dist/app/mount-routes.d.ts +31 -0
  8. package/dist/app/mount-routes.js +696 -0
  9. package/dist/app/sse-events.d.ts +15 -0
  10. package/dist/app/sse-events.js +83 -0
  11. package/dist/app.d.ts +30 -17
  12. package/dist/app.js +164 -1337
  13. package/dist/auth/guards.d.ts +2 -1
  14. package/dist/auth/guards.js +10 -2
  15. package/dist/auth/middleware.d.ts +9 -14
  16. package/dist/auth/middleware.js +38 -6
  17. package/dist/auth/oidc.d.ts +22 -0
  18. package/dist/auth/oidc.js +68 -9
  19. package/dist/auth/service-scope.d.ts +8 -4
  20. package/dist/auth/service-scope.js +9 -5
  21. package/dist/events/hub.d.ts +2 -2
  22. package/dist/events/hub.js +3 -38
  23. package/dist/lib/app-config.d.ts +2 -0
  24. package/dist/lib/app-config.js +3 -2
  25. package/dist/lib/cors.d.ts +23 -0
  26. package/dist/lib/cors.js +24 -0
  27. package/dist/lib/defaults-store.d.ts +2 -25
  28. package/dist/lib/defaults-store.js +5 -87
  29. package/dist/lib/i18n.js +58 -6
  30. package/dist/main.js +23 -7
  31. package/dist/middleware/rate-limiter.d.ts +4 -1
  32. package/dist/middleware/rate-limiter.js +4 -2
  33. package/dist/routes/agents.d.ts +2 -2
  34. package/dist/routes/audit.d.ts +1 -1
  35. package/dist/routes/audit.js +2 -2
  36. package/dist/routes/auth.d.ts +2 -2
  37. package/dist/routes/auth.js +28 -4
  38. package/dist/routes/context.d.ts +2 -2
  39. package/dist/routes/gateway-patterns.d.ts +3 -3
  40. package/dist/routes/gateway-patterns.js +1 -1
  41. package/dist/routes/llm.d.ts +8 -2
  42. package/dist/routes/llm.js +9 -5
  43. package/dist/routes/mcp-registry.d.ts +6 -6
  44. package/dist/routes/mcp-registry.js +10 -10
  45. package/dist/routes/mcp.d.ts +1 -1
  46. package/dist/routes/mcp.js +1 -1
  47. package/dist/routes/messages.d.ts +5 -4
  48. package/dist/routes/messages.js +30 -3
  49. package/dist/routes/models.d.ts +7 -2
  50. package/dist/routes/models.js +3 -1
  51. package/dist/routes/projects.d.ts +7 -7
  52. package/dist/routes/projects.js +7 -7
  53. package/dist/routes/providers.d.ts +15 -3
  54. package/dist/routes/providers.js +34 -21
  55. package/dist/routes/queue.d.ts +5 -4
  56. package/dist/routes/queue.js +30 -3
  57. package/dist/routes/sessions.d.ts +14 -4
  58. package/dist/routes/sessions.js +234 -34
  59. package/dist/routes/users.js +1 -1
  60. package/dist/test-helpers/close-server.d.ts +33 -0
  61. package/dist/test-helpers/close-server.js +50 -0
  62. package/package.json +3 -3
@@ -0,0 +1,34 @@
1
+ import { IncomingMessage } from 'node:http';
2
+ import type { Hono } from 'hono';
3
+ import type { EventBus, SessionManager, QueueProcessorManager, ChatOrchestrator, ProjectRepository, MetricsRegistry } from '@itphx/synth-core';
4
+ import type { AuthKit } from '../auth/middleware.js';
5
+ import type { EventHub } from '../events/hub.js';
6
+ export interface BackendListenDeps {
7
+ app: Hono;
8
+ auth: AuthKit;
9
+ eventHub: EventHub;
10
+ sessionManager: SessionManager;
11
+ projectStore: ProjectRepository;
12
+ eventBus: EventBus;
13
+ queueManager: QueueProcessorManager;
14
+ processMessage: ReturnType<ChatOrchestrator['createProcessMessage']>;
15
+ orchestrator: ChatOrchestrator;
16
+ /** Порт по умолчанию (`backendConfig.port`). */
17
+ defaultPort: number;
18
+ /**
19
+ * ADR-094: реестр метрик (задан только при `metrics.enabled`). WS-апгрейд не
20
+ * проходит через Hono-middleware — активные соединения учитываются здесь.
21
+ */
22
+ metrics?: MetricsRegistry;
23
+ }
24
+ /**
25
+ * Создать функцию `listen` хэндла приложения.
26
+ *
27
+ * Поднять HTTP-сервер с WebSocket /ws/events на указанном порту
28
+ * (порт 0 → эфемерный). Возвращает фактический порт.
29
+ */
30
+ export declare function createBackendListen(deps: BackendListenDeps): (port?: number, host?: string) => Promise<{
31
+ server: import("http").Server<typeof IncomingMessage, typeof import("http").ServerResponse>;
32
+ wss: import("ws").Server<typeof import("ws").default, typeof IncomingMessage>;
33
+ port: number;
34
+ }>;
@@ -0,0 +1,309 @@
1
+ // HTTP/WS-адаптер backend: Node HTTP-сервер, прокачка ответа Hono в Node-ответ
2
+ // (включая SSE/долгоживущие стримы) и WebSocket `/ws/events` (ADR-008/009/024/089).
3
+ // Вынесено из `app.ts` (ADR-095, шаг 4b) — «вынос по швам», без изменения поведения.
4
+ import { createServer } from 'node:http';
5
+ import { Readable } from 'node:stream';
6
+ import { WebSocketServer } from 'ws';
7
+ import { enqueueUserMessage, isSessionVisible } from '@itphx/synth-core';
8
+ import { nowISO, MessageRole, generateStreamId } from '@itphx/synth-shared';
9
+ /**
10
+ * Вспомогательная функция для конвертации Node Request в Web Request.
11
+ */
12
+ function toWebRequest(req) {
13
+ const protocol = 'http';
14
+ const host = req.headers.host || 'localhost';
15
+ const url = `${protocol}://${host}${req.url || '/'}`;
16
+ const headers = new Headers();
17
+ for (const [k, v] of Object.entries(req.headers)) {
18
+ if (v)
19
+ headers.set(k, Array.isArray(v) ? v.join(', ') : v);
20
+ }
21
+ const method = req.method || 'GET';
22
+ const noBody = ['GET', 'HEAD'].includes(method) || !req.headers['content-length'];
23
+ return new Request(url, {
24
+ method,
25
+ headers,
26
+ body: noBody ? undefined : Readable.toWeb(req),
27
+ duplex: 'half',
28
+ });
29
+ }
30
+ /**
31
+ * Адаптер для auth.getCurrentUser из сырого IncomingMessage (WS upgrade).
32
+ */
33
+ function reqAdapter(req) {
34
+ const headers = new Headers();
35
+ for (const [k, v] of Object.entries(req.headers)) {
36
+ if (v)
37
+ headers.set(k, Array.isArray(v) ? v.join(', ') : v);
38
+ }
39
+ return {
40
+ req: {
41
+ header(name) {
42
+ const h = req.headers[name.toLowerCase()];
43
+ if (!h)
44
+ return undefined;
45
+ return Array.isArray(h) ? h[0] : h;
46
+ },
47
+ raw: { headers },
48
+ },
49
+ };
50
+ }
51
+ /**
52
+ * Создать функцию `listen` хэндла приложения.
53
+ *
54
+ * Поднять HTTP-сервер с WebSocket /ws/events на указанном порту
55
+ * (порт 0 → эфемерный). Возвращает фактический порт.
56
+ */
57
+ export function createBackendListen(deps) {
58
+ const { app, auth, eventHub, sessionManager, projectStore, eventBus, queueManager, processMessage, orchestrator } = deps;
59
+ return async function listen(port = deps.defaultPort, host = '0.0.0.0') {
60
+ // Создаем HTTP сервер с WebSocket
61
+ const server = createServer(async (req, res) => {
62
+ try {
63
+ const webReq = toWebRequest(req);
64
+ const response = await app.fetch(webReq, {});
65
+ if (!response) {
66
+ res.writeHead(500);
67
+ res.end();
68
+ return;
69
+ }
70
+ const headers = Object.fromEntries(response.headers.entries());
71
+ res.writeHead(response.status, headers);
72
+ // SSE/долгоживущие стримы: при chunked-кодировании Node не сбрасывает
73
+ // заголовки в сокет до первого write()/end(). Для пустого начала стрима
74
+ // (SSE до первого события/keepalive) клиент иначе не получит заголовки
75
+ // вовсе — сбрасываем head принудительно.
76
+ res.flushHeaders();
77
+ if (response.body) {
78
+ const reader = response.body.getReader();
79
+ const pump = async () => {
80
+ while (true) {
81
+ const { done, value } = await reader.read();
82
+ if (done)
83
+ break;
84
+ res.write(value);
85
+ }
86
+ res.end();
87
+ };
88
+ pump().catch(() => res.end());
89
+ }
90
+ else {
91
+ res.end();
92
+ }
93
+ }
94
+ catch {
95
+ res.writeHead(500);
96
+ res.end();
97
+ }
98
+ });
99
+ // WebSocket /ws/chat
100
+ const wss = new WebSocketServer({ noServer: true });
101
+ server.on('upgrade', async (request, socket, head) => {
102
+ const url = new URL(request.url || '', `http://${request.headers.host}`);
103
+ // Глобальный event-хаб для всех сессий пользователя
104
+ if (url.pathname === '/ws/events') {
105
+ const user = await auth.getCurrentUser(reqAdapter(request)).catch(() => null);
106
+ if (!user) {
107
+ socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
108
+ socket.destroy();
109
+ return;
110
+ }
111
+ // ADR-052 (этап IV) / ADR-089: тот же watch-all, что у SSE. В WS-апгрейде
112
+ // Hono-контекста нет, поэтому service-key распознаётся по синтетическому
113
+ // id `service:<keyId>` (его ставит резолвер `getCurrentUser`); ADMIN/LEAD —
114
+ // сквозной обзор. Обычный USER получает только свои сессии.
115
+ const allSessions = user.id.startsWith('service:') || auth.hasRole({ get: () => user }, 'ADMIN', 'LEAD');
116
+ wss.handleUpgrade(request, socket, head, (ws) => {
117
+ const clientId = `ws-events-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
118
+ // ADR-094: активное WS-соединение — в streams_active (не в гистограмме).
119
+ const streams = deps.metrics?.gauge('synth_http_streams_active', 'Number of active long-lived streams (SSE/WebSocket).');
120
+ streams?.inc();
121
+ let streamReleased = false;
122
+ const releaseStream = () => {
123
+ if (streamReleased)
124
+ return;
125
+ streamReleased = true;
126
+ streams?.dec();
127
+ };
128
+ const client = {
129
+ userId: user.id,
130
+ username: user.username,
131
+ allSessions,
132
+ send(event) {
133
+ try {
134
+ if (ws.readyState === ws.OPEN) {
135
+ ws.send(JSON.stringify(event));
136
+ }
137
+ }
138
+ catch {
139
+ // ignore send errors
140
+ }
141
+ },
142
+ };
143
+ eventHub.registerClient(client).then(() => {
144
+ console.log(`[WS /ws/events] Connected: client=${clientId} user=${user.username}`);
145
+ ws.send(JSON.stringify({
146
+ type: 'connected',
147
+ client_id: clientId,
148
+ }));
149
+ }).catch(() => {
150
+ ws.send(JSON.stringify({
151
+ type: 'error',
152
+ data: { error: 'Failed to register client' },
153
+ timestamp: nowISO(),
154
+ }));
155
+ });
156
+ /**
157
+ * ADR-089 (P0): сессия, доступная текущему клиенту, либо `null`.
158
+ * Единое правило видимости (`isSessionVisible`) — владелец/участник
159
+ * проекта; ADMIN/LEAD и service-key (allSessions) видят всё.
160
+ * Недоступная чужая сессия неотличима от несуществующей.
161
+ */
162
+ const loadVisibleSession = async (sid) => {
163
+ const session = await sessionManager.getSession(sid);
164
+ if (!session)
165
+ return null;
166
+ const visible = await isSessionVisible(session, projectStore, {
167
+ userId: user.id,
168
+ elevated: allSessions,
169
+ });
170
+ return visible ? session : null;
171
+ };
172
+ ws.on('message', (raw) => {
173
+ try {
174
+ const msg = JSON.parse(raw.toString());
175
+ if (msg.type === 'ping') {
176
+ ws.send(JSON.stringify({ type: 'pong' }));
177
+ }
178
+ else if (msg.type === 'send_message') {
179
+ const sid = msg.session_id;
180
+ if (!sid || !msg.content?.trim())
181
+ return;
182
+ const streamId = msg.stream_id || generateStreamId();
183
+ (async () => {
184
+ const session = await loadVisibleSession(sid);
185
+ if (!session) {
186
+ ws.send(JSON.stringify({
187
+ type: 'error',
188
+ session_id: sid,
189
+ data: { error: 'Session not found' },
190
+ timestamp: nowISO(),
191
+ }));
192
+ return;
193
+ }
194
+ ws.send(JSON.stringify({
195
+ type: 'queued',
196
+ session_id: sid,
197
+ stream_id: streamId,
198
+ timestamp: nowISO(),
199
+ }));
200
+ const message = {
201
+ id: streamId,
202
+ role: MessageRole.USER,
203
+ seq: session.messages.length + 1,
204
+ origin: 'local',
205
+ parts: [{ id: generateStreamId(), type: 'text', data: msg.content.trim() }],
206
+ content: msg.content.trim(),
207
+ createdAt: nowISO(),
208
+ disabled: false,
209
+ pinned: false,
210
+ hidden: false,
211
+ author: user.username,
212
+ agentRole: msg.agent_role || session.settings.agentRole,
213
+ provider: msg.provider || session.settings.provider,
214
+ model: msg.model || session.settings.model,
215
+ metadata: { stream_id: streamId },
216
+ };
217
+ const result = await enqueueUserMessage(sessionManager, eventBus, sid, message, queueManager, processMessage, (msgSid, msg) => orchestrator.obfuscateUserMessageForHistory(msgSid, msg));
218
+ if (!result) {
219
+ ws.send(JSON.stringify({
220
+ type: 'queue.stalled',
221
+ session_id: sid,
222
+ data: { pending_count: session.pendingMessages.length },
223
+ timestamp: nowISO(),
224
+ }));
225
+ }
226
+ })().catch(() => { });
227
+ }
228
+ else if (msg.type === 'cancel') {
229
+ const sid = msg.session_id;
230
+ if (!sid)
231
+ return;
232
+ (async () => {
233
+ const session = await loadVisibleSession(sid);
234
+ if (session?.currentStream) {
235
+ orchestrator.cancel(session.currentStream.streamId);
236
+ }
237
+ })().catch(() => { });
238
+ }
239
+ else if (msg.type === 'permission_reply') {
240
+ const sid = msg.session_id;
241
+ const approvalId = msg.approval_id;
242
+ if (!sid || !approvalId)
243
+ return;
244
+ // Новый формат: { action: 'allow'|'deny', once?: boolean }.
245
+ // Старый формат { approved: boolean } остаётся совместимым.
246
+ const action = msg.action === 'allow' || msg.action === 'deny' ? msg.action : undefined;
247
+ const approved = action !== undefined ? action === 'allow' : msg.approved === true;
248
+ const once = typeof msg.once === 'boolean' ? msg.once : undefined;
249
+ (async () => {
250
+ // ADR-089 (P0): подтверждать права можно только в своей сессии.
251
+ const session = await loadVisibleSession(sid);
252
+ if (!session)
253
+ return;
254
+ eventBus.publish(sid, 'permission.replied', {
255
+ approval_id: approvalId,
256
+ session_id: sid,
257
+ approved,
258
+ ...(action ? { action } : {}),
259
+ ...(once !== undefined ? { once } : {}),
260
+ });
261
+ })().catch(() => { });
262
+ }
263
+ else if (msg.type === 'permission_hold') {
264
+ const sid = msg.session_id;
265
+ const approvalId = msg.approval_id;
266
+ if (!sid || !approvalId)
267
+ return;
268
+ (async () => {
269
+ // «Остановить таймер»: publish permission.hold — оркестратор снимает
270
+ // авто-отклонение по таймауту, запрос ждёт ответа пользователя.
271
+ // ADR-089 (P0): только для своей сессии.
272
+ const session = await loadVisibleSession(sid);
273
+ if (!session)
274
+ return;
275
+ eventBus.publish(sid, 'permission.hold', {
276
+ approval_id: approvalId,
277
+ session_id: sid,
278
+ });
279
+ })().catch(() => { });
280
+ }
281
+ }
282
+ catch {
283
+ // ignore parse errors
284
+ }
285
+ });
286
+ ws.on('close', () => {
287
+ console.log(`[WS /ws/events] Disconnected: client=${clientId}`);
288
+ releaseStream();
289
+ eventHub.unregisterClient(client);
290
+ });
291
+ ws.on('error', () => {
292
+ releaseStream();
293
+ eventHub.unregisterClient(client);
294
+ });
295
+ });
296
+ return;
297
+ }
298
+ socket.write('HTTP/1.1 404 Not Found\r\n\r\n');
299
+ socket.destroy();
300
+ });
301
+ await new Promise((resolve, reject) => {
302
+ server.once('error', reject);
303
+ server.listen(port, host, () => resolve());
304
+ });
305
+ const address = server.address();
306
+ const actualPort = typeof address === 'object' && address ? address.port : port;
307
+ return { server, wss, port: actualPort };
308
+ };
309
+ }
@@ -0,0 +1,31 @@
1
+ import type { Hono } from 'hono';
2
+ import type { MetricsReadiness, MetricsRegistry } from '@itphx/synth-core';
3
+ import type { AuthKit } from '../auth/middleware.js';
4
+ import type { BackendConfig } from '../lib/app-config.js';
5
+ import type { BackendDeps } from './deps.js';
6
+ export interface BackendRoutesContext {
7
+ /** Конфиг backend (config.yaml + env + dataDir). */
8
+ config: BackendConfig;
9
+ /** Зависимости backend (`createBackendDeps`). */
10
+ deps: BackendDeps;
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;
26
+ }
27
+ /**
28
+ * Смонтировать все `/api/v2/*`-роуты и служебные заглушки (`/api/config/themes`,
29
+ * i18n-эндпоинты) в порядке, идентичном прежнему `createBackendApp`.
30
+ */
31
+ export declare function mountBackendRoutes(app: Hono, auth: AuthKit, ctx: BackendRoutesContext): void;