@itphx/synth-backend 0.3.0 → 0.5.7

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 (70) hide show
  1. package/dist/app.d.ts +47 -0
  2. package/dist/app.d.ts.map +1 -0
  3. package/dist/app.js +737 -0
  4. package/dist/app.js.map +1 -0
  5. package/dist/auth/middleware.d.ts +1 -1
  6. package/dist/auth/middleware.d.ts.map +1 -1
  7. package/dist/auth/middleware.js +27 -4
  8. package/dist/auth/middleware.js.map +1 -1
  9. package/dist/auth/oidc.d.ts +87 -0
  10. package/dist/auth/oidc.d.ts.map +1 -0
  11. package/dist/auth/oidc.js +210 -0
  12. package/dist/auth/oidc.js.map +1 -0
  13. package/dist/auth/oidc.test.d.ts +2 -0
  14. package/dist/auth/oidc.test.d.ts.map +1 -0
  15. package/dist/auth/oidc.test.js +39 -0
  16. package/dist/auth/oidc.test.js.map +1 -0
  17. package/dist/integration/hybrid.integration.test.d.ts +2 -0
  18. package/dist/integration/hybrid.integration.test.d.ts.map +1 -0
  19. package/dist/integration/hybrid.integration.test.js +289 -0
  20. package/dist/integration/hybrid.integration.test.js.map +1 -0
  21. package/dist/lib/app-config.d.ts.map +1 -1
  22. package/dist/lib/app-config.js +1 -0
  23. package/dist/lib/app-config.js.map +1 -1
  24. package/dist/lib/i18n.d.ts.map +1 -1
  25. package/dist/lib/i18n.js +12 -0
  26. package/dist/lib/i18n.js.map +1 -1
  27. package/dist/main.js +16 -570
  28. package/dist/main.js.map +1 -1
  29. package/dist/routes/audit.js +1 -1
  30. package/dist/routes/audit.js.map +1 -1
  31. package/dist/routes/auth.d.ts.map +1 -1
  32. package/dist/routes/auth.js +104 -12
  33. package/dist/routes/auth.js.map +1 -1
  34. package/dist/routes/auth.test.d.ts +2 -0
  35. package/dist/routes/auth.test.d.ts.map +1 -0
  36. package/dist/routes/auth.test.js +63 -0
  37. package/dist/routes/auth.test.js.map +1 -0
  38. package/dist/routes/llm.d.ts +25 -0
  39. package/dist/routes/llm.d.ts.map +1 -0
  40. package/dist/routes/llm.js +332 -0
  41. package/dist/routes/llm.js.map +1 -0
  42. package/dist/routes/llm.test.d.ts +2 -0
  43. package/dist/routes/llm.test.d.ts.map +1 -0
  44. package/dist/routes/llm.test.js +552 -0
  45. package/dist/routes/llm.test.js.map +1 -0
  46. package/dist/routes/models.d.ts +1 -1
  47. package/dist/routes/models.d.ts.map +1 -1
  48. package/dist/routes/models.js +11 -3
  49. package/dist/routes/models.js.map +1 -1
  50. package/dist/routes/models.test.js +68 -2
  51. package/dist/routes/models.test.js.map +1 -1
  52. package/dist/routes/projects.d.ts.map +1 -1
  53. package/dist/routes/projects.js +17 -2
  54. package/dist/routes/projects.js.map +1 -1
  55. package/dist/routes/projects.test.js +40 -0
  56. package/dist/routes/projects.test.js.map +1 -1
  57. package/dist/routes/providers.d.ts +1 -1
  58. package/dist/routes/providers.d.ts.map +1 -1
  59. package/dist/routes/providers.js +3 -1
  60. package/dist/routes/providers.js.map +1 -1
  61. package/dist/routes/providers.test.d.ts +2 -0
  62. package/dist/routes/providers.test.d.ts.map +1 -0
  63. package/dist/routes/providers.test.js +83 -0
  64. package/dist/routes/providers.test.js.map +1 -0
  65. package/dist/routes/sessions.d.ts.map +1 -1
  66. package/dist/routes/sessions.js +91 -7
  67. package/dist/routes/sessions.js.map +1 -1
  68. package/dist/routes/sessions.test.js +123 -0
  69. package/dist/routes/sessions.test.js.map +1 -1
  70. package/package.json +4 -3
