@itphx/synth-backend 0.7.3 → 0.8.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 (229) hide show
  1. package/dist/app.d.ts +1 -2
  2. package/dist/app.js +241 -85
  3. package/dist/auth/middleware.d.ts +0 -1
  4. package/dist/auth/middleware.js +0 -1
  5. package/dist/auth/oidc.d.ts +0 -1
  6. package/dist/auth/oidc.js +0 -1
  7. package/dist/events/hub.d.ts +0 -1
  8. package/dist/events/hub.js +0 -1
  9. package/dist/lib/app-config.d.ts +0 -1
  10. package/dist/lib/app-config.js +0 -1
  11. package/dist/lib/defaults-store.d.ts +0 -1
  12. package/dist/lib/defaults-store.js +0 -1
  13. package/dist/lib/i18n-config.d.ts +0 -1
  14. package/dist/lib/i18n-config.js +0 -1
  15. package/dist/lib/i18n.d.ts +0 -1
  16. package/dist/lib/i18n.js +2 -1
  17. package/dist/lib/recalc-can-summarize.d.ts +15 -0
  18. package/dist/lib/recalc-can-summarize.js +47 -0
  19. package/dist/main.d.ts +0 -1
  20. package/dist/main.js +0 -1
  21. package/dist/middleware/rate-limiter.d.ts +0 -1
  22. package/dist/middleware/rate-limiter.js +0 -1
  23. package/dist/routes/agents.d.ts +8 -4
  24. package/dist/routes/agents.js +18 -155
  25. package/dist/routes/audit.d.ts +0 -1
  26. package/dist/routes/audit.js +0 -1
  27. package/dist/routes/auth.d.ts +0 -1
  28. package/dist/routes/auth.js +0 -1
  29. package/dist/routes/context.d.ts +0 -1
  30. package/dist/routes/context.js +0 -1
  31. package/dist/routes/debug.d.ts +0 -1
  32. package/dist/routes/debug.js +0 -1
  33. package/dist/routes/gateway-patterns.d.ts +0 -1
  34. package/dist/routes/gateway-patterns.js +0 -1
  35. package/dist/routes/llm.d.ts +0 -1
  36. package/dist/routes/llm.js +0 -1
  37. package/dist/routes/logs.d.ts +0 -1
  38. package/dist/routes/logs.js +0 -1
  39. package/dist/routes/mcp-registry.d.ts +16 -0
  40. package/dist/routes/mcp-registry.js +359 -0
  41. package/dist/routes/mcp.d.ts +9 -14
  42. package/dist/routes/mcp.js +10 -383
  43. package/dist/routes/messages.d.ts +5 -1
  44. package/dist/routes/messages.js +15 -154
  45. package/dist/routes/models.d.ts +3 -3
  46. package/dist/routes/models.js +7 -169
  47. package/dist/routes/projects.d.ts +24 -4
  48. package/dist/routes/projects.js +53 -217
  49. package/dist/routes/providers.d.ts +1 -2
  50. package/dist/routes/providers.js +0 -1
  51. package/dist/routes/queue.d.ts +4 -1
  52. package/dist/routes/queue.js +11 -139
  53. package/dist/routes/sessions.d.ts +1 -2
  54. package/dist/routes/sessions.js +4 -2
  55. package/dist/routes/users.d.ts +0 -1
  56. package/dist/routes/users.js +0 -1
  57. package/package.json +4 -5
  58. package/dist/app.d.ts.map +0 -1
  59. package/dist/app.js.map +0 -1
  60. package/dist/auth/middleware.d.ts.map +0 -1
  61. package/dist/auth/middleware.js.map +0 -1
  62. package/dist/auth/oidc.d.ts.map +0 -1
  63. package/dist/auth/oidc.js.map +0 -1
  64. package/dist/auth/oidc.test.d.ts +0 -2
  65. package/dist/auth/oidc.test.d.ts.map +0 -1
  66. package/dist/auth/oidc.test.js +0 -39
  67. package/dist/auth/oidc.test.js.map +0 -1
  68. package/dist/events/hub.d.ts.map +0 -1
  69. package/dist/events/hub.js.map +0 -1
  70. package/dist/events/hub.test.d.ts +0 -2
  71. package/dist/events/hub.test.d.ts.map +0 -1
  72. package/dist/events/hub.test.js +0 -74
  73. package/dist/events/hub.test.js.map +0 -1
  74. package/dist/integration/hybrid.integration.test.d.ts +0 -2
  75. package/dist/integration/hybrid.integration.test.d.ts.map +0 -1
  76. package/dist/integration/hybrid.integration.test.js +0 -289
  77. package/dist/integration/hybrid.integration.test.js.map +0 -1
  78. package/dist/lib/app-config.d.ts.map +0 -1
  79. package/dist/lib/app-config.js.map +0 -1
  80. package/dist/lib/defaults-store.d.ts.map +0 -1
  81. package/dist/lib/defaults-store.js.map +0 -1
  82. package/dist/lib/defaults-store.test.d.ts +0 -2
  83. package/dist/lib/defaults-store.test.d.ts.map +0 -1
  84. package/dist/lib/defaults-store.test.js +0 -168
  85. package/dist/lib/defaults-store.test.js.map +0 -1
  86. package/dist/lib/git-service.d.ts +0 -15
  87. package/dist/lib/git-service.d.ts.map +0 -1
  88. package/dist/lib/git-service.js +0 -215
  89. package/dist/lib/git-service.js.map +0 -1
  90. package/dist/lib/i18n-config.d.ts.map +0 -1
  91. package/dist/lib/i18n-config.js.map +0 -1
  92. package/dist/lib/i18n.d.ts.map +0 -1
  93. package/dist/lib/i18n.js.map +0 -1
  94. package/dist/lib/orchestrator-workspace.test.d.ts +0 -2
  95. package/dist/lib/orchestrator-workspace.test.d.ts.map +0 -1
  96. package/dist/lib/orchestrator-workspace.test.js +0 -85
  97. package/dist/lib/orchestrator-workspace.test.js.map +0 -1
  98. package/dist/lib/workspace-resolver.d.ts +0 -26
  99. package/dist/lib/workspace-resolver.d.ts.map +0 -1
  100. package/dist/lib/workspace-resolver.js +0 -249
  101. package/dist/lib/workspace-resolver.js.map +0 -1
  102. package/dist/main.d.ts.map +0 -1
  103. package/dist/main.js.map +0 -1
  104. package/dist/middleware/rate-limiter.d.ts.map +0 -1
  105. package/dist/middleware/rate-limiter.js.map +0 -1
  106. package/dist/routes/agents.d.ts.map +0 -1
  107. package/dist/routes/agents.js.map +0 -1
  108. package/dist/routes/agents.test.d.ts +0 -2
  109. package/dist/routes/agents.test.d.ts.map +0 -1
  110. package/dist/routes/agents.test.js +0 -211
  111. package/dist/routes/agents.test.js.map +0 -1
  112. package/dist/routes/audit.d.ts.map +0 -1
  113. package/dist/routes/audit.js.map +0 -1
  114. package/dist/routes/audit.test.d.ts +0 -2
  115. package/dist/routes/audit.test.d.ts.map +0 -1
  116. package/dist/routes/audit.test.js +0 -285
  117. package/dist/routes/audit.test.js.map +0 -1
  118. package/dist/routes/auth.d.ts.map +0 -1
  119. package/dist/routes/auth.js.map +0 -1
  120. package/dist/routes/auth.test.d.ts +0 -2
  121. package/dist/routes/auth.test.d.ts.map +0 -1
  122. package/dist/routes/auth.test.js +0 -63
  123. package/dist/routes/auth.test.js.map +0 -1
  124. package/dist/routes/context.d.ts.map +0 -1
  125. package/dist/routes/context.js.map +0 -1
  126. package/dist/routes/debug.d.ts.map +0 -1
  127. package/dist/routes/debug.js.map +0 -1
  128. package/dist/routes/debug.test.d.ts +0 -2
  129. package/dist/routes/debug.test.d.ts.map +0 -1
  130. package/dist/routes/debug.test.js +0 -102
  131. package/dist/routes/debug.test.js.map +0 -1
  132. package/dist/routes/fs.d.ts +0 -5
  133. package/dist/routes/fs.d.ts.map +0 -1
  134. package/dist/routes/fs.js +0 -391
  135. package/dist/routes/fs.js.map +0 -1
  136. package/dist/routes/gateway-patterns.d.ts.map +0 -1
  137. package/dist/routes/gateway-patterns.js.map +0 -1
  138. package/dist/routes/gateway-patterns.test.d.ts +0 -2
  139. package/dist/routes/gateway-patterns.test.d.ts.map +0 -1
  140. package/dist/routes/gateway-patterns.test.js +0 -176
  141. package/dist/routes/gateway-patterns.test.js.map +0 -1
  142. package/dist/routes/git.d.ts +0 -5
  143. package/dist/routes/git.d.ts.map +0 -1
  144. package/dist/routes/git.js +0 -105
  145. package/dist/routes/git.js.map +0 -1
  146. package/dist/routes/llm.d.ts.map +0 -1
  147. package/dist/routes/llm.js.map +0 -1
  148. package/dist/routes/llm.test.d.ts +0 -2
  149. package/dist/routes/llm.test.d.ts.map +0 -1
  150. package/dist/routes/llm.test.js +0 -629
  151. package/dist/routes/llm.test.js.map +0 -1
  152. package/dist/routes/logs.d.ts.map +0 -1
  153. package/dist/routes/logs.js.map +0 -1
  154. package/dist/routes/logs.test.d.ts +0 -2
  155. package/dist/routes/logs.test.d.ts.map +0 -1
  156. package/dist/routes/logs.test.js +0 -269
  157. package/dist/routes/logs.test.js.map +0 -1
  158. package/dist/routes/mcp-network-policy.integration.test.d.ts +0 -2
  159. package/dist/routes/mcp-network-policy.integration.test.d.ts.map +0 -1
  160. package/dist/routes/mcp-network-policy.integration.test.js +0 -44
  161. package/dist/routes/mcp-network-policy.integration.test.js.map +0 -1
  162. package/dist/routes/mcp-registry.test.d.ts +0 -2
  163. package/dist/routes/mcp-registry.test.d.ts.map +0 -1
  164. package/dist/routes/mcp-registry.test.js +0 -247
  165. package/dist/routes/mcp-registry.test.js.map +0 -1
  166. package/dist/routes/mcp.d.ts.map +0 -1
  167. package/dist/routes/mcp.js.map +0 -1
  168. package/dist/routes/mcp.test.d.ts +0 -2
  169. package/dist/routes/mcp.test.d.ts.map +0 -1
  170. package/dist/routes/mcp.test.js +0 -388
  171. package/dist/routes/mcp.test.js.map +0 -1
  172. package/dist/routes/messages.d.ts.map +0 -1
  173. package/dist/routes/messages.js.map +0 -1
  174. package/dist/routes/models.d.ts.map +0 -1
  175. package/dist/routes/models.js.map +0 -1
  176. package/dist/routes/models.test.d.ts +0 -2
  177. package/dist/routes/models.test.d.ts.map +0 -1
  178. package/dist/routes/models.test.js +0 -449
  179. package/dist/routes/models.test.js.map +0 -1
  180. package/dist/routes/projects-mcp.test.d.ts +0 -6
  181. package/dist/routes/projects-mcp.test.d.ts.map +0 -1
  182. package/dist/routes/projects-mcp.test.js +0 -160
  183. package/dist/routes/projects-mcp.test.js.map +0 -1
  184. package/dist/routes/projects.d.ts.map +0 -1
  185. package/dist/routes/projects.js.map +0 -1
  186. package/dist/routes/projects.test.d.ts +0 -2
  187. package/dist/routes/projects.test.d.ts.map +0 -1
  188. package/dist/routes/projects.test.js +0 -250
  189. package/dist/routes/projects.test.js.map +0 -1
  190. package/dist/routes/providers.d.ts.map +0 -1
  191. package/dist/routes/providers.js.map +0 -1
  192. package/dist/routes/providers.test.d.ts +0 -2
  193. package/dist/routes/providers.test.d.ts.map +0 -1
  194. package/dist/routes/providers.test.js +0 -211
  195. package/dist/routes/providers.test.js.map +0 -1
  196. package/dist/routes/queue.d.ts.map +0 -1
  197. package/dist/routes/queue.js.map +0 -1
  198. package/dist/routes/queue.test.d.ts +0 -2
  199. package/dist/routes/queue.test.d.ts.map +0 -1
  200. package/dist/routes/queue.test.js +0 -224
  201. package/dist/routes/queue.test.js.map +0 -1
  202. package/dist/routes/sessions-mcp.test.d.ts +0 -6
  203. package/dist/routes/sessions-mcp.test.d.ts.map +0 -1
  204. package/dist/routes/sessions-mcp.test.js +0 -182
  205. package/dist/routes/sessions-mcp.test.js.map +0 -1
  206. package/dist/routes/sessions.d.ts.map +0 -1
  207. package/dist/routes/sessions.js.map +0 -1
  208. package/dist/routes/sessions.test.d.ts +0 -2
  209. package/dist/routes/sessions.test.d.ts.map +0 -1
  210. package/dist/routes/sessions.test.js +0 -602
  211. package/dist/routes/sessions.test.js.map +0 -1
  212. package/dist/routes/settings.test.d.ts +0 -2
  213. package/dist/routes/settings.test.d.ts.map +0 -1
  214. package/dist/routes/settings.test.js +0 -184
  215. package/dist/routes/settings.test.js.map +0 -1
  216. package/dist/routes/users.d.ts.map +0 -1
  217. package/dist/routes/users.js.map +0 -1
  218. package/dist/storage/json-store.d.ts +0 -20
  219. package/dist/storage/json-store.d.ts.map +0 -1
  220. package/dist/storage/json-store.js +0 -100
  221. package/dist/storage/json-store.js.map +0 -1
  222. package/dist/storage/json-store.test.d.ts +0 -2
  223. package/dist/storage/json-store.test.d.ts.map +0 -1
  224. package/dist/storage/json-store.test.js +0 -59
  225. package/dist/storage/json-store.test.js.map +0 -1
  226. package/dist/storage/project-store.d.ts +0 -30
  227. package/dist/storage/project-store.d.ts.map +0 -1
  228. package/dist/storage/project-store.js +0 -109
  229. package/dist/storage/project-store.js.map +0 -1
