@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
@@ -1,7 +1,8 @@
1
1
  import { Hono } from 'hono';
2
2
  import { MessageRole, generateStreamId, nowISO, sessionMcpUpdateSchema, normalizeIconKey, normalizeColorKey, } from '@itphx/synth-shared';
3
3
  import { createRateLimiter } from '../middleware/rate-limiter.js';
4
- import { enqueueUserMessage, serializeSession, createSessionRoutes as createCoreSessionRoutes, } from '@itphx/synth-core';
4
+ import { scopeGuard, projectGuard } from '../auth/service-scope.js';
5
+ import { enqueueUserMessage, serializeSession, isSessionVisible, createSessionRoutes as createCoreSessionRoutes, } from '@itphx/synth-core';
5
6
  import { t } from '../lib/i18n.js';
6
7
  /**
7
8
  * Backend-обёртка над core-фабрикой сессий (ТД-1, фаза B2). Здесь остаются только
@@ -18,12 +19,37 @@ export function createSessionRoutes(kit, sessionManager, eventBus, queueManager,
18
19
  /** Профили пользователей: display name для статистики (fallback — username). */
19
20
  profilesStore,
20
21
  /** Агент по умолчанию для новых сессий без `settings.agentRole` (runtime-настройка). */
21
- resolveDefaultAgent) {
22
+ resolveDefaultAgent,
23
+ /**
24
+ * ADR-089: единый funnel создания сессий (прокидывается в core-фабрику).
25
+ * Не задан — core-фабрика использует прямой `SessionManager.createSession`.
26
+ */
27
+ requestSessionService) {
22
28
  const app = new Hono();
23
29
  const agentRegistry = orchestrator.agentRegistry;
24
- // AD-071 §2.4: владелец сессии — обычный пользователь, управляющий её MCP-скоупом.
30
+ // ADR-071 §2.4: владелец сессии — обычный пользователь, управляющий её MCP-скоупом.
25
31
  const isSessionOwner = (session, userId) => (session.ownerId ?? session.userId) === userId;
26
- /** AD-071 §2.4: эффективный MCP-скоуп сессии (включая отключённые с причиной). */
32
+ /**
33
+ * ADR-089 / безопасность: доступ к сессии по id для backend-only роутов
34
+ * (export/notes/optimization/debug-system-message). Единое правило —
35
+ * `isSessionVisible` из core: elevated (ADMIN/LEAD) → всё; владелец → да;
36
+ * сессия без владельца → да; иначе сессия проекта видна её owner/участникам
37
+ * (`projectStore`). Нет доступа → 404 NOT_FOUND: не раскрываем существование
38
+ * чужой сессии (защита от перебора id; ранее здесь была IDOR-уязвимость).
39
+ */
40
+ const sessionAccessDenied = async (c, session, currentUser) => {
41
+ const user = currentUser ?? (await kit.getCurrentUser(c));
42
+ // Вызовы `kit.isAdmin`/`hasRole` защищены `typeof` — у мок-AuthKit в тестах
43
+ // они могут отсутствовать (паритет с resolveElevated ниже).
44
+ const elevated = (typeof kit.isAdmin === 'function'
45
+ && kit.isAdmin(c))
46
+ || (typeof kit.hasRole === 'function'
47
+ && kit.hasRole(c, 'LEAD'));
48
+ if (await isSessionVisible(session, projectStore, { userId: user.id, elevated }))
49
+ return null;
50
+ return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
51
+ };
52
+ /** ADR-071 §2.4: эффективный MCP-скоуп сессии (включая отключённые с причиной). */
27
53
  const buildSessionMcpPayload = async (session) => {
28
54
  const servers = await orchestrator.resolveMcpServers(session);
29
55
  return {
@@ -34,7 +60,7 @@ resolveDefaultAgent) {
34
60
  mcpDisabledServers: session.settings.mcpDisabledServers ?? [],
35
61
  };
36
62
  };
37
- // GET /api/v2/sessions/:id/mcp — эффективный MCP-скоуп (AD-071 §2.4).
63
+ // GET /api/v2/sessions/:id/mcp — эффективный MCP-скоуп (ADR-071 §2.4).
38
64
  // Показывает все серверы, включая отключённые (reason). RBAC: владелец сессии/ADMIN.
39
65
  app.get('/:id/mcp', kit.requireAuth, async (c) => {
40
66
  const session = await sessionManager.getSession(c.req.param('id'));
@@ -47,7 +73,7 @@ resolveDefaultAgent) {
47
73
  }
48
74
  return c.json(await buildSessionMcpPayload(session));
49
75
  });