package/dist/main.js CHANGED
@@ -1,332 +1,12 @@
1
- import { createServer } from 'node:http';
2
- import { join } from 'node:path';
3
- import { WebSocketServer } from 'ws';
4
- import { Readable } from 'node:stream';
5
- import { Hono } from 'hono';
6
- import { cors } from 'hono/cors';
7
- import { logger } from 'hono/logger';
8
- import { FileStore, SessionManager, EventBus, QueueProcessorManager, ContextConfig, ContextBuilder, ContextOptimizer, ChatOrchestrator, FileProfileStore, enqueueUserMessage, createToolRegistry, createAgentRegistry, McpManager, RuntimeSettingsStore, createSettingsRoutes, AuditLogger, mergeLlmGatewayConfig, mergeSecurityConfig, ProtectedPathsStore, SecretPatternStore, } from '@itphx/synth-core';
9
- import { nowISO, ensureDataDir, MessageRole, generateStreamId, findConfigPath } from '@itphx/synth-shared';
10
- import { loadBackendConfig } from './lib/app-config.js';
11
- import { createAuthMiddleware } from './auth/middleware.js';
12
- import { createAuthRoutes } from './routes/auth.js';
13
- import { createProjectRoutes } from './routes/projects.js';
14
- import { createSessionRoutes } from './routes/sessions.js';
15
- import { createMessageRoutes } from './routes/messages.js';
16
- import { createQueueRoutes } from './routes/queue.js';
17
- import { createFsRoutes } from './routes/fs.js';
18
- import { createProviderRoutes } from './routes/providers.js';
19
- import { createModelRoutes } from './routes/models.js';
20
- import { createAgentRoutes } from './routes/agents.js';
21
- import { createContextRoutes } from './routes/context.js';
22
- import { createDebugRoutes } from './routes/debug.js';
23
- import { createUserRoutes } from './routes/users.js';
24
- import { createGitRoutes } from './routes/git.js';
25
- import { createMcpRoutes } from './routes/mcp.js';
26
- import { createAuditRoutes } from './routes/audit.js';
27
- import { createLogsRoutes, resolveLogDir } from './routes/logs.js';
28
- import { createGatewayPatternsRoutes } from './routes/gateway-patterns.js';
29
- import { YamlMcpConfigStore } from './lib/mcp-config-store.js';
30
- import { t, getTranslations } from './lib/i18n.js';
31
- import { ProjectStore } from './storage/project-store.js';
32
- import { JsonStore } from './storage/json-store.js';
33
- import { EventHub } from './events/hub.js';
1
+ // Точка входа synth-backend. Тонкая обёртка над фабрикой createBackendApp
2
+ // (см. app.ts): строит приложение, слушает порт, обрабатывает graceful shutdown.
3
+ // Всё построение Hono-app (конфиг → auth → stores → orchestrator → routes)
4
+ // живёт в app.ts — это позволяет поднимать backend in-process в интеграционных
5
+ // тестах без запуска процесса.
6
+ import { createBackendApp } from './app.js';
34
7
  const host = process.env.SYNTH_HOST || '0.0.0.0';