@@ -1,629 +0,0 @@
1
- import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2
- import { Hono } from 'hono';
3
- import { mkdtemp, rm, readFile } from 'node:fs/promises';
4
- import { tmpdir } from 'node:os';
5
- import { join } from 'node:path';
6
- import { createLlmRoutes } from './llm.js';
7
- import { AuditLogger, BaseProvider, ContextLengthExceededError, ProviderFactory, RateLimitError, RateLimiter, SecretPatternStore, } from '@itphx/synth-core';
8
- const userUser = {
9
- id: 'developer',
10
- username: 'developer',
11
- roles: ['USER'],
12
- preferredLanguage: 'ru',
13
- createdAt: '',
14
- teamRole: 'USER',
15
- notes: '',
16
- interviewCompleted: false,
17
- };
18
- function createMockKit(user) {
19
- return {
20
- requireAuth: async (c, next) => {
21
- c.set('user', user);
22
- await next();
23
- },
24
- getCurrentUser: () => user,
25
- };
26
- }
27
- function createUnauthorizedKit() {
28
- return {
29
- requireAuth: async (c) => {
30
- return c.json({ error: { code: 'UNAUTHORIZED', message: 'Unauthorized' } }, 401);
31
- },
32
- getCurrentUser: () => null,
33
- };
34
- }
35
- /** Минимальный fake-провайдер с фиксированным ответом (имитирует OpenAIProvider). */
36
- class FakeProvider extends BaseProvider {
37
- throwError = null;
38
- /** Если true — chat/chatAsync возвращают последнее user-сообщение (для теста обфускации). */
39
- echoUserContent = false;
40
- /** Если задан — chat/chatAsync возвращают tool_calls (OpenAI-формат). */
41
- toolCalls = null;
42
- /** Если задан — chat/chatAsync возвращают reasoning_content. */
43
- reasoning;
44
- /**
45
- * Если задан — chatAsync отдаёт reasoning несколькими чанками с растущей
46
- * cumulative-строкой (как OpenAIProvider/DeepSeek). Проверяет инкрементальный
47
- * стрим reasoning через прокси.
48
- */
49
- reasoningChunks;
50
- lastMessages = [];
51
- constructor(model = 'fake-model') {
52
- super({ url: 'http://fake.local/v1', apiKey: 'test-key', model, name: 'fake' });
53
- }
54
- getProviderName() {
55
- return 'fake';
56
- }
57
- async chat(messages, _systemPrompt, _tools, _stream) {
58
- if (this.throwError)
59
- throw this.throwError;
60
- this.lastMessages = messages;
61
- const content = this.echoUserContent
62
- ? (messages.find((m) => m.role === 'user')?.content ?? '')
63
- : 'Ответ fake-провайдера';
64
- return {
65
- content,
66
- model: this.model,
67
- usage: { inputTokens: 11, outputTokens: 7, totalTokens: 18 },
68
- ...(this.toolCalls ? { toolCalls: this.toolCalls } : {}),
69
- ...(this.reasoning ? { reasoning: this.reasoning } : {}),
70
- };
71
- }
72
- async *chatAsync(messages, _systemPrompt, _tools, _debugCollector, _cancellationToken) {
73
- if (this.throwError)
74
- throw this.throwError;
75
- this.lastMessages = messages;
76
- const content = this.echoUserContent
77
- ? (messages.find((m) => m.role === 'user')?.content ?? '')
78
- : 'Привет';
79
- // Cumulative-строка reasoning: для reasoningChunks — последний (полный) элемент,
80
- // для reasoning — само значение. Провайдер прикладывает её к content и final чанкам.
81
- const effectiveReasoning = this.reasoningChunks?.at(-1) ?? this.reasoning;
82
- if (this.reasoningChunks) {
83
- for (const r of this.reasoningChunks) {
84
- yield {
85
- content: '',
86
- isFinal: false,
87
- usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
88
- reasoning: r,
89
- };
90
- }
91
- }
92
- yield {
93
- content,
94
- isFinal: false,
95
- usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
96
- ...(this.toolCalls ? { toolCalls: this.toolCalls } : {}),
97
- ...(effectiveReasoning ? { reasoning: effectiveReasoning } : {}),
98
- };
99
- yield {
100
- content: '',
101
- isFinal: true,
102
- usage: { inputTokens: 11, outputTokens: 7, totalTokens: 18 },
103
- ...(this.toolCalls ? { toolCalls: this.toolCalls } : {}),
104
- ...(effectiveReasoning ? { reasoning: effectiveReasoning } : {}),
105
- };
106
- }
107
- }
108
- const modelConfig = {
109
- id: 'fake/fake-model',
110
- name: 'fake-model',
111
- provider: 'fake',
112
- description: '',
113
- enabled: true,
114
- isDefault: true,
115
- };
116
- const providerConfig = {
117
- name: 'fake',
118
- type: 'openai',
119
- baseUrl: 'http://fake.local/v1',
120
- apiKey: 'test-key',
121
- defaultModel: 'fake-model',
122
- timeout: 30,
123
- enabled: true,
124
- icon: '',
125
- };
126
- const gatewayDisabledConfig = {
127
- enabled: false,
128
- inputMode: 'obfuscate',
129
- logPayloads: false,
130
- payloadLogPath: '',
131
- rateLimit: { userPerMinute: 100, providerPerMinute: 100 },
132
- audit: { enabled: true, logPath: '' },
133
- };
134
- const gatewayEnabledConfig = {
135
- ...gatewayDisabledConfig,
136
- enabled: true,
137
- };
138
- const BASE = '/api/v2/llm/chat/completions';
139
- function postBody(body) {
140
- return {
141
- method: 'POST',
142
- headers: { 'Content-Type': 'application/json' },
143
- body: JSON.stringify(body),
144
- };
145
- }
146
- describe('LLM Proxy routes (гибридный режим, Часть 5)', () => {
147
- let tmpDir;
148
- beforeEach(async () => {
149
- tmpDir = await mkdtemp(join(tmpdir(), 'synth-llm-proxy-'));
150
- });
151
- afterEach(async () => {
152
- vi.restoreAllMocks();
153
- await rm(tmpDir, { recursive: true, force: true });
154
- });
155
- function createTestContext(user, opts = {}) {
156
- const fake = opts.fakeProvider ?? new FakeProvider();
157
- const auditPath = join(tmpDir, 'audit', 'llm-gateway.jsonl');
158
- const deps = {
159
- providerLoader: opts.providerLoader ?? ((name) => (name === 'fake' ? providerConfig : null)),
160
- modelLoader: opts.modelLoader ?? ((model) => (model === 'fake-model' || model === 'fake/fake-model' ? modelConfig : null)),
161
- gatewayConfig: opts.gatewayConfig ?? gatewayDisabledConfig,
162
- gatewayAuditLogger: new AuditLogger(auditPath),
163
- gatewayRateLimiter: new RateLimiter(100, 100),
164
- gatewayPayloadLogPath: '',
165
- patternStore: opts.patternStore ?? null,
166
- };
167
- vi.spyOn(ProviderFactory, 'create').mockReturnValue(fake);
168
- const app = new Hono();
169
- const kit = createMockKit(user);
170
- app.route('/api/v2/llm', createLlmRoutes(kit, deps));
171
- return { app, fake, auditPath };
172
- }
173
- describe('валидация тела', () => {
174
- it('невалидный JSON → 400 BAD_REQUEST', async () => {
175
- const { app } = createTestContext(userUser);
176
- const res = await app.request(BASE, {
177
- method: 'POST',
178
- headers: { 'Content-Type': 'application/json' },
179
- body: '{не-json',
180
- });
181
- expect(res.status).toBe(400);
182
- const body = await res.json();
183
- expect(body.error.code).toBe('BAD_REQUEST');
184
- });
185
- it('пустое тело / нет model → 400 BAD_REQUEST', async () => {
186
- const { app } = createTestContext(userUser);
187
- const res = await app.request(BASE, postBody({
188
- messages: [{ role: 'user', content: 'привет' }],
189
- }));
190
- expect(res.status).toBe(400);
191
- const body = await res.json();
192
- expect(body.error.code).toBe('BAD_REQUEST');
193
- });
194
- it('пустой messages → 400 BAD_REQUEST', async () => {
195
- const { app } = createTestContext(userUser);
196
- const res = await app.request(BASE, postBody({ model: 'fake-model', messages: [] }));
197
- expect(res.status).toBe(400);
198
- const body = await res.json();
199
- expect(body.error.code).toBe('BAD_REQUEST');
200
- });
201
- });
202
- describe('резолв модели/провайдера', () => {
203
- it('модель не найдена → 404 MODEL_NOT_FOUND', async () => {
204
- const { app } = createTestContext(userUser);
205
- const res = await app.request(BASE, postBody({
206
- model: 'no-such-model',
207
- messages: [{ role: 'user', content: 'привет' }],
208
- }));
209
- expect(res.status).toBe(404);
210
- const body = await res.json();
211
- expect(body.error.code).toBe('MODEL_NOT_FOUND');
212
- expect(body.error.message).toContain('no-such-model');
213
- });
214
- it('модель отключена → 400 MODEL_DISABLED', async () => {
215
- const { app } = createTestContext(userUser, {
216
- modelLoader: () => ({ ...modelConfig, enabled: false }),
217
- });
218
- const res = await app.request(BASE, postBody({
219
- model: 'fake-model',
220
- messages: [{ role: 'user', content: 'привет' }],
221
- }));
222
- expect(res.status).toBe(400);
223
- const body = await res.json();
224
- expect(body.error.code).toBe('MODEL_DISABLED');
225
- });
226
- it('провайдер не найден → 502 PROVIDER_NOT_FOUND', async () => {
227
- const { app } = createTestContext(userUser, {
228
- modelLoader: () => ({ ...modelConfig, provider: 'missing' }),
229
- providerLoader: () => null,
230
- });
231
- const res = await app.request(BASE, postBody({
232
- model: 'fake-model',
233
- messages: [{ role: 'user', content: 'привет' }],
234
- }));
235
- expect(res.status).toBe(502);
236
- const body = await res.json();
237
- expect(body.error.code).toBe('PROVIDER_NOT_FOUND');
238
- });
239
- it('провайдер отключён → 400 PROVIDER_DISABLED', async () => {
240
- const { app } = createTestContext(userUser, {
241
- providerLoader: () => ({ ...providerConfig, enabled: false }),
242
- });
243
- const res = await app.request(BASE, postBody({
244
- model: 'fake-model',
245
- messages: [{ role: 'user', content: 'привет' }],
246
- }));
247
- expect(res.status).toBe(400);
248
- const body = await res.json();
249
- expect(body.error.code).toBe('PROVIDER_DISABLED');
250
- });
251
- });
252
- describe('явный provider в теле (remote-зеркала)', () => {
253
- // Сервер знает двух провайдеров: fake (владелец fake-model) и itphx.
254
- const twoProviderLoader = (name) => {
255
- if (name === 'fake')
256
- return providerConfig;
257
- if (name === 'itphx')
258
- return { ...providerConfig, name: 'itphx', baseUrl: 'https://ai.itphx.ru/v1', defaultModel: 'local.qwen3:14b' };
259
- return null;
260
- };
261
- it('provider совпадает с провайдером модели → 200 (как раньше)', async () => {
262
- const { app } = createTestContext(userUser, { providerLoader: twoProviderLoader });
263
- const res = await app.request(BASE, postBody({
264
- model: 'fake-model',
265
- provider: 'fake',
266
- messages: [{ role: 'user', content: 'привет' }],
267
- }));
268
- expect(res.status).toBe(200);
269
- const body = await res.json();
270
- expect(body.choices[0].message.content).toBe('Ответ fake-провайдера');
271
- });
272
- it('provider существует, но не совпадает с провайдером модели → 400 MODEL_MISMATCH', async () => {
273
- const { app } = createTestContext(userUser, { providerLoader: twoProviderLoader });
274
- const res = await app.request(BASE, postBody({
275
- model: 'fake-model',
276
- provider: 'itphx',
277
- messages: [{ role: 'user', content: 'привет' }],
278
- }));
279
- expect(res.status).toBe(400);
280
- const body = await res.json();
281
- expect(body.error.code).toBe('MODEL_MISMATCH');
282
- expect(body.error.message).toContain('itphx');
283
- expect(body.error.message).toContain('fake-model');
284
- });
285
- it('provider не существует на сервере → 502 PROVIDER_NOT_FOUND', async () => {
286
- const { app } = createTestContext(userUser, { providerLoader: twoProviderLoader });
287
- const res = await app.request(BASE, postBody({
288
- model: 'fake-model',
289
- provider: 'no-such-provider',
290
- messages: [{ role: 'user', content: 'привет' }],
291
- }));
292
- expect(res.status).toBe(502);
293
- const body = await res.json();
294
- expect(body.error.code).toBe('PROVIDER_NOT_FOUND');
295
- });
296
- it('provider существует, но отключён → 400 PROVIDER_DISABLED', async () => {
297
- const { app } = createTestContext(userUser, {
298
- providerLoader: (name) => (name === 'itphx' ? { ...providerConfig, name: 'itphx', enabled: false } : providerConfig),
299
- });
300
- const res = await app.request(BASE, postBody({
301
- model: 'fake-model',
302
- provider: 'itphx',
303
- messages: [{ role: 'user', content: 'привет' }],
304
- }));
305
- expect(res.status).toBe(400);
306
- const body = await res.json();
307
- expect(body.error.code).toBe('PROVIDER_DISABLED');
308
- });
309
- it('без provider работает как раньше (резолв по модели)', async () => {
310
- const { app } = createTestContext(userUser, { providerLoader: twoProviderLoader });
311
- const res = await app.request(BASE, postBody({
312
- model: 'fake-model',
313
- messages: [{ role: 'user', content: 'привет' }],
314
- }));
315
- expect(res.status).toBe(200);
316
- });
317
- });
318
- describe('non-stream успех', () => {
319
- it('возвращает OpenAI-формат и usage', async () => {
320
- const { app } = createTestContext(userUser);
321
- const res = await app.request(BASE, postBody({
322
- model: 'fake-model',
323
- messages: [{ role: 'user', content: 'привет' }],
324
- temperature: 0.3,
325
- max_tokens: 64,
326
- }));
327
- expect(res.status).toBe(200);
328
- const body = await res.json();
329
- expect(body.id).toMatch(/^chatcmpl-/);
330
- expect(body.object).toBe('chat.completion');
331
- expect(typeof body.created).toBe('number');
332
- expect(body.model).toBe('fake-model');
333
- expect(body.choices).toHaveLength(1);
334
- expect(body.choices[0]).toMatchObject({
335
- index: 0,
336
- message: { role: 'assistant', content: 'Ответ fake-провайдера' },
337
- finish_reason: 'stop',
338
- });
339
- expect(body.usage).toEqual({ prompt_tokens: 11, completion_tokens: 7, total_tokens: 18 });
340
- });
341
- it('прокидывает user-сообщения в провайдер (LLMMessage)', async () => {
342
- const fake = new FakeProvider();
343
- const { app } = createTestContext(userUser, { fakeProvider: fake });
344
- await app.request(BASE, postBody({
345
- model: 'fake-model',
346
- messages: [
347
- { role: 'system', content: 'ты ассистент' },
348
- { role: 'user', content: 'привет' },
349
- ],
350
- }));
351
- expect(fake.lastMessages.map((m) => m.role)).toEqual(['system', 'user']);
352
- expect(fake.lastMessages[1]?.content).toBe('привет');
353
- });
354
- it('tool-цикл: tool_calls/tool_call_id/reasoning_content доходят до провайдера', async () => {
355
- const fake = new FakeProvider();
356
- const { app } = createTestContext(userUser, { fakeProvider: fake });
357
- await app.request(BASE, postBody({
358
- model: 'fake-model',
359
- messages: [
360
- {
361
- role: 'assistant',
362
- content: null,
363
- tool_calls: [
364
- { id: 'call_1', type: 'function', function: { name: 'read_file', arguments: '{"path":"a.ts"}' } },
365
- ],
366
- reasoning_content: 'подумал и решил прочитать файл',
367
- },
368
- { role: 'tool', content: 'содержимое файла', tool_call_id: 'call_1' },
369
- { role: 'user', content: 'продолжай' },
370
- ],
371
- }));
372
- const assistant = fake.lastMessages[0];
373
- expect(assistant.toolUse).toEqual([
374
- { id: 'call_1', type: 'function', function: { name: 'read_file', arguments: '{"path":"a.ts"}' } },
375
- ]);
376
- expect(assistant.reasoning).toBe('подумал и решил прочитать файл');
377
- const toolMsg = fake.lastMessages[1];
378
- expect(toolMsg.role).toBe('tool');
379
- expect(toolMsg.toolCallId).toBe('call_1');
380
- expect(toolMsg.content).toBe('содержимое файла');
381
- });
382
- it('non-stream: tool_calls/reasoning_content пробрасываются в choices[0].message', async () => {
383
- const fake = new FakeProvider();
384
- fake.toolCalls = [
385
- { id: 'call_2', type: 'function', function: { name: 'edit_file', arguments: '{"path":"b.ts"}' } },
386
- ];
387
- fake.reasoning = 'надо отредактировать';
388
- const { app } = createTestContext(userUser, { fakeProvider: fake });
389
- const res = await app.request(BASE, postBody({
390
- model: 'fake-model',
391
- messages: [{ role: 'user', content: 'исправь' }],
392
- }));
393
- expect(res.status).toBe(200);
394
- const body = await res.json();
395
- expect(body.choices[0].message.tool_calls).toEqual(fake.toolCalls);
396
- expect(body.choices[0].message.reasoning_content).toBe('надо отредактировать');
397
- expect(body.choices[0].message.content).toBe('Ответ fake-провайдера');
398
- });
399
- });
400
- describe('stream успех', () => {
401
- it('возвращает SSE-чунки OpenAI-формата и [DONE]', async () => {
402
- const { app } = createTestContext(userUser);
403
- const res = await app.request(BASE, postBody({
404
- model: 'fake-model',
405
- messages: [{ role: 'user', content: 'привет' }],
406
- stream: true,
407
- }));
408
- expect(res.status).toBe(200);
409
- expect(res.headers.get('content-type')).toContain('text/event-stream');
410
- const text = await res.text();
411
- const lines = text.split('\n').filter((l) => l.startsWith('data: '));
412
- // data: [DONE] — не JSON, исключаем из парсинга
413
- const parsed = lines
414
- .filter((l) => !l.includes('[DONE]'))
415
- .map((l) => JSON.parse(l.slice(6)));
416
- // дельта-чанк с контентом
417
- expect(parsed[0].object).toBe('chat.completion.chunk');
418
- expect(parsed[0].choices[0].delta.content).toBe('Привет');
419
- expect(parsed[0].choices[0].finish_reason).toBeNull();
420
- // финальный чанк: finish_reason stop + usage
421
- const last = parsed[parsed.length - 1];
422
- expect(last.choices[0].finish_reason).toBe('stop');
423
- expect(last.usage).toEqual({ prompt_tokens: 11, completion_tokens: 7, total_tokens: 18 });
424
- // завершение потока
425
- expect(text.trimEnd().endsWith('data: [DONE]')).toBe(true);
426
- });
427
- it('AD-070: stream_options.include_usage принимается и usage есть в финальном чанке', async () => {
428
- const { app } = createTestContext(userUser);
429
- const res = await app.request(BASE, postBody({
430
- model: 'fake-model',
431
- messages: [{ role: 'user', content: 'привет' }],
432
- stream: true,
433
- stream_options: { include_usage: true },
434
- }));
435
- expect(res.status).toBe(200);
436
- const text = await res.text();
437
- const lines = text.split('\n').filter((l) => l.startsWith('data: '));
438
- const parsed = lines
439
- .filter((l) => !l.includes('[DONE]'))
440
- .map((l) => JSON.parse(l.slice(6)));
441
- const last = parsed[parsed.length - 1];
442
- expect(last.choices[0].finish_reason).toBe('stop');
443
- expect(last.usage).toEqual({ prompt_tokens: 11, completion_tokens: 7, total_tokens: 18 });
444
- });
445
- it('ошибка провайдера в стриме шлёт error-объект и [DONE]', async () => {
446
- const fake = new FakeProvider();
447
- fake.throwError = new RateLimitError('too many requests');
448
- const { app } = createTestContext(userUser, { fakeProvider: fake });
449
- const res = await app.request(BASE, postBody({
450
- model: 'fake-model',
451
- messages: [{ role: 'user', content: 'привет' }],
452
- stream: true,
453
- }));
454
- expect(res.status).toBe(200);
455
- const text = await res.text();
456
- expect(text).toContain('RATE_LIMITED');
457
- expect(text.trimEnd().endsWith('data: [DONE]')).toBe(true);
458
- });
459
- it('stream: tool_calls пробрасываются в choices[0].delta, reasoning — отдельным стрим-чанком', async () => {
460
- const fake = new FakeProvider();
461
- fake.toolCalls = [
462
- { index: 0, id: 'call_3', type: 'function', function: { name: 'grep_files', arguments: '{"pattern":"x"}' } },
463
- ];
464
- fake.reasoning = 'надо поискать';
465
- const { app } = createTestContext(userUser, { fakeProvider: fake });
466
- const res = await app.request(BASE, postBody({
467
- model: 'fake-model',
468
- messages: [{ role: 'user', content: 'найди' }],
469
- stream: true,
470
- }));
471
- expect(res.status).toBe(200);
472
- const text = await res.text();
473
- const lines = text.split('\n').filter((l) => l.startsWith('data: '));
474
- const parsed = lines
475
- .filter((l) => !l.includes('[DONE]'))
476
- .map((l) => JSON.parse(l.slice(6)));
477
- // Reasoning приходит отдельным(и) стрим-чанком(ами), а не в tool_calls-чанке.
478
- const reasoningChunks = parsed.filter((c) => typeof c.choices?.[0]?.delta?.reasoning_content === 'string');
479
- expect(reasoningChunks).toHaveLength(1);
480
- expect(reasoningChunks[0].choices[0].delta.reasoning_content).toBe('надо поискать');
481
- // Контент-дельта как раньше.
482
- const contentChunk = parsed.find((c) => c.choices?.[0]?.delta?.content === 'Привет');
483
- expect(contentChunk).toBeDefined();
484
- // Отдельный дельта-чанк с накопленными tool_calls (один раз), без reasoning.
485
- const toolChunk = parsed.find((c) => Array.isArray(c.choices?.[0]?.delta?.tool_calls));
486
- expect(toolChunk).toBeDefined();
487
- expect(toolChunk.choices[0].delta.tool_calls).toEqual(fake.toolCalls);
488
- expect(toolChunk.choices[0].delta.reasoning_content).toBeUndefined();
489
- // Порядок: reasoning → content → tool_calls.
490
- const reasoningIdx = parsed.indexOf(reasoningChunks[0]);
491
- expect(reasoningIdx).toBeLessThan(parsed.indexOf(contentChunk));
492
- expect(parsed.indexOf(contentChunk)).toBeLessThan(parsed.indexOf(toolChunk));
493
- // Финальный чанк — как раньше.
494
- const last = parsed[parsed.length - 1];
495
- expect(last.choices[0].finish_reason).toBe('stop');
496
- expect(text.trimEnd().endsWith('data: [DONE]')).toBe(true);
497
- });
498
- it('stream: reasoning стримится инкрементально (не одним чанком в конце)', async () => {
499
- const fake = new FakeProvider();
500
- // Cumulative-строки с растущей длиной, как у OpenAIProvider/DeepSeek.
501
- fake.reasoningChunks = ['надо', 'надо по', 'надо поискать'];
502
- const { app } = createTestContext(userUser, { fakeProvider: fake });
503
- const res = await app.request(BASE, postBody({
504
- model: 'fake-model',
505
- messages: [{ role: 'user', content: 'найди' }],
506
- stream: true,
507
- }));
508
- expect(res.status).toBe(200);
509
- const text = await res.text();
510
- const lines = text.split('\n').filter((l) => l.startsWith('data: '));
511
- const parsed = lines
512
- .filter((l) => !l.includes('[DONE]'))
513
- .map((l) => JSON.parse(l.slice(6)));
514
- const reasoningChunks = parsed.filter((c) => typeof c.choices?.[0]?.delta?.reasoning_content === 'string');
515
- // Несколько чанков, а не один в конце.
516
- expect(reasoningChunks).toHaveLength(3);
517
- const deltas = reasoningChunks.map((c) => c.choices[0].delta.reasoning_content);
518
- // Дельта-инкременты (не cumulative-повторы).
519
- expect(deltas).toEqual(['надо', ' по', 'искать']);
520
- // Конкатенация = полная строка, без дублей.
521
- expect(deltas.join('')).toBe('надо поискать');
522
- // Все reasoning-чанки идут до content-чанка (порядок reasoning → content).
523
- const contentIdx = parsed.findIndex((c) => c.choices?.[0]?.delta?.content === 'Привет');
524
- const lastReasoningIdx = parsed.reduce((acc, c, i) => typeof c.choices?.[0]?.delta?.reasoning_content === 'string' ? i : acc, -1);
525
- expect(contentIdx).toBeGreaterThan(lastReasoningIdx);
526
- // Финальный чанк — finish_reason stop, затем [DONE].
527
- expect(parsed[parsed.length - 1].choices[0].finish_reason).toBe('stop');
528
- expect(text.trimEnd().endsWith('data: [DONE]')).toBe(true);
529
- });
530
- });
531
- describe('маппинг ошибок провайдера', () => {
532
- it.each([
533
- [new RateLimitError('rate limit exceeded'), 429, 'RATE_LIMITED'],
534
- [new ContextLengthExceededError('context length exceeded'), 400, 'CONTEXT_LENGTH_EXCEEDED'],
535
- [new Error('OpenAI API error 500: upstream failed'), 502, 'PROVIDER_ERROR'],
536
- ])('%s → %i %s', async (err, status, code) => {
537
- const fake = new FakeProvider();
538
- fake.throwError = err;
539
- const { app } = createTestContext(userUser, { fakeProvider: fake });
540
- const res = await app.request(BASE, postBody({
541
- model: 'fake-model',
542
- messages: [{ role: 'user', content: 'привет' }],
543
- }));
544
- expect(res.status).toBe(status);
545
- const body = await res.json();
546
- expect(body.error.code).toBe(code);
547
- });
548
- it('fallback-классификация по тексту: 429 для «429» в обычном Error', async () => {
549
- const fake = new FakeProvider();
550
- fake.throwError = new Error('HTTP 429 Too Many Requests');
551
- const { app } = createTestContext(userUser, { fakeProvider: fake });
552
- const res = await app.request(BASE, postBody({
553
- model: 'fake-model',
554
- messages: [{ role: 'user', content: 'привет' }],
555
- }));
556
- expect(res.status).toBe(429);
557
- const body = await res.json();
558
- expect(body.error.code).toBe('RATE_LIMITED');
559
- });
560
- });
561
- describe('без auth', () => {
562
- it('возвращает 401', async () => {
563
- const app = new Hono();
564
- const kit = createUnauthorizedKit();
565
- const deps = {
566
- providerLoader: () => providerConfig,
567
- modelLoader: () => modelConfig,
568
- gatewayConfig: gatewayDisabledConfig,
569
- gatewayAuditLogger: new AuditLogger(join(tmpDir, 'audit', 'llm-gateway.jsonl')),
570
- gatewayRateLimiter: new RateLimiter(100, 100),
571
- patternStore: null,
572
- };
573
- app.route('/api/v2/llm', createLlmRoutes(kit, deps));
574
- const res = await app.request(BASE, postBody({
575
- model: 'fake-model',
576
- messages: [{ role: 'user', content: 'привет' }],
577
- }));
578
- expect(res.status).toBe(401);
579
- const body = await res.json();
580
- expect(body.error.code).toBe('UNAUTHORIZED');
581
- });
582
- });
583
- describe('LLM Gateway (AD-036)', () => {
584
- it('обфусцирует секрет в запросе и восстанавливает его в ответе (non-stream)', async () => {
585
- const fake = new FakeProvider();
586
- fake.echoUserContent = true;
587
- const patternStore = new SecretPatternStore({ dataDir: tmpDir });
588
- const { app, auditPath } = createTestContext(userUser, {
589
- fakeProvider: fake,
590
- gatewayConfig: gatewayEnabledConfig,
591
- patternStore,
592
- });
593
- const secret = 'sk-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
594
- const res = await app.request(BASE, postBody({
595
- model: 'fake-model',
596
- messages: [{ role: 'user', content: `мой ключ ${secret} используй его` }],
597
- }));
598
- expect(res.status).toBe(200);
599
- const body = await res.json();
600
- // Провайдер получил обфусцированное сообщение, ответ деобфусцирован.
601
- expect(fake.lastMessages[0].content).toContain('⟦SYNTH_SECRET_1⟧');
602
- expect(fake.lastMessages[0].content).not.toContain(secret);
603
- expect(body.choices[0].message.content).toContain(secret);
604
- expect(body.choices[0].message.content).not.toContain('⟦SYNTH_SECRET_1⟧');
605
- // Аудит: событие obfuscated записано.
606
- const auditRaw = await readFile(auditPath, 'utf8');
607
- const entries = auditRaw.trim().split('\n').map((l) => JSON.parse(l));
608
- expect(entries.some((e) => e.type === 'obfuscated' && e.sessionId === `llm-proxy:${userUser.id}`)).toBe(true);
609
- });
610
- it('с выключенным gateway секрет не трогается', async () => {
611
- const fake = new FakeProvider();
612
- fake.echoUserContent = true;
613
- const { app } = createTestContext(userUser, {
614
- fakeProvider: fake,
615
- gatewayConfig: gatewayDisabledConfig,
616
- });
617
- const secret = 'sk-ABCDEFGHIJKLMNOPQRSTUVWXYZ';
618
- const res = await app.request(BASE, postBody({
619
- model: 'fake-model',
620
- messages: [{ role: 'user', content: `мой ключ ${secret}` }],
621
- }));
622
- expect(res.status).toBe(200);
623
- const body = await res.json();
624
- expect(fake.lastMessages[0].content).toContain(secret);
625
- expect(body.choices[0].message.content).toContain(secret);
626
- });
627
- });
628
- });
629
- //# sourceMappingURL=llm.test.js.map