@itphx/synth-backend 0.9.0 → 0.10.1

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 (55) 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 +106 -0
  4. package/dist/app/deps.js +617 -0
  5. package/dist/app/listen.d.ts +29 -0
  6. package/dist/app/listen.js +298 -0
  7. package/dist/app/mount-routes.d.ts +18 -0
  8. package/dist/app/mount-routes.js +466 -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 +29 -3
  12. package/dist/app.js +110 -900
  13. package/dist/auth/guards.d.ts +20 -0
  14. package/dist/auth/guards.js +65 -0
  15. package/dist/auth/middleware.d.ts +20 -1
  16. package/dist/auth/middleware.js +53 -1
  17. package/dist/auth/oidc.d.ts +15 -0
  18. package/dist/auth/oidc.js +41 -3
  19. package/dist/auth/service-scope.d.ts +14 -0
  20. package/dist/auth/service-scope.js +40 -0
  21. package/dist/events/hub.d.ts +9 -0
  22. package/dist/events/hub.js +29 -0
  23. package/dist/lib/cors.d.ts +23 -0
  24. package/dist/lib/cors.js +24 -0
  25. package/dist/lib/i18n.js +64 -0
  26. package/dist/main.js +10 -1
  27. package/dist/middleware/rate-limiter.d.ts +4 -1
  28. package/dist/middleware/rate-limiter.js +4 -2
  29. package/dist/routes/audit.d.ts +1 -1
  30. package/dist/routes/audit.js +2 -2
  31. package/dist/routes/auth.js +35 -5
  32. package/dist/routes/gateway-patterns.d.ts +1 -1
  33. package/dist/routes/gateway-patterns.js +1 -1
  34. package/dist/routes/llm.js +7 -4
  35. package/dist/routes/mcp-registry.d.ts +3 -3
  36. package/dist/routes/mcp-registry.js +40 -17
  37. package/dist/routes/mcp.d.ts +1 -1
  38. package/dist/routes/mcp.js +1 -1
  39. package/dist/routes/projects.d.ts +7 -4
  40. package/dist/routes/projects.js +17 -7
  41. package/dist/routes/providers.js +1 -0
  42. package/dist/routes/sessions.d.ts +7 -1
  43. package/dist/routes/sessions.js +119 -8
  44. package/dist/routes/users.js +17 -4
  45. package/package.json +4 -4
  46. package/dist/agents/definitions/admin.json +0 -24
  47. package/dist/agents/definitions/analyst.json +0 -20
  48. package/dist/agents/definitions/assistant.json +0 -25
  49. package/dist/agents/definitions/auditor.json +0 -19
  50. package/dist/agents/definitions/developer.json +0 -23
  51. package/dist/agents/definitions/devops.json +0 -23
  52. package/dist/agents/definitions/explore.json +0 -15
  53. package/dist/agents/definitions/general.json +0 -15
  54. package/dist/agents/definitions/pm.json +0 -20
  55. package/dist/agents/definitions/qa.json +0 -22