35
- const app = new Hono();
36
- app.use(logger());
37
- // CORS настраивается после загрузки конфига
38
- // Health (без auth)
39
- app.get('/health', (c) => c.json({ status: 'healthy', version: '0.1.0', time: nowISO() }));
40
- app.get('/api/v2/health', (c) => c.json({ status: 'healthy', version: '0.1.0', time: nowISO() }));
41
- // Конфигурация
42
- const backendConfig = await loadBackendConfig();
43
- // Динамический CORS origin: если задан explicit ORIGIN через env var, использовать его;
44
- // если задан список allowedOrigins — проверять и эхо; если список пуст — разрешить все.
45
- const allowedOrigins = backendConfig.synth.server.allowedOrigins ?? [];
46
- const envCorsOrigin = process.env.SYNTH_CORS_ORIGIN;
47
- app.use(cors({
48
- origin: (origin) => {
49
- if (envCorsOrigin)
50
- return envCorsOrigin;
51
- if (!origin)
52
- return origin;
53
- if (allowedOrigins.length === 0)
54
- return origin;
55
- if (allowedOrigins.includes(origin))
56
- return origin;
57
- return allowedOrigins[0];
58
- },
59
- credentials: true,
60
- }));
61
- const auth = createAuthMiddleware(backendConfig.auth);
62
- // Прикрепляем пользователя ко всем запросам
63
- app.use('*', auth.attachUser);
64
- // Хранилища
65
- const dataDir = backendConfig.dataDir;
66
- await ensureDataDir(dataDir);
67
- const fileStore = new FileStore({ dataDir });
68
- const sessionManager = new SessionManager(fileStore);
69
- const projectStore = new ProjectStore({ dataDir });
70
- const providerStore = new JsonStore({ dataDir, subdir: 'providers' });
71
- const modelStore = new JsonStore({ dataDir, subdir: 'models' });
72
- const agentStore = new JsonStore({ dataDir, subdir: 'agents' });
73
- const contextConfig = new ContextConfig({ userDataDir: `${dataDir}/context` });
74
- const profilesStore = new FileProfileStore({ dataDir });
75
- // AD-036: хранилище кастомных regex-паттернов детекции секретов (override ?? дефолт)
76
- const patternStore = new SecretPatternStore({ dataDir });
77
- // Runtime-настройки (AD-005): workspace/mcp из {dataDir}/settings.json (переживают рестарт)
78
- const settingsStore = new RuntimeSettingsStore({ dataDir });
79
- // MCP
80
- const configPath = findConfigPath() || './config.yaml';
81
- const mcpConfigStore = new YamlMcpConfigStore(configPath);
82
- await mcpConfigStore.load();
83
- const mcpManager = new McpManager();
84
- mcpManager.setConfig(mcpConfigStore.getServers());
85
- // Auth routes (после profilesStore)
86
- app.route('/auth', createAuthRoutes(auth, backendConfig.auth, profilesStore, dataDir));
87
- // Сидирование тестовых пользователей (debug mode)
88
- if (backendConfig.auth.debugMode && backendConfig.auth.testUsers) {
89
- for (const tu of backendConfig.auth.testUsers) {
90
- profilesStore.getOrCreateProfile({
91
- username: tu.username,
92
- roles: tu.roles,
93
- }).catch((e) => console.warn('seed: failed to create profile for', tu.username, e));
94
- }
95
- }
96
- const eventBus = new EventBus();
97
- const queueManager = new QueueProcessorManager();
98
- // Context builder
99
- const contextBuilder = new ContextBuilder(contextConfig, {
100
- profilesStore,
101
- projectDataDir: `${dataDir}/projects`,
102
- defaultLanguage: 'ru',
103
- });
104
- // Provider loader
105
- const providerLoader = (name) => {
106
- // При старте загружаем все конфиги — JsonStore.list() не подходит для быстрого lookup
107
- // поэтому кешируем провайдеров в Map
108
- return providerCache.get(name) ?? null;
109
- };
110
- // Кеш провайдеров (заполняется при старте)
111
- const providerCache = new Map();
112
- (await providerStore.list()).forEach((p) => {
113
- providerCache.set(p.name, p);
114
- });
115
- // Кеш моделей (заполняется при старте)
116
- const modelCache = new Map();
117
- (await modelStore.list()).forEach((m) => {
118
- modelCache.set(m.id, m);
119
- });
120
- // Загрузчик сохранённого контекстного окна модели (ModelConfig.contextWindow)
121
- const modelWindowLoader = (modelName) => {
122
- for (const m of modelCache.values()) {
123
- if (m.name === modelName || m.id === modelName) {
124
- return m.contextWindow && m.contextWindow > 0 ? m.contextWindow : 0;
125
- }
126
- }
127
- return 0;
128
- };
129
- // ContextOptimizer
130
- const summarizationConfig = backendConfig.synth.summarization;
131
- const contextOptimizer = new ContextOptimizer(contextConfig, providerLoader, summarizationConfig, modelWindowLoader);
132
- // Set ContextOptimizer on QueueProcessorManager
133
- queueManager.setContextOptimizer(contextOptimizer);
134
- // Model price loader
135
- const modelPriceLoader = (modelName) => {
136
- // Поиск по имени модели в кэше (сначала по полному ID, потом по name)
137
- for (const m of modelCache.values()) {
138
- if (m.name === modelName || m.id === modelName) {
139
- return {
140
- inputPrice: m.inputPrice,
141
- outputPrice: m.outputPrice,
142
- cacheReadPrice: m.cacheReadPrice,
143
- cacheWritePrice: m.cacheWritePrice,
144
- };
145
- }
146
- }
147
- return null;
148
- };
149
- // LLM Gateway: общий AuditLogger создаётся снаружи, чтобы эндпоинт
150
- // GET /api/v2/audit и оркестратор писали/читали один и тот же JSONL-файл.
151
- const gatewayAuditLogger = new AuditLogger(backendConfig.synth.llmGateway.audit.logPath || join(dataDir, 'audit', 'llm-gateway.jsonl'));
152
- // Полный лог запросов/ответов LLM (после обфускации) — один JSONL-файл для
153
- // записи (оркестратор) и чтения (GET /api/v2/logs/llm).
154
- const gatewayPayloadLogPath = backendConfig.synth.llmGateway.payloadLogPath
155
- || join(dataDir, 'audit', 'llm-payloads.jsonl');
156
- // AD-036: runtime-настройка LLM Gateway (тумблер из UI, {dataDir}/settings.json)
157
- // приоритетнее config.yaml — мёржим при старте, чтобы шлюз применялся к оркестратору.
158
- const runtimeGateway = await settingsStore.getLlmGatewaySettings();
159
- const gatewayConfig = mergeLlmGatewayConfig(backendConfig.synth.llmGateway, runtimeGateway);
160
- // AD-040: runtime-настройка защищённых путей (тумблер из UI, {dataDir}/settings.json)
161
- // приоритетнее config.yaml — мёржим при старте, чтобы защита применялась к оркестратору.
162
- const runtimeSecurity = await settingsStore.getSecuritySettings();
163
- const securityConfig = mergeSecurityConfig(backendConfig.synth.security, runtimeSecurity);
164
- const protectedPathsStore = new ProtectedPathsStore({ dataDir });
165
- // Orchestrator
166
- const toolRegistry = createToolRegistry();
167
- const agentRegistry = createAgentRegistry(toolRegistry, join(dataDir, 'agents'));
168
- const orchestrator = new ChatOrchestrator({
169
- sessionManager,
170
- eventBus,
171
- contextBuilder,
172
- contextConfig,
173
- providerLoader,
174
- contextOptimizer,
175
- modelPriceLoader,
176
- dataDir,
177
- toolRegistry,
178
- agentRegistry,
179
- mcpManager,
180
- projectStore,
181
- workspacesRoot: backendConfig.workspacesRoot,
182
- routerConfig: backendConfig.synth.router,
183
- permissionConfig: backendConfig.synth.permission,
184
- defaultPlanMode: backendConfig.synth.session.planMode,
185
- securityConfig,
186
- gatewayConfig,
187
- gatewayAuditLogger,
188
- gatewayPayloadLogPath,
189
- gatewayPatternStore: patternStore,
190
- });
191
- const processMessage = orchestrator.createProcessMessage();
192
- // EventHub — центральный диспетчер подписок
193
- const eventHub = new EventHub(eventBus, sessionManager);
194
- // API-заглушки для UI
195
- app.get('/api/config/themes', (c) => c.json({ themes: [] }));
196
- // i18n endpoints
197
- app.get('/api/v2/i18n/current', (c) => {
198
- const header = c.req.header('Accept-Language');
199
- const lang = header?.split(',')[0]?.trim()?.slice(0, 2) === 'en' ? 'en' : 'ru';
200
- return c.json({ language: lang, locale: lang });
201
- });
202
- app.get('/api/v2/i18n/translations/ru', (c) => c.json(getTranslations('ru')));
203
- app.get('/api/v2/i18n/translations/en', (c) => c.json(getTranslations('en')));
204
- // Projects routes
205
- app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, backendConfig.workspacesRoot));
206
- // Sessions routes
207
- app.route('/api/v2/sessions', createSessionRoutes(auth, sessionManager, eventBus, queueManager, processMessage, orchestrator, eventHub, contextOptimizer, projectStore));
208
- // Messages routes
209
- app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus));
210
- // Queue routes
211
- app.route('/api/v2/queue', createQueueRoutes(auth, sessionManager, queueManager, eventBus, processMessage));
212
- // FS routes
213
- app.route('/api/v2/fs', createFsRoutes(auth, projectStore, backendConfig.workspacesRoot));
214
- // Providers routes
215
- app.route('/api/v2/providers', createProviderRoutes(auth, providerStore));
216
- // Models routes
217
- app.route('/api/v2/models', createModelRoutes(auth, modelStore, providerStore));
218
- // Agents routes
219
- app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, sessionManager, agentRegistry));
220
- // Context routes
221
- app.route('/api/v2/context', createContextRoutes(auth, contextConfig));
222
- // User admin routes
223
- app.route('/api/v2/users', createUserRoutes(auth, profilesStore));
224
- // Git routes
225
- app.route('/api/v2/git', createGitRoutes(auth, projectStore, backendConfig.workspacesRoot));
226
- // MCP routes
227
- app.route('/api/v2/mcp', createMcpRoutes(auth, mcpConfigStore, mcpManager, sessionManager));
228
- // LLM Gateway audit routes (AD-036) — GET только ADMIN/AUDITOR, POST /revealed — все авторизованные
229
- app.route('/api/v2/audit', createAuditRoutes(auth, {
230
- auditLogPath: gatewayAuditLogger.logPath,
231
- sessionExists: async (sessionId) => {
232
- const session = await sessionManager.getSession(sessionId);
233
- return session !== null;
234
- },
235
- logger: gatewayAuditLogger,
236
- }));
237
- // Логи сервисов (core/ui/backend) + полный лог запросов/ответов LLM — чтение, только ADMIN/AUDITOR
238
- app.route('/api/v2/logs', createLogsRoutes(auth, {
239
- logDir: resolveLogDir(),
240
- payloadLogPath: gatewayPayloadLogPath,
241
- }));
242
- // LLM Gateway patterns routes (AD-036) — управление regex-паттернами детекции секретов, только ADMIN
243
- app.route('/api/v2/gateway', createGatewayPatternsRoutes(auth, patternStore));
244
- // Settings routes (runtime-настройки для UI: workspace + mcp; переиспользуем core-реализацию)
245
- app.route('/api/v2/settings', createSettingsRoutes(auth, {
246
- settingsStore,
247
- fallbackWorkspace: join(dataDir, 'workspaces', 'default'),
248
- // AD-036: live-применение тумблера LLM Gateway из UI — без рестарта сервера.
249
- onLlmGatewayChange: async (runtime) => {
250
- const merged = mergeLlmGatewayConfig(backendConfig.synth.llmGateway, runtime);
251
- orchestrator.setGatewayConfig(merged);
252
- },
253
- // live-применение тумблера защищённых путей из UI — без рестарта сервера.
254
- onSecurityChange: async (runtime) => {
255
- const merged = mergeSecurityConfig(backendConfig.synth.security, runtime);
256
- orchestrator.setSecurityConfig(merged);
257
- },
258
- protectedPathsStore,
259
- }));
260
- // Глобальный SSE-хаб для всех сессий пользователя
261
- app.get('/api/v2/events', auth.requireAuth, async (c) => {
262
- const user = auth.getCurrentUser(c);
263
- const signal = c.req.raw.signal;
264
- return new Response(new ReadableStream({
265
- async start(controller) {
266
- const encoder = new TextEncoder();
267
- const sseClient = {
268
- userId: user.id,
269
- username: user.username,
270
- send(event) {
271
- try {
272
- const line = `data: ${JSON.stringify(event)}\n\n`;
273
- controller.enqueue(encoder.encode(line));
274
- }
275
- catch {
276
- // client disconnected
277
- }
278
- },
279
- };
280
- try {
281
- console.log(`[SSE /api/v2/events] Connected: user=${user.username}`);
282
- await eventHub.registerClient(sseClient);
283
- // Keepalive: раз в 30 секунд отправляем комментарий для предотвращения разрыва
284
- const keepalive = setInterval(() => {
285
- try {
286
- controller.enqueue(encoder.encode(':keepalive\n\n'));
287
- }
288
- catch {
289
- clearInterval(keepalive);
290
- }
291
- }, 30_000);
292
- // Keep connection alive until abort or disconnect
293
- try {
294
- await new Promise((resolve) => {
295
- if (signal.aborted) {
296
- resolve();
297
- return;
298
- }
299
- signal.addEventListener('abort', () => resolve(), { once: true });
300
- });
301
- }
302
- finally {
303
- clearInterval(keepalive);
304
- }
305
- }
306
- catch (err) {
307
- console.error('[SSE /api/v2/events] Error:', err);
308
- }
309
- finally {
310
- eventHub.unregisterClient(sseClient);
311
- try {
312
- controller.close();
313
- }
314
- catch { /* already closed */ }
315
- }
316
- },
317
- }), {
318
- status: 200,
319
- headers: {
320
- 'Content-Type': 'text/event-stream',
321
- 'Cache-Control': 'no-cache',
322
- 'Connection': 'keep-alive',
323
- 'X-Accel-Buffering': 'no',
324
- },
325
- });
326
- });
327
- // Admin routes
328
- app.get('/admin/sessions/blocked', auth.requireAdmin, (c) => c.json({ sessions: [], count: 0 }));
329
- app.route('/api/v2/admin/debug', createDebugRoutes(auth));
8
+ const handle = await createBackendApp();
9
+ const { app, dataDir, port, config, auth, eventHub, queueManager, sessionManager } = handle;
330
10
  let shuttingDown = false;