50
- // PUT /api/v2/sessions/:id/mcp — переключение MCP пользователем (AD-071 §2.4),
76
+ // PUT /api/v2/sessions/:id/mcp — переключение MCP пользователем (ADR-071 §2.4),
51
77
  // включая opt-out системных серверов. RBAC: владелец сессии/ADMIN.
52
78
  app.put('/:id/mcp', kit.requireAuth, async (c) => {
53
79
  const session = await sessionManager.getSession(c.req.param('id'));
@@ -100,7 +126,7 @@ resolveDefaultAgent) {
100
126
  eventBus.publish(session.id, 'session.updated', serializeSession(session, { agentRegistry }));
101
127
  return c.json(await buildSessionMcpPayload(session));
102
128
  });
103
- // GET /api/v2/sessions/:id/secrets — карта обфускации LLM Gateway (AD-036).
129
+ // GET /api/v2/sessions/:id/secrets — карта обфускации LLM Gateway (ADR-036).
104
130
  // RBAC: только ADMIN/AUDITOR — сама карта является секретом.
105
131
  app.get('/:id/secrets', kit.requirePermission('ADMIN', 'AUDITOR'), async (c) => {
106
132
  const session = await sessionManager.getSession(c.req.param('id'));
@@ -113,16 +139,22 @@ resolveDefaultAgent) {
113
139
  // мирами (publish/fork). Внутренний формат: объект Session (camelCase) из
114
140
  // SessionManager — история сообщений, todos, настройки, заметки, ссылки,
115
141
  // чекпоинты, план-флаг и карта обфускации. Не публичный DTO.
142
+ // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
116
143
  app.get('/:id/export', kit.requireAuth, async (c) => {
117
144
  const session = await sessionManager.getSession(c.req.param('id'));
118
145
  if (!session) {
119
146
  return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
120
147
  }
148
+ const denied = await sessionAccessDenied(c, session);
149
+ if (denied)
150
+ return denied;
121
151
  return c.json(session);
122
152
  });
123
153
  // POST /api/v2/sessions/import — создать сессию из экспорта другой сессии
124
154
  // (перенос истории между мирами). Тело: объект экспорта + import.project_id
125
155
  // (целевой проект; если не задан — берётся из экспорта). LLM не запускается.
156
+ // ADR-089: это materialization-операция (создание-как-факт переноса истории),
157
+ // а не request — идёт прямым `createSession`, минуя funnel `session.requested`.
126
158
  app.post('/import', kit.requireAuth, async (c) => {
127
159
  const user = (await kit.getCurrentUser(c));
128
160
  const body = await c.req.json().catch(() => ({}));
@@ -140,6 +172,7 @@ resolveDefaultAgent) {
140
172
  return c.json({ error: { code: 'PROJECT_NOT_FOUND', message: 'Проект не найден' } }, 400);
141
173
  }
142
174
  }
175
+ // ADR-089: materialization (перенос истории), не request — прямой createSession.
143
176
  const session = await sessionManager.createSession({
144
177
  title: typeof body.title === 'string' ? body.title : undefined,
145
178
  projectId: targetProjectId,
@@ -197,12 +230,16 @@ resolveDefaultAgent) {
197
230
  return c.json(serializeSession(session, { agentRegistry }), 201);
198
231
  });
199
232
  // POST /api/v2/sessions/:id/debug-system-message — отправить отладочное системное сообщение
233
+ // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
200
234
  app.post('/:id/debug-system-message', kit.requireAuth, async (c) => {
201
235
  const session = await sessionManager.getSession(c.req.param('id'));
202
236
  if (!session) {
203
237
  return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
204
238
  }
205
239
  const user = (await kit.getCurrentUser(c));
240
+ const denied = await sessionAccessDenied(c, session, user);
241
+ if (denied)
242
+ return denied;
206
243
  const streamId = generateStreamId();
207
244
  const sysMsg = {
208
245
  id: streamId,
@@ -225,11 +262,15 @@ resolveDefaultAgent) {
225
262
  return c.json({ status: 'enqueued', stream_id: streamId });
226
263
  });
227
264
  // GET /api/v2/sessions/:id/optimization — настройки оптимизации
265
+ // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
228
266
  app.get('/:id/optimization', kit.requireAuth, async (c) => {
229
267
  const session = await sessionManager.getSession(c.req.param('id'));
230
268
  if (!session) {
231
269
  return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
232
270
  }
271
+ const denied = await sessionAccessDenied(c, session);
272
+ if (denied)
273
+ return denied;
233
274
  return c.json({
234
275
  context_optimization: session.settings.contextOptimization,
235
276
  sliding_window_mode: session.settings.slidingWindowMode,
@@ -244,7 +285,15 @@ resolveDefaultAgent) {
244
285
  });
245
286
  });
246
287
  // PATCH /api/v2/sessions/:id/optimization — обновить настройки
288
+ // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
247
289
  app.patch('/:id/optimization', kit.requireAuth, async (c) => {
290
+ const session = await sessionManager.getSession(c.req.param('id'));
291
+ if (!session) {
292
+ return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
293
+ }
294
+ const denied = await sessionAccessDenied(c, session);
295
+ if (denied)
296
+ return denied;
248
297
  const body = await c.req.json().catch(() => ({}));
249
298
  await sessionManager.withLock(c.req.param('id'), async (s) => {
250
299
  if (body.context_optimization !== undefined)
@@ -273,11 +322,15 @@ resolveDefaultAgent) {
273
322
  return c.json(serializeSession(updated, { agentRegistry }));
274
323
  });
275
324
  // POST /api/v2/sessions/:id/optimization/check — проверить триггеры
325
+ // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
276
326
  app.post('/:id/optimization/check', kit.requireAuth, async (c) => {
277
327
  const session = await sessionManager.getSession(c.req.param('id'));
278
328
  if (!session) {
279
329
  return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
280
330
  }
331
+ const denied = await sessionAccessDenied(c, session);
332
+ if (denied)
333
+ return denied;
281
334
  if (!contextOptimizer) {
282
335
  return c.json({ sliding_window: { triggered: false }, summarization: { triggered: false } });
283
336
  }
@@ -290,11 +343,15 @@ resolveDefaultAgent) {
290
343
  });
291
344
  });
292
345
  // POST /api/v2/sessions/:id/optimization/cancel-summarization — отменить ожидающую суммаризацию
346
+ // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
293
347
  app.post('/:id/optimization/cancel-summarization', kit.requireAuth, async (c) => {
294
348
  const session = await sessionManager.getSession(c.req.param('id'));
295
349
  if (!session) {
296
350
  return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
297
351
  }
352
+ const denied = await sessionAccessDenied(c, session);
353
+ if (denied)
354
+ return denied;
298
355
  await sessionManager.withLock(session.id, async (s) => {
299
356
  s.summarizationPending = false;
300
357
  await sessionManager.saveSession(s);
@@ -312,15 +369,27 @@ resolveDefaultAgent) {
312
369
  });
313
370
  // ===== Sticky Notes =====
314
371
  // GET /api/v2/sessions/:id/notes — список заметок
372
+ // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
315
373
  app.get('/:id/notes', kit.requireAuth, async (c) => {
316
374
  const session = await sessionManager.getSession(c.req.param('id'));
317
375
  if (!session) {
318
376
  return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
319
377
  }
378
+ const denied = await sessionAccessDenied(c, session);
379
+ if (denied)
380
+ return denied;
320
381
  return c.json({ notes: session.stickyNotes });
321
382
  });
322
383
  // POST /api/v2/sessions/:id/notes — создать заметку
384
+ // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
323
385
  app.post('/:id/notes', kit.requireAuth, async (c) => {
386
+ const session = await sessionManager.getSession(c.req.param('id'));
387
+ if (!session) {
388
+ return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
389
+ }
390
+ const denied = await sessionAccessDenied(c, session);
391
+ if (denied)
392
+ return denied;
324
393
  const body = await c.req.json().catch(() => ({}));
325
394
  if (!body.content?.trim()) {
326
395
  return c.json({ error: { code: 'VALIDATION_ERROR', message: 'Content is required' } }, 400);
@@ -342,7 +411,15 @@ resolveDefaultAgent) {
342
411
  return c.json({ note, notes: updated.stickyNotes }, 201);
343
412
  });
344
413
  // PATCH /api/v2/sessions/:id/notes/:noteId — обновить заметку
414
+ // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
345
415
  app.patch('/:id/notes/:noteId', kit.requireAuth, async (c) => {
416
+ const session = await sessionManager.getSession(c.req.param('id'));
417
+ if (!session) {
418
+ return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
419
+ }
420
+ const denied = await sessionAccessDenied(c, session);
421
+ if (denied)
422
+ return denied;
346
423
  const body = await c.req.json().catch(() => ({}));
347
424
  const noteId = c.req.param('noteId');
348
425
  await sessionManager.withLock(c.req.param('id'), async (s) => {
@@ -361,7 +438,15 @@ resolveDefaultAgent) {
361
438
  return c.json({ notes: updated.stickyNotes });
362
439
  });
363
440
  // DELETE /api/v2/sessions/:id/notes/:noteId — удалить заметку
441
+ // RBAC: владелец сессии / elevated (ADMIN/LEAD) / участник проекта (ADR-089).
364
442
  app.delete('/:id/notes/:noteId', kit.requireAuth, async (c) => {
443
+ const session = await sessionManager.getSession(c.req.param('id'));
444
+ if (!session) {
445
+ return c.json({ error: { code: 'NOT_FOUND', message: t('errors.notFound.session', undefined, c) } }, 404);
446
+ }
447
+ const denied = await sessionAccessDenied(c, session);
448
+ if (denied)
449
+ return denied;
365
450
  const noteId = c.req.param('noteId');
366
451
  await sessionManager.withLock(c.req.param('id'), async (s) => {
367
452
  s.stickyNotes = s.stickyNotes.filter((n) => n.id !== noteId);
@@ -373,11 +458,34 @@ resolveDefaultAgent) {
373
458
  });
374
459
  // Общая логика — в core-фабрике (backend-специфика выше). Регистрируем её
375
460
  // последней: статические/backend-only сегменты должны матчиться раньше.
376
- app.route('/', createCoreSessionRoutes({ requireAuth: kit.requireAuth }, { sessionManager, eventBus, queueManager, processMessage, orchestrator, contextOptimizer, projectStore, profilesStore }, {
461
+ app.route('/', createCoreSessionRoutes({ requireAuth: kit.requireAuth }, { sessionManager, eventBus, queueManager, processMessage, orchestrator, contextOptimizer, projectStore, profilesStore, requestSessionService }, {
377
462
  resolveUserId: async (c) => (await kit.getCurrentUser(c)).id,
378
463
  resolveOwner: async (c) => (await kit.getCurrentUser(c)).id,
379
464
  forkWithOwner: true,
380
465
  canAccess: (session, c, userId) => isSessionOwner(session, userId) || kit.isAdmin(c),
466
+ // ADR-089: сквозной обзор сессий для ADMIN/LEAD. Вызовы `kit.isAdmin`/`hasRole`
467
+ // защищены `typeof` — у мок-AuthKit в тестах они могут отсутствовать.
468
+ resolveElevated: (c) => {
469
+ const isAdmin = typeof kit.isAdmin === 'function' && kit.isAdmin(c);
470
+ const isLead = typeof kit.hasRole === 'function' && kit.hasRole(c, 'LEAD');
471
+ return isAdmin || isLead;
472
+ },
473
+ // ADR-089: проекты-участия пользователя — проектные сессии видны участникам.
474
+ resolveMemberProjectIds: async (_c, userId) => {
475
+ if (!projectStore)
476
+ return [];
477
+ const projects = await projectStore.list(userId);
478
+ return projects.map((p) => p.id);
479
+ },
480
+ // ADR-089: доступ по id — участник проекта сессии (owner/член), не только владелец.
481
+ resolveCanAccessExtra: async (session, _c, userId) => {
482
+ if (!projectStore || !session.projectId)
483
+ return false;
484
+ const project = await projectStore.load(session.projectId);
485
+ if (!project)
486
+ return false;
487
+ return project.ownerId === userId || userId in (project.members ?? {});
488
+ },
381
489
  resolveAuthor: async (c) => (await kit.getCurrentUser(c)).username,
382
490
  promptMessageId: 'stream',
383
491
  publishRenamed: false,
@@ -388,6 +496,9 @@ resolveDefaultAgent) {
388
496
  promptMiddleware: [createRateLimiter(30, 60_000)],
389
497
  enableSessionEvents: false,
390
498
  resolveDefaultAgent,
499
+ // ADR-052 (этап I): scope-гейт и проектная проекция service-key (i18n-403).
500
+ scopeGuard,
501
+ projectGuard,
391
502
  messages: {
392
503
  sessionNotFound: (c) => t('errors.notFound.session', undefined, c),
393
504
  forbidden: (c) => t('auth.forbidden', undefined, c),
@@ -2,10 +2,12 @@ import { Hono } from 'hono';
2
2
  import { nowISO } from '@itphx/synth-shared';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { t } from '../lib/i18n.js';
5
+ import { requireAdminOrScope } from '../auth/guards.js';
5
6
  export function createUserRoutes(kit, profiles) {
6
7
  const app = new Hono();
7
- // GET /api/v2/users — список всех пользователей (admin)
8
- app.get('/', kit.requireAdmin, async (c) => {
8
+ // GET /api/v2/users — список всех пользователей (ADMIN или scope `users:read`).
9
+ // Идентичности сознательно не включаются: список не раздувается (детали — в /:id).
10
+ app.get('/', requireAdminOrScope('users:read'), async (c) => {
9
11
  const all = await profiles.listProfiles();
10
12
  return c.json({
11
13
  users: all.map((p) => ({
@@ -25,8 +27,10 @@ export function createUserRoutes(kit, profiles) {
25
27
  })),
26
28
  });
27
29
  });
28
- // GET /api/v2/users/:id — детали пользователя (admin)
29
- app.get('/:id', kit.requireAdmin, async (c) => {
30
+ // GET /api/v2/users/:id — детали пользователя (ADMIN или scope `users:read`).
31
+ // ADR-089/O1: отдаёт `identities` профиля (snake_case) — нужно аддонам для
32
+ // адресации внешних идентичностей машинной кредой.
33
+ app.get('/:id', requireAdminOrScope('users:read'), async (c) => {
30
34
  const id = c.req.param('id');
31
35
  const p = await profiles.loadProfile(id);
32
36
  if (!p) {
@@ -42,6 +46,14 @@ export function createUserRoutes(kit, profiles) {
42
46
  display_name: p.displayName || null,
43
47
  is_active: p.isActive,
44
48
  notes: p.notes,
49
+ identities: (p.identities ?? []).map((identity) => ({
50
+ provider: identity.provider,
51
+ external_id: identity.externalId,
52
+ ...(identity.username !== undefined ? { username: identity.username } : {}),
53
+ ...(identity.displayName !== undefined ? { display_name: identity.displayName } : {}),
54
+ linked_at: identity.linkedAt,
55
+ ...(identity.linkedBy !== undefined ? { linked_by: identity.linkedBy } : {}),
56
+ })),
45
57
  created_at: p.createdAt,
46
58
  updated_at: p.updatedAt,
47
59
  last_login: p.lastLogin || null,
@@ -74,6 +86,7 @@ export function createUserRoutes(kit, profiles) {
74
86
  isActive: body.is_active ?? true,
75
87
  preferences: {},
76
88
  notes: body.notes || '',
89
+ interviewCompleted: false,
77
90
  displayName: body.display_name || undefined,
78
91
  createdAt: now,
79
92
  updatedAt: now,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@itphx/synth-backend",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "files": [
@@ -8,8 +8,8 @@
8
8
  ],
9
9
  "dependencies": {
10
10
  "@hono/node-server": "^1.18.0",
11
- "@itphx/synth-core": "0.9.0",
12
- "@itphx/synth-shared": "0.9.0",
11
+ "@itphx/synth-core": "0.10.1",
12
+ "@itphx/synth-shared": "0.10.1",
13
13
  "hono": "^4.9.0",
14
14
  "hono-rate-limiter": "^0.5.3",
15
15
  "jose": "^6.2.3",
@@ -27,7 +27,7 @@
27
27
  "scripts": {
28
28
  "dev": "tsx src/main.ts",
29
29
  "start": "node dist/main.js",
30
- "build": "rm -rf dist && tsc -p tsconfig.build.json && mkdir -p dist/agents && cp -r src/agents/definitions dist/agents/definitions",
30
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
31
31
  "typecheck": "tsc --noEmit",
32
32
  "lint": "eslint src/",
33
33
  "test": "vitest run",
@@ -1,24 +0,0 @@
1
- {
2
- "id": "admin",
3
- "displayName": {
4
- "en": "Admin",
5
- "ru": "Админ"
6
- },
7
- "description": {
8
- "en": "System administration and configuration",
9
- "ru": "Системное администрирование и настройка"
10
- },
11
- "capabilities": [
12
- "file_read",
13
- "file_write",
14
- "search",
15
- "shell",
16
- "git_read",
17
- "git_write",
18
- "task",
19
- "mcp"
20
- ],
21
- "icon": "shield-keyhole",
22
- "color": "--status-error",
23
- "contextFile": "ADMIN.md"
24
- }
@@ -1,20 +0,0 @@
1
- {
2
- "id": "analyst",
3
- "displayName": {
4
- "en": "Analyst",
5
- "ru": "Аналитик"
6
- },
7
- "description": {
8
- "en": "Code analysis, research and documentation",
9
- "ru": "Анализ кода, исследование и документация"
10
- },
11
- "capabilities": [
12
- "file_read",
13
- "search",
14
- "web",
15
- "mcp"
16
- ],
17
- "icon": "chart-line",
18
- "color": "--syntax-function",
19
- "contextFile": "ANALYST.md"
20
- }
@@ -1,25 +0,0 @@
1
- {
2
- "id": "assistant",
3
- "displayName": {
4
- "en": "Assistant",
5
- "ru": "Ассистент"
6
- },
7
- "description": {
8
- "en": "Universal assistant for any task",
9
- "ru": "Универсальный ассистент для любых задач"
10
- },
11
- "capabilities": [
12
- "file_read",
13
- "file_write",
14
- "search",
15
- "shell",
16
- "web",
17
- "git_read",
18
- "git_write",
19
- "task",
20
- "mcp"
21
- ],
22
- "icon": "robot-3",
23
- "color": "--status-success",
24
- "contextFile": "ASSISTANT.md"
25
- }
@@ -1,19 +0,0 @@
1
- {
2
- "id": "auditor",
3
- "displayName": {
4
- "en": "Security Auditor",
5
- "ru": "Аудитор безопасности"
6
- },
7
- "description": {
8
- "en": "Security audit and vulnerability search",
9
- "ru": "Аудит безопасности и поиск уязвимостей"
10
- },
11
- "capabilities": [
12
- "file_read",
13
- "search",
14
- "mcp"
15
- ],
16
- "icon": "shield-check",
17
- "color": "--status-warning",
18
- "contextFile": "AUDITOR.md"
19
- }
@@ -1,23 +0,0 @@
1
- {
2
- "id": "developer",
3
- "displayName": {
4
- "en": "Developer",
5
- "ru": "Разработчик"
6
- },
7
- "description": {
8
- "en": "Code development and refactoring",
9
- "ru": "Разработка и рефакторинг кода"
10
- },
11
- "capabilities": [
12
- "file_read",
13
- "file_write",
14
- "search",
15
- "shell",
16
- "git_read",
17
- "git_write",
18
- "mcp"
19
- ],
20
- "icon": "code-s-slash",
21
- "color": "--status-info",
22
- "contextFile": "DEVELOPER.md"
23
- }
@@ -1,23 +0,0 @@
1
- {
2
- "id": "devops",
3
- "displayName": {
4
- "en": "DevOps",
5
- "ru": "DevOps"
6
- },
7
- "description": {
8
- "en": "Infrastructure, CI/CD, deployment",
9
- "ru": "Инфраструктура, CI/CD, деплоймент"
10
- },
11
- "capabilities": [
12
- "file_read",
13
- "file_write",
14
- "search",
15
- "shell",
16
- "git_read",
17
- "git_write",
18
- "mcp"
19
- ],
20
- "icon": "server",
21
- "color": "--syntax-type",
22
- "contextFile": "DEVOPS.md"
23
- }
@@ -1,15 +0,0 @@
1
- {
2
- "id": "explore",
3
- "displayName": { "en": "Explorer", "ru": "Исследователь" },
4
- "description": {
5
- "en": "Fast codebase exploration and search (read-only)",
6
- "ru": "Быстрый поиск и исследование кодовой базы (только чтение)"
7
- },
8
- "capabilities": ["file_read", "search", "web", "mcp"],
9
- "icon": "search-eye",
10
- "color": "--syntax-keyword",
11
- "contextFile": "",
12
- "agentMode": ["subagent"],
13
- "subagentPrompt": "Ты — специалист по исследованию кодовых баз. Твоя задача — быстро находить файлы по шаблонам (glob), искать код по ключевым словам (grep), читать файлы и отвечать на вопросы о структуре проекта.\n\n## Инструменты\nУ тебя есть доступ к инструментам только для чтения: read_file, list_directory, glob, grep_files, web_fetch, web_search.\n\n## Что ты можешь\n- Находить файлы по glob-паттернам (например, \"src/components/**/*.tsx\")\n- Искать код по ключевым словам или регулярным выражениям\n- Читать содержимое найденных файлов\n- Отвечать на вопросы о структуре и содержимом кодовой базы\n\n## Что ты НЕ можешь\n- Изменять файлы\n- Выполнять shell-команды\n- Делать git-операции\n\n## Формат ответа\nВозвращай результат в формате:\n- Найденные файлы: абсолютные пути\n- Краткое описание находки\n- Ответ на поставленный вопрос\n\nБудь тщательным в поиске. Если задача требует поиска в нескольких местах, делай несколько запросов.",
14
- "maxSteps": 10
15
- }
@@ -1,15 +0,0 @@
1
- {
2
- "id": "general",
3
- "displayName": { "en": "General", "ru": "Универсальный" },
4
- "description": {
5
- "en": "Universal subagent for complex multi-step tasks",
6
- "ru": "Универсальный сабагент для сложных многошаговых задач"
7
- },
8
- "capabilities": ["file_read", "file_write", "search", "shell", "git_read", "git_write", "web", "mcp"],
9
- "icon": "robot-3",
10
- "color": "--syntax-variable",
11
- "contextFile": "",
12
- "agentMode": ["subagent"],
13
- "subagentPrompt": "Ты — универсальный помощник для выполнения сложных многошаговых задач.\nУ тебя есть доступ к инструментам для работы с файлами, поиска, git и shell.\n\n## Инструменты\nУ тебя есть полный набор инструментов: read_file, write_file, edit_file, list_directory, glob, grep_files, execute_shell, git_status, git_diff, git_log, git_commit, web_fetch, web_search.\n\n## Принципы работы\n1. Анализируй задачу и разбивай на логические шаги\n2. Выполняй шаги последовательно\n3. Проверяй результаты каждого шага\n4. Возвращай структурированный результат\n\n## Формат ответа\nВозвращай результат в формате:\n- Что было сделано (краткий список шагов)\n- Результат (ключевые находки, изменения, выводы)\n- Если что-то не получилось — объясни почему\n\nРаботай автономно, не задавай уточняющих вопросов если контекст достаточен.",
14
- "maxSteps": 15
15
- }
@@ -1,20 +0,0 @@
1
- {
2
- "id": "pm",
3
- "displayName": {
4
- "en": "Project Manager",
5
- "ru": "Менеджер проекта"
6
- },
7
- "description": {
8
- "en": "Planning, requirements analysis, coordination",
9
- "ru": "Планирование, анализ требований, координация"
10
- },
11
- "capabilities": [
12
- "file_read",
13
- "search",
14
- "web",
15
- "mcp"
16
- ],
17
- "icon": "clipboard",
18
- "color": "--primary",
19
- "contextFile": "PM.md"
20
- }
@@ -1,22 +0,0 @@
1
- {
2
- "id": "qa",
3
- "displayName": {
4
- "en": "QA Engineer",
5
- "ru": "Тестировщик"
6
- },
7
- "description": {
8
- "en": "Testing, quality assurance, bug reports",
9
- "ru": "Тестирование, контроль качества, баг-репорты"
10
- },
11
- "capabilities": [
12
- "file_read",
13
- "file_write",
14
- "search",
15
- "shell",
16
- "git_read",
17
- "mcp"
18
- ],
19
- "icon": "bug",
20
- "color": "--syntax-number",
21
- "contextFile": "QA.md"
22
- }