@@ -0,0 +1,298 @@
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
+ const client = {
119
+ userId: user.id,
120
+ username: user.username,
121
+ allSessions,
122
+ send(event) {
123
+ try {
124
+ if (ws.readyState === ws.OPEN) {
125
+ ws.send(JSON.stringify(event));
126
+ }
127
+ }
128
+ catch {
129
+ // ignore send errors
130
+ }
131
+ },
132
+ };
133
+ eventHub.registerClient(client).then(() => {
134
+ console.log(`[WS /ws/events] Connected: client=${clientId} user=${user.username}`);
135
+ ws.send(JSON.stringify({
136
+ type: 'connected',
137
+ client_id: clientId,
138
+ engine: 'synth',
139
+ }));
140
+ }).catch(() => {
141
+ ws.send(JSON.stringify({
142
+ type: 'error',
143
+ data: { error: 'Failed to register client' },
144
+ timestamp: nowISO(),
145
+ }));
146
+ });
147
+ /**
148
+ * ADR-089 (P0): сессия, доступная текущему клиенту, либо `null`.
149
+ * Единое правило видимости (`isSessionVisible`) — владелец/участник
150
+ * проекта; ADMIN/LEAD и service-key (allSessions) видят всё.
151
+ * Недоступная чужая сессия неотличима от несуществующей.
152
+ */
153
+ const loadVisibleSession = async (sid) => {
154
+ const session = await sessionManager.getSession(sid);
155
+ if (!session)
156
+ return null;
157
+ const visible = await isSessionVisible(session, projectStore, {
158
+ userId: user.id,
159
+ elevated: allSessions,
160
+ });
161
+ return visible ? session : null;
162
+ };
163
+ ws.on('message', (raw) => {
164
+ try {
165
+ const msg = JSON.parse(raw.toString());
166
+ if (msg.type === 'ping') {
167
+ ws.send(JSON.stringify({ type: 'pong' }));
168
+ }
169
+ else if (msg.type === 'send_message') {
170
+ const sid = msg.session_id;
171
+ if (!sid || !msg.content?.trim())
172
+ return;
173
+ const streamId = msg.stream_id || generateStreamId();
174
+ (async () => {
175
+ const session = await loadVisibleSession(sid);
176
+ if (!session) {
177
+ ws.send(JSON.stringify({
178
+ type: 'error',
179
+ session_id: sid,
180
+ data: { error: 'Session not found' },
181
+ timestamp: nowISO(),
182
+ }));
183
+ return;
184
+ }
185
+ ws.send(JSON.stringify({
186
+ type: 'queued',
187
+ session_id: sid,
188
+ stream_id: streamId,
189
+ timestamp: nowISO(),
190
+ }));
191
+ const message = {
192
+ id: streamId,
193
+ role: MessageRole.USER,
194
+ seq: session.messages.length + 1,
195
+ origin: 'local',
196
+ parts: [{ id: generateStreamId(), type: 'text', data: msg.content.trim() }],
197
+ content: msg.content.trim(),
198
+ createdAt: nowISO(),
199
+ disabled: false,
200
+ pinned: false,
201
+ hidden: false,
202
+ author: user.username,
203
+ agentRole: msg.agent_role || session.settings.agentRole,
204
+ provider: msg.provider || session.settings.provider,
205
+ model: msg.model || session.settings.model,
206
+ metadata: { stream_id: streamId },
207
+ };
208
+ const result = await enqueueUserMessage(sessionManager, eventBus, sid, message, queueManager, processMessage, (msgSid, msg) => orchestrator.obfuscateUserMessageForHistory(msgSid, msg));
209
+ if (!result) {
210
+ ws.send(JSON.stringify({
211
+ type: 'queue.stalled',
212
+ session_id: sid,
213
+ data: { pending_count: session.pendingMessages.length },
214
+ timestamp: nowISO(),
215
+ }));
216
+ }
217
+ })().catch(() => { });
218
+ }
219
+ else if (msg.type === 'cancel') {
220
+ const sid = msg.session_id;
221
+ if (!sid)
222
+ return;
223
+ (async () => {
224
+ const session = await loadVisibleSession(sid);
225
+ if (session?.currentStream) {
226
+ orchestrator.cancel(session.currentStream.streamId);
227
+ }
228
+ })().catch(() => { });
229
+ }
230
+ else if (msg.type === 'permission_reply') {
231
+ const sid = msg.session_id;
232
+ const approvalId = msg.approval_id;
233
+ if (!sid || !approvalId)
234
+ return;
235
+ // Новый формат: { action: 'allow'|'deny', once?: boolean }.
236
+ // Старый формат { approved: boolean } остаётся совместимым.
237
+ const action = msg.action === 'allow' || msg.action === 'deny' ? msg.action : undefined;
238
+ const approved = action !== undefined ? action === 'allow' : msg.approved === true;
239
+ const once = typeof msg.once === 'boolean' ? msg.once : undefined;
240
+ (async () => {
241
+ // ADR-089 (P0): подтверждать права можно только в своей сессии.
242
+ const session = await loadVisibleSession(sid);
243
+ if (!session)
244
+ return;
245
+ eventBus.publish(sid, 'permission.replied', {
246
+ approval_id: approvalId,
247
+ session_id: sid,
248
+ approved,
249
+ ...(action ? { action } : {}),
250
+ ...(once !== undefined ? { once } : {}),
251
+ });
252
+ })().catch(() => { });
253
+ }
254
+ else if (msg.type === 'permission_hold') {
255
+ const sid = msg.session_id;
256
+ const approvalId = msg.approval_id;
257
+ if (!sid || !approvalId)
258
+ return;
259
+ (async () => {
260
+ // «Остановить таймер»: publish permission.hold — оркестратор снимает
261
+ // авто-отклонение по таймауту, запрос ждёт ответа пользователя.
262
+ // ADR-089 (P0): только для своей сессии.
263
+ const session = await loadVisibleSession(sid);
264
+ if (!session)
265
+ return;
266
+ eventBus.publish(sid, 'permission.hold', {
267
+ approval_id: approvalId,
268
+ session_id: sid,
269
+ });
270
+ })().catch(() => { });
271
+ }
272
+ }
273
+ catch {
274
+ // ignore parse errors
275
+ }
276
+ });
277
+ ws.on('close', () => {
278
+ console.log(`[WS /ws/events] Disconnected: client=${clientId}`);
279
+ eventHub.unregisterClient(client);
280
+ });
281
+ ws.on('error', () => {
282
+ eventHub.unregisterClient(client);
283
+ });
284
+ });
285
+ return;
286
+ }
287
+ socket.write('HTTP/1.1 404 Not Found\r\n\r\n');
288
+ socket.destroy();
289
+ });
290
+ await new Promise((resolve, reject) => {
291
+ server.once('error', reject);
292
+ server.listen(port, host, () => resolve());
293
+ });
294
+ const address = server.address();
295
+ const actualPort = typeof address === 'object' && address ? address.port : port;
296
+ return { server, wss, port: actualPort };
297
+ };
298
+ }
@@ -0,0 +1,18 @@
1
+ import type { Hono } from 'hono';
2
+ import type { ServiceApiKeyStore } 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-052 (этап I): реестр service-key (создаётся до `auth` в `app.ts`). */
12
+ serviceApiKeyStore: ServiceApiKeyStore;
13
+ }
14
+ /**
15
+ * Смонтировать все `/api/v2/*`-роуты и служебные заглушки (`/api/config/themes`,
16
+ * i18n-эндпоинты) в порядке, идентичном прежнему `createBackendApp`.
17
+ */
18
+ export declare function mountBackendRoutes(app: Hono, auth: AuthKit, ctx: BackendRoutesContext): void;