331
11
  async function gracefulShutdown(signal) {
332
12
  if (shuttingDown)
@@ -371,258 +51,24 @@ async function waitForStreamsDrain() {
371
51
  await new Promise((r) => setTimeout(r, 200));
372
52
  }
373
53
  }
374
- // Graceful shutdown — POST /admin/shutdown (только ADMIN)
54
+ // Graceful shutdown — POST /admin/shutdown (только ADMIN).
55
+ // Регистрируется здесь, т.к. требует server/gracefulShutdown.
375
56
  app.post('/admin/shutdown', auth.requireAdmin, async (c) => {
376
57
  void gracefulShutdown('API');
377
58
  return c.json({ status: 'shutting_down' });
378
59
  });
60
+ // Admin routes
61
+ app.get('/admin/sessions/blocked', auth.requireAdmin, (c) => c.json({ sessions: [], count: 0 }));
379
62
  process.on('SIGTERM', () => { void gracefulShutdown('SIGTERM'); });
380
63
  process.on('SIGINT', () => { void gracefulShutdown('SIGINT'); });
381
- // 404
382
- app.notFound((c) => {
383
- return c.json({
384
- error: {
385
- code: 'NOT_FOUND',
386
- message: t('errors.notFound.route', { method: c.req.method, path: c.req.path }, c),
387
- },
388
- }, 404);
389
- });
390
- const port = backendConfig.port;
391
- // Вспомогательная функция для конвертации Node Request в Web Request
392
- function toWebRequest(req) {
393
- const protocol = 'http';
394
- const host = req.headers.host || 'localhost';
395
- const url = `${protocol}://${host}${req.url || '/'}`;
396
- const headers = new Headers();
397
- for (const [k, v] of Object.entries(req.headers)) {
398
- if (v)
399
- headers.set(k, Array.isArray(v) ? v.join(', ') : v);
400
- }
401
- const method = req.method || 'GET';
402
- const noBody = ['GET', 'HEAD'].includes(method) || !req.headers['content-length'];
403
- return new Request(url, {
404
- method,
405
- headers,
406
- body: noBody ? undefined : Readable.toWeb(req),
407
- duplex: 'half',
408
- });
409
- }
410
- // Создаем HTTP сервер с WebSocket
411
- const server = createServer(async (req, res) => {
412
- try {
413
- const webReq = toWebRequest(req);
414
- const response = await app.fetch(webReq, {});
415
- if (!response) {
416
- res.writeHead(500);
417
- res.end();
418
- return;
419
- }
420
- const headers = Object.fromEntries(response.headers.entries());
421
- res.writeHead(response.status, headers);
422
- if (response.body) {
423
- const reader = response.body.getReader();
424
- const pump = async () => {
425
- while (true) {
426
- const { done, value } = await reader.read();
427
- if (done)
428
- break;
429
- res.write(value);
430
- }
431
- res.end();
432
- };
433
- pump().catch(() => res.end());
434
- }
435
- else {
436
- res.end();
437
- }
438
- }
439
- catch {
440
- res.writeHead(500);
441
- res.end();
442
- }
443
- });
444
- // WebSocket /ws/chat
445
- const wss = new WebSocketServer({ noServer: true });
446
- // Адаптер для auth.getCurrentUser из сырого IncomingMessage
447
- function reqAdapter(req) {
448
- const headers = new Headers();
449
- for (const [k, v] of Object.entries(req.headers)) {
450
- if (v)
451
- headers.set(k, Array.isArray(v) ? v.join(', ') : v);
452
- }
453
- return {
454
- req: {
455
- header(name) {
456
- const h = req.headers[name.toLowerCase()];
457
- if (!h)
458
- return undefined;
459
- return Array.isArray(h) ? h[0] : h;
460
- },
461
- raw: { headers },
462
- },
463
- };
464
- }
465
- server.on('upgrade', (request, socket, head) => {
466
- const url = new URL(request.url || '', `http://${request.headers.host}`);
467
- // Глобальный event-хаб для всех сессий пользователя
468
- if (url.pathname === '/ws/events') {
469
- const user = auth.getCurrentUser(reqAdapter(request));
470
- if (!user) {
471
- socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
472
- socket.destroy();
473
- return;
474
- }
475
- wss.handleUpgrade(request, socket, head, (ws) => {
476
- const clientId = `ws-events-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
477
- const client = {
478
- userId: user.id,
479
- username: user.username,
480
- send(event) {
481
- try {
482
- if (ws.readyState === ws.OPEN) {
483
- ws.send(JSON.stringify(event));
484
- }
485
- }
486
- catch {
487
- // ignore send errors
488
- }
489
- },
490
- };
491
- eventHub.registerClient(client).then(() => {
492
- console.log(`[WS /ws/events] Connected: client=${clientId} user=${user.username}`);
493
- ws.send(JSON.stringify({
494
- type: 'connected',
495
- client_id: clientId,
496
- engine: 'synth',
497
- }));
498
- }).catch(() => {
499
- ws.send(JSON.stringify({
500
- type: 'error',
501
- data: { error: 'Failed to register client' },
502
- timestamp: nowISO(),
503
- }));
504
- });
505
- ws.on('message', (raw) => {
506
- try {
507
- const msg = JSON.parse(raw.toString());
508
- if (msg.type === 'ping') {
509
- ws.send(JSON.stringify({ type: 'pong' }));
510
- }
511
- else if (msg.type === 'send_message') {
512
- const sid = msg.session_id;
513
- if (!sid || !msg.content?.trim())
514
- return;
515
- const streamId = msg.stream_id || generateStreamId();
516
- ws.send(JSON.stringify({
517
- type: 'queued',
518
- session_id: sid,
519
- stream_id: streamId,
520
- timestamp: nowISO(),
521
- }));
522
- (async () => {
523
- const session = await sessionManager.getSession(sid);
524
- if (!session) {
525
- ws.send(JSON.stringify({
526
- type: 'error',
527
- session_id: sid,
528
- data: { error: 'Session not found' },
529
- timestamp: nowISO(),
530
- }));
531
- return;
532
- }
533
- const message = {
534
- id: streamId,
535
- role: MessageRole.USER,
536
- seq: session.messages.length + 1,
537
- origin: 'local',
538
- parts: [{ id: generateStreamId(), type: 'text', data: msg.content.trim() }],
539
- content: msg.content.trim(),
540
- createdAt: nowISO(),
541
- disabled: false,
542
- pinned: false,
543
- hidden: false,
544
- author: user.username,
545
- agentRole: msg.agent_role || session.settings.agentRole,
546
- provider: msg.provider || session.settings.provider,
547
- model: msg.model || session.settings.model,
548
- metadata: { stream_id: streamId },
549
- };
550
- const result = await enqueueUserMessage(sessionManager, eventBus, sid, message, queueManager, processMessage, (msgSid, msg) => orchestrator.obfuscateUserMessageForHistory(msgSid, msg));
551
- if (!result) {
552
- ws.send(JSON.stringify({
553
- type: 'queue.stalled',
554
- session_id: sid,
555
- data: { pending_count: session.pendingMessages.length },
556
- timestamp: nowISO(),
557
- }));
558
- }
559
- })().catch(() => { });
560
- }
561
- else if (msg.type === 'cancel') {
562
- const sid = msg.session_id;
563
- if (!sid)
564
- return;
565
- (async () => {
566
- const session = await sessionManager.getSession(sid);
567
- if (session?.currentStream) {
568
- orchestrator.cancel(session.currentStream.streamId);
569
- }
570
- })().catch(() => { });
571
- }
572
- else if (msg.type === 'permission_reply') {
573
- const sid = msg.session_id;
574
- const approvalId = msg.approval_id;
575
- if (!sid || !approvalId)
576
- return;
577
- // Новый формат: { action: 'allow'|'deny', once?: boolean }.
578
- // Старый формат { approved: boolean } остаётся совместимым.
579
- const action = msg.action === 'allow' || msg.action === 'deny' ? msg.action : undefined;
580
- eventBus.publish(sid, 'permission.replied', {
581
- approval_id: approvalId,
582
- session_id: sid,
583
- approved: action !== undefined ? action === 'allow' : msg.approved === true,
584
- ...(action ? { action } : {}),
585
- ...(typeof msg.once === 'boolean' ? { once: msg.once } : {}),
586
- });
587
- }
588
- else if (msg.type === 'permission_hold') {
589
- const sid = msg.session_id;
590
- const approvalId = msg.approval_id;
591
- if (!sid || !approvalId)
592
- return;
593
- // «Остановить таймер»: publish permission.hold — оркестратор снимает
594
- // авто-отклонение по таймауту, запрос ждёт ответа пользователя.
595
- eventBus.publish(sid, 'permission.hold', {
596
- approval_id: approvalId,
597
- session_id: sid,
598
- });
599
- }
600
- }
601
- catch {
602
- // ignore parse errors
603
- }
604
- });
605
- ws.on('close', () => {
606
- console.log(`[WS /ws/events] Disconnected: client=${clientId}`);
607
- eventHub.unregisterClient(client);
608
- });
609
- ws.on('error', () => {
610
- eventHub.unregisterClient(client);
611
- });
612
- });
613
- return;
614
- }
615
- socket.write('HTTP/1.1 404 Not Found\r\n\r\n');
616
- socket.destroy();
617
- });
618
64
  console.log(`synth-backend starting on http://${host}:${port}`);
619
65
  console.log(` data dir: ${dataDir}`);
620
- console.log(` debug mode: ${backendConfig.auth.debugMode}`);
621
- if (backendConfig.auth.debugMode) {
66
+ console.log(` debug mode: ${config.auth.debugMode}`);
67
+ if (config.auth.debugMode) {
622
68
  console.log(' test users:');
623
- backendConfig.auth.testUsers?.forEach((u) => {
69
+ config.auth.testUsers?.forEach((u) => {
624
70
  console.log(` ${u.username} [${u.roles.join(', ')}] → key: ${u.apiKey.slice(0, 8)}...`);
625
71
  });
626
72
  }
627
- server.listen(port, host);
73
+ const { server, wss } = await handle.listen(port, host);
628
74
  //# sourceMappingURL=main.js.map