@animastor/assistant 0.1.0

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.
@@ -0,0 +1,1233 @@
1
+ // ======================================================
2
+ // @animastor/assistant — AI CHAT ROUTES
3
+ // ======================================================
4
+ // All /api/v1/ai/* endpoints.
5
+ //
6
+ // Physically extracted from backend/src/routes/ai-routes.cjs
7
+ // (docs/architecture/ai-assistant-extraction.md). The contour receives
8
+ // ONLY the narrow AssistantPorts seam + chat engine. No storage barrel,
9
+ // no SQL, no whole Book/VBook services, no host service requires — book
10
+ // reads/writes, provider resolution, session persistence AND the
11
+ // transport legs (SSRF-guarded fetch, connector shared-inference,
12
+ // shared-error description, source-token mapping) all arrive through
13
+ // the injected ports (chatTransport), wired host-side at the composition
14
+ // root.
15
+
16
+ module.exports = function(app, redis, deps) {
17
+ const {
18
+ chatEngine,
19
+ assistantPorts,
20
+ utils,
21
+ } = deps;
22
+ const { log } = utils;
23
+ // The ports seam is the single host contract of the Assistant contour.
24
+ const {
25
+ loadBook, persistBook, resolveChatAI,
26
+ sessionRepo,
27
+ chatTransport,
28
+ } = assistantPorts;
29
+ const { safeFetch, runSharedInference, describeSharedError, chatAiSourceToken } = chatTransport;
30
+ const sharedPool = {
31
+ runSharedInference,
32
+ describeSharedError,
33
+ };
34
+
35
+ // ── Session ID counter ───────────────────────────
36
+ let sessionIdCounter = 0;
37
+
38
+ // ── Workspace AI provider (Experimental Beta) ──────────────────────
39
+ // Phase 3: chat provider resolution lives on the Provider Gateway
40
+ // (host Provider Gateway adapter) — the stable entry point consumers
41
+ // use instead of the resolver internals. resolveChatAI is injected through
42
+ // the AssistantPorts seam (bound to the gateway at the composition root).
43
+
44
+ /** 503 guard — no usable AI provider (kill switch OFF / unconfigured). */
45
+ function aiUnavailable(res) {
46
+ return res.status(503).json({
47
+ error: 'AI is currently unavailable. No AI provider is configured or system AI is disabled.',
48
+ code: 'ai_unavailable',
49
+ });
50
+ }
51
+
52
+ const AI_FETCH_TIMEOUT_MS = 180_000; // 3 minutes — AI providers need time for large book contexts
53
+
54
+ // ── Token budget & thinking policy ─────────────────
55
+ // Tool-carrying requests use a HIGH max_tokens: reasoning models
56
+ // (deepseek-v4-flash, qwen3) count reasoning tokens against max_tokens,
57
+ // so a 4096 cap can be fully consumed by reasoning before any
58
+ // content/tool_call is produced (observed: finish_reason=length,
59
+ // reasoning_tokens=4096, empty content → "Tool executed" ghost reply).
60
+ // Tool-less conversation gets a small budget and no thinking — faster,
61
+ // cheaper replies.
62
+ const MAX_TOKENS_WITH_TOOLS = 16384;
63
+
64
+ // History entries with empty content (e.g. a UI-side "no result" turn
65
+ // pushed as {assistant, ''}) fail the connector's strict non-empty
66
+ // content validation — and would poison every later turn of the session.
67
+ // Dropped at the seam by both chat routes via this filter.
68
+ const hasNonEmptyContent = (m) => m && typeof m.content === 'string' && m.content.length > 0;
69
+ const MAX_TOKENS_PLAIN = 4096;
70
+
71
+ // Local AI Connector per-message cap is 32 KB (lib/chat.cjs
72
+ // maxMessageChars, mirrored by transport). The base system prompt plus
73
+ // tool instructions must also fit, so the book context budget is kept
74
+ // below it; anything larger rides as the compact structural summary.
75
+ const CONNECTOR_BOOK_CONTEXT_BUDGET = 24 * 1024;
76
+
77
+ function aiRequestBodyExtras(tools) {
78
+ const hasTools = Array.isArray(tools) && tools.length > 0;
79
+ return {
80
+ max_tokens: hasTools ? MAX_TOKENS_WITH_TOOLS : MAX_TOKENS_PLAIN,
81
+ enable_thinking: hasTools, // reasoning only for tool/edit work
82
+ };
83
+ }
84
+
85
+ // ── Hermesian tool call parser ──────────────────────
86
+ // Qwen3-32B (reasoning model) sometimes outputs tool_call as text in content
87
+ // instead of using the structured tool_calls field. This parser extracts those.
88
+ function extractToolCallsFromContent(content) {
89
+ if (!content) return { toolCalls: [], cleanedContent: content || '' };
90
+ const extracted = [];
91
+ let cleaned = content;
92
+ let idx = 0;
93
+ const now = Date.now();
94
+
95
+ // Pattern 1: 〖tool_call〗...〖/tool_call〗 (Hermesian bracket format)
96
+ cleaned = cleaned.replace(/[〖【]tool_call[〗】][\s\S]*?[〖【]\/tool_call[〗】]/g, (match) => {
97
+ const inner = match.replace(/[〖【]\/?tool_call[〗】]/g, '').trim();
98
+ const tc = _parseToolCallJson(inner, now, idx);
99
+ if (tc) { extracted.push(tc); idx++; }
100
+ return '';
101
+ });
102
+
103
+ // Pattern 2: Fallback — scan remaining content for any JSON object with balanced braces
104
+ cleaned = _extractBalancedJsonToolCalls(cleaned, extracted, now);
105
+
106
+ return { toolCalls: extracted, cleanedContent: cleaned.trim() };
107
+ }
108
+
109
+ function _extractBalancedJsonToolCalls(text, extracted, now) {
110
+ let result = '';
111
+ let i = 0;
112
+ while (i < text.length) {
113
+ if (text[i] === '{') {
114
+ let depth = 1;
115
+ let j = i + 1;
116
+ while (j < text.length && depth > 0) {
117
+ if (text[j] === '{') depth++;
118
+ else if (text[j] === '}') depth--;
119
+ j++;
120
+ }
121
+ if (depth === 0) {
122
+ const candidate = text.slice(i, j);
123
+ try {
124
+ const parsed = JSON.parse(candidate);
125
+ const name = parsed.name || parsed.function?.name;
126
+ if (name) {
127
+ const args = parsed.arguments || parsed.function?.arguments || {};
128
+ extracted.push({
129
+ id: `call_content_${now}_${extracted.length}`,
130
+ type: 'function',
131
+ function: {
132
+ name,
133
+ arguments: typeof args === 'string' ? args : JSON.stringify(args)
134
+ }
135
+ });
136
+ i = j; // skip matched part
137
+ continue;
138
+ }
139
+ } catch (_) {}
140
+ }
141
+ }
142
+ result += text[i];
143
+ i++;
144
+ }
145
+ return result;
146
+ }
147
+
148
+ function _parseToolCallJson(text, now, idx) {
149
+ try {
150
+ const p = JSON.parse(text);
151
+ const name = p.name || p.function?.name;
152
+ if (name) {
153
+ const args = p.arguments || p.function?.arguments || {};
154
+ return {
155
+ id: `call_content_${now}_${idx}`,
156
+ type: 'function',
157
+ function: {
158
+ name,
159
+ arguments: typeof args === 'string' ? args : JSON.stringify(args)
160
+ }
161
+ };
162
+ }
163
+ } catch (_) {
164
+ // Try extracting JSON from arbitrary surrounding text
165
+ const m = text.match(/\{[\s\S]*\}/);
166
+ if (m) {
167
+ try {
168
+ const p = JSON.parse(m[0]);
169
+ const name = p.name || p.function?.name;
170
+ if (name) {
171
+ const args = p.arguments || p.function?.arguments || {};
172
+ return {
173
+ id: `call_content_${now}_${idx}`,
174
+ type: 'function',
175
+ function: {
176
+ name,
177
+ arguments: typeof args === 'string' ? args : JSON.stringify(args)
178
+ }
179
+ };
180
+ }
181
+ } catch (_2) {}
182
+ }
183
+ }
184
+ return null;
185
+ }
186
+
187
+ // ======================================================
188
+ // LIST SESSIONS (metadata only — messages live behind /messages)
189
+ // ======================================================
190
+ app.get('/api/v1/ai/sessions', async (req, res) => {
191
+ try {
192
+ const { book_id } = req.query;
193
+ const sessions = await sessionRepo.listSessionsForBook(book_id);
194
+ res.json({ sessions });
195
+ } catch (err) {
196
+ console.error('[AI SESSIONS LIST] Error:', err.message);
197
+ res.json({ sessions: [] });
198
+ }
199
+ });
200
+
201
+ // ======================================================
202
+ // GET SESSION
203
+ // ======================================================
204
+ app.get('/api/v1/ai/sessions/:id', async (req, res) => {
205
+ try {
206
+ const session = await sessionRepo.getSession(req.params.id);
207
+ if (!session) return res.status(404).json({ error: 'Session not found' });
208
+ res.json({ session });
209
+ } catch (err) {
210
+ res.status(500).json({ error: err.message });
211
+ }
212
+ });
213
+
214
+ // ======================================================
215
+ // RENAME SESSION (PATCH) — Android parity: BackendApi.kt PATCHes
216
+ // { title } (BackendApi.kt:78). The route never existed → silent 404.
217
+ // ======================================================
218
+ app.patch('/api/v1/ai/sessions/:id', async (req, res) => {
219
+ try {
220
+ const { title } = req.body || {};
221
+ if (typeof title !== 'string' || !title.trim()) {
222
+ return res.status(400).json({ error: 'title required' });
223
+ }
224
+ const renamedId = await sessionRepo.renameSession(
225
+ req.params.id, title.trim().slice(0, 200)
226
+ );
227
+ if (!renamedId) return res.status(404).json({ error: 'Session not found' });
228
+ log('[AI] Session renamed:', req.params.id);
229
+ res.json({ session_id: req.params.id, title: title.trim(), renamed: true });
230
+ } catch (err) {
231
+ console.error('[AI SESSION RENAME] Error:', err.message);
232
+ res.status(500).json({ error: err.message });
233
+ }
234
+ });
235
+
236
+ // ======================================================
237
+ // DELETE SESSION — Android parity (BackendApi.kt:84) and web parity
238
+ // (AiAssistantPage deleteSession). Both clients called this route when
239
+ // it did not exist → silent 404, chats never deleted server-side.
240
+ // ======================================================
241
+ app.delete('/api/v1/ai/sessions/:id', async (req, res) => {
242
+ try {
243
+ const deletedId = await sessionRepo.deleteSession(req.params.id);
244
+ if (!deletedId) return res.status(404).json({ error: 'Session not found' });
245
+ log('[AI] Session deleted:', req.params.id);
246
+ res.json({ session_id: req.params.id, deleted: true });
247
+ } catch (err) {
248
+ console.error('[AI SESSION DELETE] Error:', err.message);
249
+ res.status(500).json({ error: err.message });
250
+ }
251
+ });
252
+
253
+ // ======================================================
254
+ // GET SESSION MESSAGES (session.messages JSON via the sessionRepo port)
255
+ // ======================================================
256
+ app.get('/api/v1/ai/sessions/:id/messages', async (req, res) => {
257
+ try {
258
+ const session = await sessionRepo.getSession(req.params.id);
259
+ if (!session) return res.json({ messages: [] });
260
+ const msgs = session.messages || [];
261
+ const formatted = msgs.map((m, i) => ({
262
+ id: i + 1,
263
+ book_id: session.book_id,
264
+ session_id: session.id,
265
+ role: m.role || 'user',
266
+ message: m.content || m.message || '',
267
+ error: !!m.error,
268
+ created_at: m.timestamp || Date.now(),
269
+ }));
270
+ res.json({ messages: formatted });
271
+ } catch (err) {
272
+ console.error('[AI SESSION MESSAGES] Error:', err.message);
273
+ res.json({ messages: [] });
274
+ }
275
+ });
276
+
277
+ // ======================================================
278
+ // CREATE SESSION
279
+ // ======================================================
280
+ app.post('/api/v1/ai/sessions', async (req, res) => {
281
+ try {
282
+ const { book_id, title, mode, topic_id } = req.body || {};
283
+ const scopedBookId = req.scopedBookId || book_id || null;
284
+ if (!scopedBookId) return res.status(400).json({ error: 'book_id required' });
285
+
286
+ const id = `ai-session-${Date.now()}-${++sessionIdCounter}`;
287
+ const cleanTitle = (typeof title === 'string' && title.trim()) ? title.trim().slice(0, 200) : 'Chat';
288
+ const session = {
289
+ id, book_id: scopedBookId, title: cleanTitle, mode: mode || 'chat',
290
+ topic_id: topic_id || 'book',
291
+ messages: [], created_at: Date.now(), updated_at: Date.now(),
292
+ context: null, locked: false,
293
+ };
294
+
295
+ await sessionRepo.createSession(session);
296
+
297
+ log('[AI] Created session:', id, 'for book:', book_id, 'mode:', session.mode);
298
+ res.json({ session });
299
+ } catch (err) {
300
+ console.error('[AI CREATE SESSION] Error:', err.message);
301
+ res.status(500).json({ error: err.message });
302
+ }
303
+ });
304
+
305
+ // ======================================================
306
+ // CHAT (non-streaming)
307
+ // ======================================================
308
+ app.post('/api/v1/ai/chat', async (req, res) => {
309
+ // Hoisted so the catch block can persist the failed turn (user
310
+ // message + error explanation) into the session history — without
311
+ // this the 504 explanation never reached the UI after a reload
312
+ // (messages live behind the sessionRepo port — PG is host-side).
313
+ let activeSessionId = null;
314
+ let userContent = '';
315
+ // Consumer-side AI source provenance (Phase 2): 'private-local' |
316
+ // 'shared' | 'cloud' | 'system' — a safe token for the UI badge,
317
+ // never endpoint/owner detail.
318
+ let aiSource = null;
319
+ try {
320
+ const { session_id, message, messages, book_id, system, mode, scene_id, topic_id } = req.body || {};
321
+
322
+ // Accept either `messages` array (frontend format) or `message` string (legacy)
323
+ const hasMessagesArray = Array.isArray(messages) && messages.length > 0;
324
+ if (!hasMessagesArray && !message) {
325
+ return res.status(400).json({ error: 'messages or message required' });
326
+ }
327
+
328
+ // The AUTHORIZED book — set by aiBookGuard. Never re-derive a
329
+ // different one from the body (cross-tenant provider/data/write).
330
+ const scopedBookId = req.scopedBookId || book_id || null;
331
+
332
+ // Auto-create session if session_id not provided
333
+ activeSessionId = session_id;
334
+ if (!activeSessionId) {
335
+ if (!scopedBookId) {
336
+ return res.status(400).json({ error: 'book_id required when no session_id' });
337
+ }
338
+ const id = `ai-session-${Date.now()}-${++sessionIdCounter}`;
339
+ await sessionRepo.createSession({
340
+ id, book_id: scopedBookId, mode: mode || 'chat',
341
+ topic_id: topic_id || 'book',
342
+ messages: [], created_at: Date.now(), updated_at: Date.now(),
343
+ });
344
+ activeSessionId = id;
345
+ log('[AI] Auto-created session:', id, 'for book:', scopedBookId);
346
+ }
347
+
348
+ const session = await sessionRepo.getSession(activeSessionId);
349
+ if (!session) return res.status(404).json({ error: 'Session not found' });
350
+
351
+ const storedMessages = session.messages || [];
352
+ const bookId = req.scopedBookId || book_id || session.book_id;
353
+
354
+ // Load book data for context (AssistantPorts seam — canonical ||
355
+ // draft fallback lives inside the facade)
356
+ let bookData = null;
357
+ try { bookData = loadBook(bookId); } catch (_) {}
358
+
359
+ const isLocked = bookData?.manifest?.locked === true;
360
+ const sessionMode = mode || session.mode || 'chat';
361
+ const tools = chatEngine.getToolsForMode(sessionMode, bookId, isLocked);
362
+
363
+ const ai = await resolveChatAI(bookId);
364
+ // Connector snapshots legitimately carry no apiKey (LAC §9) —
365
+ // the connector path is guarded below at the fetch site.
366
+ if (!ai.apiKey && ai.transport !== 'connector') return aiUnavailable(res);
367
+ // A connector binding without a usable model id (no bound model,
368
+ // no discovered models) must fail closed with a clear message.
369
+ if (ai.transport === 'connector' && (!ai.connectorId || !ai.model)) {
370
+ return res.status(503).json({
371
+ error: 'Local AI is not ready — select a connector and a model in Settings / AI',
372
+ code: 'local_ai_not_ready',
373
+ });
374
+ }
375
+
376
+ // Build system prompt:
377
+ // - If `system` is explicitly provided (legacy clients), use it as base
378
+ // - Otherwise, build from structured fields (mode, topic, lang, position)
379
+ // via chatEngine.buildChatSystemPrompt() — this replaces the client-side
380
+ // system prompt assembly in AiAssistantFragment.sendMessage().
381
+ let systemPrompt;
382
+ if (system) {
383
+ // Legacy path: frontend sent fully assembled prompt
384
+ systemPrompt = system;
385
+
386
+ } else {
387
+ // F6 path: assemble from structured fields on the server.
388
+ systemPrompt = chatEngine.buildChatSystemPrompt({
389
+ mode: mode || session.mode || 'conversation',
390
+ topic: topic_id || session.topic_id || 'book',
391
+ lang: req.body?.lang || 'auto',
392
+ bookData,
393
+ sceneId: req.body?.scene_id || null,
394
+ unitIndex: req.body?.unit_index ?? null,
395
+ modelName: ai.model,
396
+ });
397
+
398
+ }
399
+
400
+ const bookContext = chatEngine.buildBookContext(bookData);
401
+ if (bookContext) {
402
+ // Connector per-message cap is 32 KB (ai-connector
403
+ // lib/chat.cjs maxMessageChars, mirrored by the transport) —
404
+ // the full book JSON for real books does not fit. Oversized
405
+ // context falls back to the compact structural summary so a
406
+ // private-local request fails closed on nothing else.
407
+ const withinConnectorBudget = bookContext.length <= CONNECTOR_BOOK_CONTEXT_BUDGET;
408
+ systemPrompt += '\n\n' + (ai.transport !== 'connector' || withinConnectorBudget
409
+ ? bookContext
410
+ : chatEngine.buildCompactBookContext(bookData));
411
+ }
412
+
413
+ // Build API messages for AI call
414
+ let apiMessages;
415
+
416
+ if (hasMessagesArray) {
417
+ // Frontend format: full history in `messages` array, `system` as system prompt
418
+ apiMessages = [
419
+ { role: 'system', content: systemPrompt },
420
+ ...messages.filter(hasNonEmptyContent),
421
+ ];
422
+ const lastUser = messages.filter(m => m.role === 'user').pop();
423
+ userContent = lastUser?.content || '';
424
+ } else {
425
+ // Legacy format: single `message` string, reconstruct from DB
426
+ userContent = message;
427
+ apiMessages = [
428
+ { role: 'system', content: systemPrompt },
429
+ ...(storedMessages.slice(-20).map(m => ({ role: m.role, content: m.content }))),
430
+ { role: 'user', content: message },
431
+ ];
432
+ }
433
+
434
+ let aiResponse;
435
+ if (ai.transport === 'connector') {
436
+ // Local AI Connector path (LAC §9): the completion rides the
437
+ // connector's authenticated WS session — no server-side URL,
438
+ // no Authorization header, no SSRF surface (AD-5). The cloud
439
+ // timer is authoritative (§5); runSharedInference maps to the
440
+ // sanitized code surface (§4) and, for SHARED snapshots
441
+ // (Phase 2), owns the per-inference pool slot (reserved
442
+ // before the call; released on success/error/timeout/cancel/
443
+ // disconnect via its finally). Tool payloads are NOT
444
+ // forwarded (Phase-4 contract: only max_tokens/temperature
445
+ // survive) — content-embedded tool calls still go through
446
+ // extractToolCallsFromContent below.
447
+ const tokenBudget = tools.length > 0
448
+ ? Math.min(MAX_TOKENS_WITH_TOOLS, 8192) // connector LIMITS.maxMaxTokens
449
+ : MAX_TOKENS_PLAIN;
450
+ // Shared capacity is borrowed: a consumer that walked away
451
+ // must not keep burning the owner's slot — res 'close' before
452
+ // the response completed aborts the request (the private
453
+ // path keeps its existing no-abort semantics unchanged).
454
+ let disconnectSignal = null;
455
+ let onConnClosed = null;
456
+ if (ai.source === 'shared') {
457
+ const abort = new AbortController();
458
+ disconnectSignal = abort.signal;
459
+ onConnClosed = () => { if (!res.writableEnded) abort.abort(); };
460
+ res.on('close', onConnClosed);
461
+ }
462
+ let cres;
463
+ try {
464
+ cres = await sharedPool.runSharedInference(ai, {
465
+ model: ai.model,
466
+ messages: apiMessages,
467
+ params: { max_tokens: tokenBudget, temperature: 0.3 },
468
+ }, { timeoutMs: AI_FETCH_TIMEOUT_MS, signal: disconnectSignal });
469
+ } finally {
470
+ if (onConnClosed) res.removeListener('close', onConnClosed);
471
+ }
472
+ if (!cres.ok) {
473
+ const code = cres.code || 'runtime_error';
474
+ const status = (code === 'connector_offline' || code === 'shared_unavailable' || code === 'busy')
475
+ ? 503 : (code === 'timeout' || code === 'cancelled' ? 504 : 502);
476
+ console.error(`[AI] connector chat error: ${code}`);
477
+ return res.status(status).json({
478
+ error: sharedPool.describeSharedError(code),
479
+ code,
480
+ });
481
+ }
482
+ aiResponse = {
483
+ choices: [{
484
+ index: 0,
485
+ message: { role: 'assistant', content: cres.content },
486
+ finish_reason: cres.finishReason || 'stop',
487
+ }],
488
+ usage: cres.usage || undefined,
489
+ };
490
+ // Consumer-side source provenance (Phase 2, minimal):
491
+ // 'private-local' | 'shared' — safe token only, no endpoint
492
+ // or owner detail rides the API response.
493
+ aiSource = ai.source === 'shared' ? 'shared' : 'private-local';
494
+ } else {
495
+ const controller = new AbortController();
496
+ const timeout = setTimeout(() => controller.abort(), AI_FETCH_TIMEOUT_MS);
497
+ const response = await safeFetch(`${ai.baseUrl}/chat/completions`, {
498
+ method: 'POST',
499
+ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ai.apiKey}` },
500
+ body: JSON.stringify({
501
+ model: ai.model,
502
+ messages: apiMessages,
503
+ tools: tools.length > 0 ? tools : undefined,
504
+ tool_choice: tools.length > 0 ? 'auto' : undefined,
505
+ ...aiRequestBodyExtras(tools),
506
+ }),
507
+ signal: controller.signal,
508
+ validatePublic: ai.validatePublic,
509
+ });
510
+ clearTimeout(timeout);
511
+
512
+ if (!response.ok) {
513
+ const errText = await response.text();
514
+ console.error('[AI] API error:', response.status, errText);
515
+ return res.status(502).json({ error: `AI API error: ${response.status}` });
516
+ }
517
+
518
+ aiResponse = await response.json();
519
+ }
520
+ const aiMessage = aiResponse.choices?.[0]?.message;
521
+ let replyText = aiMessage?.content || '';
522
+ // Strip AI chain-of-thought reasoning blocks — internal, not for the UI
523
+ replyText = replyText.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
524
+ // Strip tool_call & tool_call markers that some models leak into content
525
+ replyText = replyText.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
526
+ replyText = replyText.replace(/<\/?tool_call[^>]*>/gi, '').trim();
527
+ // Also strip partial tool_call remnants without the opening '<' (e.g. 'tool_call>')
528
+ replyText = replyText.replace(/tool_call[^>]*>/gi, '').trim();
529
+ replyText = replyText.replace(/\/?tool_call\b/gi, '').trim();
530
+ // Catch any remaining tool_call-like fragments where leading chars may be missing
531
+ // (e.g. 'ool_call>' — Qwen3 sometimes outputs partial tag remnants)
532
+ replyText = replyText.replace(/[a-z]*_call[^>]*>/gi, '').trim();
533
+ // Only extract tool calls from content if model didn't return structured tool_calls
534
+ // (avoids duplicates — Qwen3 sometimes puts tool_call JSON in both places)
535
+ const structuredToolCalls = aiMessage?.tool_calls || [];
536
+ let contentToolCalls = [];
537
+ if (structuredToolCalls.length === 0) {
538
+ const result = extractToolCallsFromContent(replyText);
539
+ contentToolCalls = result.toolCalls;
540
+ replyText = result.cleanedContent;
541
+ }
542
+ // If after stripping, the reply is just garbage remnants (e.g. 'ool_call>', 'tool_call>'),
543
+ // treat as empty so the fallback message below kicks in.
544
+ // A remnant is considered garbage if:
545
+ // - it has no real word of 3+ letters, OR
546
+ // - it contains '_call' (a tool_call-like fragment)
547
+ if (replyText && replyText.length < 30 && (!/[\w\u0400-\u04FF]{3,}/.test(replyText) || /_call/i.test(replyText))) {
548
+ replyText = '';
549
+ }
550
+ const toolCalls = [...contentToolCalls, ...structuredToolCalls];
551
+
552
+ // Handle tool calls
553
+ let patches = [];
554
+ let toolResults = [];
555
+ let lastEditError = null;
556
+
557
+ if (toolCalls.length > 0) {
558
+ for (const tc of toolCalls) {
559
+ if (tc.function.name === 'edit_book') {
560
+ try {
561
+ const args = JSON.parse(tc.function.arguments);
562
+ // Validated application: patch → contract validation →
563
+ // result. A structurally broken result (e.g. voices.json
564
+ // becoming a string instead of an object) is rejected
565
+ // here and never reaches the save block below.
566
+ const patchResult = chatEngine.applyPatchesValidated(bookData, args.patches || []);
567
+ if (patchResult.errors.length > 0) {
568
+ const errMsg = patchResult.errors.join('; ');
569
+ toolResults.push({ tool: 'edit_book', error: errMsg, validation_errors: patchResult.validation_errors });
570
+ lastEditError = errMsg;
571
+ } else {
572
+ patches = args.patches || [];
573
+ toolResults.push({ tool: 'edit_book', applied: patches.length, book_id: bookId });
574
+ }
575
+ } catch (parseErr) {
576
+ toolResults.push({ tool: 'edit_book', error: parseErr.message });
577
+ lastEditError = parseErr.message;
578
+ }
579
+ } else {
580
+ toolResults.push({ tool: tc.function.name, result: 'Tool executed (no handler)' });
581
+ }
582
+ }
583
+ }
584
+
585
+ // Save patches if any were applied
586
+ if (patches.length > 0 && bookData) {
587
+ try {
588
+ // Re-apply with validation (defense in depth): the save block
589
+ // is the last gate before disk — an invalid candidate state
590
+ // must never be written and must not be reported as applied.
591
+ const patchResult = chatEngine.applyPatchesValidated(bookData, patches);
592
+ if (patchResult.errors.length > 0) {
593
+ // Reject the whole mutation: keep previous canonical state,
594
+ // report the failure to the assistant/user, apply nothing.
595
+ if (!lastEditError) lastEditError = patchResult.errors.join('; ');
596
+ patches = [];
597
+ toolResults.push({ tool: 'edit_book', error: lastEditError, validation_errors: patchResult.validation_errors, rejected: true });
598
+ } else if (patchResult.result) {
599
+ // ONE save semantics through the AssistantPorts seam:
600
+ // full bundle save when chapters are intact, targeted
601
+ // file save (chapters skipped) on a corrupted load.
602
+ persistBook(bookId, patchResult.result);
603
+ log('[AI] Book updated (via persistBook):', patches.length, 'patches applied to', bookId);
604
+ }
605
+ } catch (saveErr) {
606
+ console.error('[AI] Failed to save updated book:', saveErr.message);
607
+ if (!lastEditError) lastEditError = saveErr.message;
608
+ // Nothing was persisted — do not report success.
609
+ patches = [];
610
+ }
611
+ }
612
+
613
+ // Build a user-visible reply when the AI returned empty content but tool calls were processed
614
+ if (!replyText && toolCalls.length > 0) {
615
+ if (lastEditError) {
616
+ replyText = `⚠️ Edit error: ${lastEditError}`;
617
+ } else if (patches.length > 0) {
618
+ replyText = `✅ Changes applied: ${patches.length} patch(es) to the book.`;
619
+ } else {
620
+ replyText = `🤖 Processed ${toolCalls.length} tool call(s).`;
621
+ }
622
+ }
623
+
624
+ // No content AND no tool calls — the model produced nothing usable
625
+ // (e.g. a reasoning model burned the whole max_tokens budget on
626
+ // reasoning). Report it honestly instead of returning an empty
627
+ // reply that UIs render as a fake "tool executed" message.
628
+ if (!replyText && toolCalls.length === 0) {
629
+ replyText = '⚠️ The assistant returned no result. Please try again.';
630
+ }
631
+
632
+ // Update session messages: merge with stored history
633
+ const updatedMessages = [
634
+ ...storedMessages,
635
+ { role: 'user', content: userContent, timestamp: Date.now() },
636
+ { role: 'assistant', content: replyText, tool_calls: toolCalls, timestamp: Date.now() },
637
+ ];
638
+
639
+ await sessionRepo.setMessages(activeSessionId, updatedMessages);
640
+
641
+ // Structured validation info for the assistant/API: names the exact
642
+ // file/resource that failed the bundle contract, so a corrective
643
+ // patch ("почини voices.json") lands in the very next turn —
644
+ // the error reply is stored in session history for that purpose.
645
+ const validationErrors = toolResults
646
+ .flatMap(tr => tr.validation_errors || []);
647
+
648
+ res.json({
649
+ reply: replyText,
650
+ tool_calls: toolCalls,
651
+ tool_results: toolResults,
652
+ patches_applied: patches.length,
653
+ validation_errors: validationErrors,
654
+ session_id: activeSessionId,
655
+ ai_source: aiSource || (ai.source === 'workspace' ? 'cloud' : (ai.source === 'system' ? 'system' : ai.source)),
656
+ });
657
+ } catch (err) {
658
+ console.error('[AI CHAT] Error:', err.message);
659
+ if (err.code === 'ENDPOINT_NOT_PUBLIC') {
660
+ return res.status(502).json({ error: err.message });
661
+ }
662
+ if (err.name === 'AbortError' || err.code === 'ABORT_ERR') {
663
+ // Persist the failed turn (user message + explanation) so the
664
+ // explanation survives a reload and is visible in session
665
+ // history. Best-effort: a PG hiccup must not mask the 504.
666
+ try {
667
+ if (activeSessionId) {
668
+ const msgs = await sessionRepo.getMessages(activeSessionId);
669
+ msgs.push({ role: 'user', content: userContent, timestamp: Date.now() });
670
+ msgs.push({
671
+ role: 'assistant',
672
+ content: '⚠️ AI не ответил за отведённое время. Попробуйте отправить более короткий запрос или повторить позже.',
673
+ error: true, timestamp: Date.now(),
674
+ });
675
+ await sessionRepo.setMessages(activeSessionId, msgs);
676
+ }
677
+ } catch (persistErr) {
678
+ console.error('[AI CHAT] Failed to persist timeout turn:', persistErr.message);
679
+ }
680
+ return res.status(504).json({ error: 'AI не ответил за отведённое время. Попробуйте отправить более короткий запрос или повторить позже.', code: 'ai_timeout' });
681
+ }
682
+ res.status(500).json({ error: err.message });
683
+ }
684
+ });
685
+
686
+ // ======================================================
687
+ // CHAT STREAM (production SSE — Phase 3 LLM sharing)
688
+ // ======================================================
689
+ // The production streaming path:
690
+ //
691
+ // Browser → THIS route → resolver (resolveChatAI — the SAME seam as
692
+ // the non-streaming chat route) → private connector OR shared pool
693
+ // endpoint → connector WS → local runtime SSE → connector chat.delta
694
+ // → here → HTTP SSE to the browser.
695
+ //
696
+ // ONE transport, ONE protocol: connector inference rides the existing
697
+ // runSharedInference streaming branch (params.stream:true over the
698
+ // connector WS — Phase 5 chat.delta machinery unchanged); shared slots
699
+ // keep the exact Phase 2 lifecycle (reserved before the call, released
700
+ // on success/error/timeout/cancel/disconnect via its finally). Cloud
701
+ // providers keep their existing non-streaming upstream call (re-emitted
702
+ // as ONE delta + terminal — no second upstream protocol is invented).
703
+ //
704
+ // SSE contract (one JSON object per `data:` frame):
705
+ // meta { session_id, ai_source, model } — once, after resolution
706
+ // delta { delta: "text" } — N× (connector streams;
707
+ // cloud = one full-text delta)
708
+ // done { reply, tool_calls, tool_results, patches_applied,
709
+ // validation_errors, session_id, ai_source, usage,
710
+ // finish_reason } — terminal, exactly once
711
+ // error { error, code, partial? } — terminal, exactly once
712
+ // (sanitized code + fixed
713
+ // message only)
714
+ // Exactly ONE terminal event (done XOR error) is ever written. Raw
715
+ // runtime errors, URLs, credentials and connector secrets never cross —
716
+ // every failure degrades to the sanitized code surface (Phase 2 §5).
717
+ //
718
+ // Cancellation path (critical): HTTP client disconnect → res 'close' →
719
+ // AbortSignal → connector transport chat.cancel → local runtime abort
720
+ // → slot released by runSharedInference's finally. No pending request
721
+ // and no shared slot survives any failure path.
722
+ // ======================================================
723
+ // <think>…</think> reasoning blocks are internal — they must not appear
724
+ // in the user-visible stream (the non-streaming route strips them from
725
+ // the final text). The stream filter suppresses them incrementally,
726
+ // holding back a possible partial tag so a tag split across two deltas
727
+ // is still caught. The terminal done event carries the SAME fully
728
+ // stripped/processed reply as the non-streaming route, so the client
729
+ // always converges to the canonical text.
730
+ function makeThinkFilter() {
731
+ let inside = false;
732
+ let tail = '';
733
+ const partialTagLen = (text, tag) => {
734
+ const max = Math.min(tag.length - 1, text.length);
735
+ for (let k = max; k > 0; k--) {
736
+ if (text.endsWith(tag.slice(0, k))) return k;
737
+ }
738
+ return 0;
739
+ };
740
+ return (delta) => {
741
+ let text = tail + delta;
742
+ tail = '';
743
+ let out = '';
744
+ while (text) {
745
+ if (!inside) {
746
+ const i = text.indexOf('<think>');
747
+ if (i === -1) {
748
+ const hold = partialTagLen(text, '<think>');
749
+ out += text.slice(0, text.length - hold);
750
+ tail = text.slice(text.length - hold);
751
+ break;
752
+ }
753
+ out += text.slice(0, i);
754
+ text = text.slice(i + 7);
755
+ inside = true;
756
+ } else {
757
+ const j = text.indexOf('</think>');
758
+ if (j === -1) {
759
+ const hold = partialTagLen(text, '</think>');
760
+ tail = text.slice(text.length - hold);
761
+ break;
762
+ }
763
+ text = text.slice(j + 8);
764
+ inside = false;
765
+ }
766
+ }
767
+ return out;
768
+ };
769
+ }
770
+
771
+ // The bounded per-request inference window for the stream route: the
772
+ // client may tighten it (its own request), the cloud timer stays
773
+ // authoritative (transport clamps to the same 180 s ceiling).
774
+ const STREAM_MIN_TIMEOUT_MS = 1_000;
775
+
776
+ function clampStreamTimeoutMs(raw) {
777
+ const n = Number(raw);
778
+ if (!Number.isFinite(n)) return AI_FETCH_TIMEOUT_MS;
779
+ return Math.max(STREAM_MIN_TIMEOUT_MS, Math.min(Math.floor(n), AI_FETCH_TIMEOUT_MS));
780
+ }
781
+
782
+ // Map a resolved chat provider to the SAFE consumer-facing source token
783
+ // (Phase 2 §6 discipline: 'private-local' | 'shared' | 'cloud' | 'system'
784
+ // — never endpoint/owner detail). The token mapping lives on the host
785
+ // Provider Gateway; the contour reaches it through the injected
786
+ // chatTransport port (composition-root bound).
787
+
788
+ app.post('/api/v1/ai/chat/stream', async (req, res) => {
789
+ // Hoisted for the failure-persistence helpers (same rationale as the
790
+ // non-streaming route: a failed turn must survive a reload).
791
+ let activeSessionId = null;
792
+ let userContent = '';
793
+ let storedMessages = [];
794
+ const aiSource = { value: null };
795
+ // Terminal-event contract: exactly one terminal frame, ever.
796
+ let terminalSent = false;
797
+ let heartbeat = null;
798
+
799
+ // Best-effort persistence of a FAILED turn (user message + sanitized
800
+ // explanation / partial answer) — mirrors the non-streaming route's
801
+ // catch-block discipline. Never masks the terminal event.
802
+ const persistFailedTurn = async (assistantText) => {
803
+ try {
804
+ if (!activeSessionId) return;
805
+ const msgs = await sessionRepo.getMessages(activeSessionId);
806
+ if (userContent) msgs.push({ role: 'user', content: userContent, timestamp: Date.now() });
807
+ if (assistantText) {
808
+ msgs.push({ role: 'assistant', content: assistantText, error: true, timestamp: Date.now() });
809
+ }
810
+ await sessionRepo.setMessages(activeSessionId, msgs);
811
+ } catch (persistErr) {
812
+ console.error('[AI STREAM] Failed to persist failed turn:', persistErr.message);
813
+ }
814
+ };
815
+
816
+ try {
817
+ const { session_id, message, messages, book_id, system, mode, scene_id, topic_id } = req.body || {};
818
+
819
+ // Same input contract as the non-streaming route.
820
+ const hasMessagesArray = Array.isArray(messages) && messages.length > 0;
821
+ if (!hasMessagesArray && !message) {
822
+ return res.status(400).json({ error: 'messages or message required' });
823
+ }
824
+
825
+ const scopedBookId = req.scopedBookId || book_id || null;
826
+
827
+ activeSessionId = session_id;
828
+ if (!activeSessionId) {
829
+ if (!scopedBookId) {
830
+ return res.status(400).json({ error: 'book_id required when no session_id' });
831
+ }
832
+ const id = `ai-session-${Date.now()}-${++sessionIdCounter}`;
833
+ await sessionRepo.createSession({
834
+ id, book_id: scopedBookId, mode: mode || 'chat',
835
+ topic_id: topic_id || 'book',
836
+ messages: [], created_at: Date.now(), updated_at: Date.now(),
837
+ });
838
+ activeSessionId = id;
839
+ log('[AI STREAM] Auto-created session:', id, 'for book:', scopedBookId);
840
+ }
841
+
842
+ const session = await sessionRepo.getSession(activeSessionId);
843
+ if (!session) return res.status(404).json({ error: 'Session not found' });
844
+
845
+ storedMessages = session.messages || [];
846
+ const bookId = req.scopedBookId || book_id || session.book_id;
847
+
848
+ let bookData = null;
849
+ // AssistantPorts seam — canonical || draft fallback lives inside
850
+ // the Book Model facade
851
+ try { bookData = loadBook(bookId); } catch (_) {}
852
+
853
+ const isLocked = bookData?.manifest?.locked === true;
854
+ const sessionMode = mode || session.mode || 'chat';
855
+ const tools = chatEngine.getToolsForMode(sessionMode, bookId, isLocked);
856
+
857
+ // The SAME resolver seam as the non-streaming route — shared AI,
858
+ // private Local AI and cloud providers all flow through here.
859
+ const ai = await resolveChatAI(bookId);
860
+ if (!ai.apiKey && ai.transport !== 'connector') return aiUnavailable(res);
861
+ if (ai.transport === 'connector' && (!ai.connectorId || !ai.model)) {
862
+ return res.status(503).json({
863
+ error: 'Local AI is not ready — select a connector and a model in Settings / AI',
864
+ code: 'local_ai_not_ready',
865
+ });
866
+ }
867
+ aiSource.value = chatAiSourceToken(ai);
868
+
869
+ let systemPrompt;
870
+ if (system) {
871
+ systemPrompt = system;
872
+ } else {
873
+ systemPrompt = chatEngine.buildChatSystemPrompt({
874
+ mode: mode || session.mode || 'conversation',
875
+ topic: topic_id || session.topic_id || 'book',
876
+ lang: req.body?.lang || 'auto',
877
+ bookData,
878
+ sceneId: req.body?.scene_id || null,
879
+ unitIndex: req.body?.unit_index ?? null,
880
+ modelName: ai.model,
881
+ });
882
+ }
883
+
884
+ const bookContext = chatEngine.buildBookContext(bookData);
885
+ if (bookContext) {
886
+ // Same connector per-message cap as the non-streaming route —
887
+ // oversized book JSON falls back to the compact summary.
888
+ const withinConnectorBudget = bookContext.length <= CONNECTOR_BOOK_CONTEXT_BUDGET;
889
+ systemPrompt += '\n\n' + (ai.transport !== 'connector' || withinConnectorBudget
890
+ ? bookContext
891
+ : chatEngine.buildCompactBookContext(bookData));
892
+ }
893
+
894
+ let apiMessages;
895
+ if (hasMessagesArray) {
896
+ // Same empty-content guard as the non-streaming route — one
897
+ // empty turn must not poison the rest of the session.
898
+ apiMessages = [
899
+ { role: 'system', content: systemPrompt },
900
+ ...messages.filter(hasNonEmptyContent),
901
+ ];
902
+ const lastUser = messages.filter(m => m.role === 'user').pop();
903
+ userContent = lastUser?.content || '';
904
+ } else {
905
+ userContent = message;
906
+ apiMessages = [
907
+ { role: 'system', content: systemPrompt },
908
+ ...(storedMessages.slice(-20).map(m => ({ role: m.role, content: m.content }))),
909
+ { role: 'user', content: message },
910
+ ];
911
+ }
912
+
913
+ // ── Stream phase: headers go out; every failure from here on is
914
+ // a terminal SSE error event (never a raw runtime detail). ──
915
+ res.status(200);
916
+ res.setHeader('Content-Type', 'text/event-stream; charset=utf-8');
917
+ res.setHeader('Cache-Control', 'no-cache, no-transform');
918
+ res.setHeader('Connection', 'keep-alive');
919
+ res.setHeader('X-Accel-Buffering', 'no'); // disable nginx buffering
920
+ res.flushHeaders?.();
921
+
922
+ const writeEvent = (event, data) => {
923
+ try {
924
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
925
+ return true;
926
+ } catch (_) { return false; }
927
+ };
928
+ const sendTerminal = (event, data) => {
929
+ if (terminalSent) return;
930
+ terminalSent = true;
931
+ writeEvent(event, data);
932
+ try { res.end(); } catch (_) {}
933
+ };
934
+
935
+ // Heartbeat comment keeps proxies/clients alive during long
936
+ // model cold-loads (30–60 s with no delta); SSE comments are
937
+ // ignored by parsers.
938
+ heartbeat = setInterval(() => {
939
+ try { res.write(': ping\n\n'); } catch (_) {}
940
+ }, 15_000);
941
+ if (heartbeat.unref) heartbeat.unref();
942
+
943
+ // Cancel path: HTTP disconnect → AbortSignal → connector
944
+ // transport chat.cancel → runtime abort → slot freed. Applies to
945
+ // EVERY source on this route (the client is gone — the inference
946
+ // must stop; the non-streaming route keeps its own semantics).
947
+ const abort = new AbortController();
948
+ let clientGone = false;
949
+ const onConnClosed = () => {
950
+ clientGone = true;
951
+ abort.abort();
952
+ };
953
+ res.on('close', onConnClosed);
954
+
955
+ writeEvent('meta', {
956
+ session_id: activeSessionId,
957
+ ai_source: aiSource.value,
958
+ model: ai.model || undefined,
959
+ });
960
+
961
+ let finalReply = '';
962
+ let terminalPayload = null;
963
+ try {
964
+ if (ai.transport === 'connector') {
965
+ const tokenBudget = tools.length > 0
966
+ ? Math.min(MAX_TOKENS_WITH_TOOLS, 8192)
967
+ : MAX_TOKENS_PLAIN;
968
+ const filter = makeThinkFilter();
969
+ let streamedLen = 0;
970
+ const cres = await sharedPool.runSharedInference(ai, {
971
+ model: ai.model,
972
+ messages: apiMessages,
973
+ params: { max_tokens: tokenBudget, temperature: 0.3 },
974
+ }, {
975
+ timeoutMs: clampStreamTimeoutMs(req.body?.timeout_ms),
976
+ signal: abort.signal,
977
+ onDelta: (delta) => {
978
+ const visible = filter(delta);
979
+ if (!visible) return;
980
+ streamedLen += visible.length;
981
+ if (!writeEvent('delta', { delta: visible })) {
982
+ // The client is gone mid-stream — stop the
983
+ // inference the same way a disconnect does.
984
+ abort.abort();
985
+ }
986
+ },
987
+ });
988
+ if (!cres.ok) {
989
+ console.error(`[AI STREAM] connector stream error: ${cres.code}`);
990
+ // Partial output is never lost: the client already
991
+ // holds the deltas; the error frame re-states the
992
+ // visible partial for reconciliation.
993
+ const partial = (clientGone ? null : (cres.partial || (streamedLen > 0 ? null : null)));
994
+ const errorData = {
995
+ error: sharedPool.describeSharedError(cres.code),
996
+ code: cres.code || 'runtime_error',
997
+ };
998
+ if (cres.partial) errorData.partial = cres.partial;
999
+ else if (partial) errorData.partial = partial;
1000
+ if (!clientGone) sendTerminal('error', errorData);
1001
+ await persistFailedTurn(
1002
+ cres.partial || (streamedLen > 0 ? null : `⚠️ ${errorData.error}`)
1003
+ );
1004
+ return;
1005
+ }
1006
+ // Terminal success → the SAME post-processing pipeline as
1007
+ // the non-streaming route (strip, tool extraction, patch
1008
+ // application, persistence) on the FULL content. The
1009
+ // canonical text replaces any streamed approximation
1010
+ // client-side (converge-on-terminal semantics — the same
1011
+ // contract as OpenAI SSE clients).
1012
+ const processed = processChatReply(cres.content || '', [], bookData, bookId);
1013
+ finalReply = processed.replyText;
1014
+ terminalPayload = {
1015
+ reply: finalReply,
1016
+ tool_calls: processed.toolCalls,
1017
+ tool_results: processed.toolResults,
1018
+ patches_applied: processed.patches.length,
1019
+ validation_errors: processed.validationErrors,
1020
+ session_id: activeSessionId,
1021
+ ai_source: aiSource.value,
1022
+ finish_reason: cres.finishReason || 'stop',
1023
+ ...(cres.usage ? { usage: cres.usage } : {}),
1024
+ };
1025
+ await persistSuccessTurn(storedMessages, userContent, finalReply, processed.toolCalls);
1026
+ } else {
1027
+ // Cloud provider branch: the existing non-streaming
1028
+ // upstream call, re-emitted as ONE delta + terminal. No
1029
+ // second upstream protocol; cloud behavior unchanged.
1030
+ const controller = new AbortController();
1031
+ const onOuterAbort = () => controller.abort();
1032
+ abort.signal.addEventListener('abort', onOuterAbort, { once: true });
1033
+ const timeout = setTimeout(() => controller.abort(), clampStreamTimeoutMs(req.body?.timeout_ms));
1034
+ let response;
1035
+ try {
1036
+ response = await safeFetch(`${ai.baseUrl}/chat/completions`, {
1037
+ method: 'POST',
1038
+ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ai.apiKey}` },
1039
+ body: JSON.stringify({
1040
+ model: ai.model,
1041
+ messages: apiMessages,
1042
+ tools: tools.length > 0 ? tools : undefined,
1043
+ tool_choice: tools.length > 0 ? 'auto' : undefined,
1044
+ ...aiRequestBodyExtras(tools),
1045
+ }),
1046
+ signal: controller.signal,
1047
+ validatePublic: ai.validatePublic,
1048
+ });
1049
+ } finally {
1050
+ clearTimeout(timeout);
1051
+ abort.signal.removeEventListener('abort', onOuterAbort);
1052
+ }
1053
+
1054
+ if (!response.ok) {
1055
+ const errText = await response.text().catch(() => '');
1056
+ console.error('[AI STREAM] API error:', response.status, errText.substring(0, 200));
1057
+ const errorData = { error: `AI API error: ${response.status}`, code: 'upstream_error' };
1058
+ if (!clientGone) sendTerminal('error', errorData);
1059
+ await persistFailedTurn(`⚠️ ${errorData.error}`);
1060
+ return;
1061
+ }
1062
+ const aiResponse = await response.json();
1063
+ const aiMessage = aiResponse.choices?.[0]?.message;
1064
+ let replyText = aiMessage?.content || '';
1065
+ const processed = processChatReply(replyText, aiMessage?.tool_calls || [], bookData, bookId);
1066
+ finalReply = processed.replyText;
1067
+ if (finalReply && !clientGone) writeEvent('delta', { delta: finalReply });
1068
+ terminalPayload = {
1069
+ reply: finalReply,
1070
+ tool_calls: processed.toolCalls,
1071
+ tool_results: processed.toolResults,
1072
+ patches_applied: processed.patches.length,
1073
+ validation_errors: processed.validationErrors,
1074
+ session_id: activeSessionId,
1075
+ ai_source: aiSource.value,
1076
+ finish_reason: aiResponse.choices?.[0]?.finish_reason || 'stop',
1077
+ ...(aiResponse.usage ? { usage: aiResponse.usage } : {}),
1078
+ };
1079
+ await persistSuccessTurn(storedMessages, userContent, finalReply, processed.toolCalls);
1080
+ }
1081
+
1082
+ if (!clientGone) sendTerminal('done', terminalPayload);
1083
+ else persistFailedTurn(finalReply || '⚠️ Generation cancelled.').catch?.(() => {});
1084
+ } catch (err) {
1085
+ // Mid-stream failure → ONE safe terminal error. Client aborts
1086
+ // and dead sockets are not "errors" for the client (it is
1087
+ // gone) — the inference is already cancelled via the signal.
1088
+ const isAbort = err.name === 'AbortError' || err.code === 'ABORT_ERR';
1089
+ if (err.code === 'ENDPOINT_NOT_PUBLIC') {
1090
+ const errorData = { error: err.message, code: 'endpoint_not_allowed' };
1091
+ if (!clientGone) sendTerminal('error', errorData);
1092
+ await persistFailedTurn(`⚠️ ${errorData.error}`);
1093
+ } else if (isAbort && !clientGone) {
1094
+ const errorData = { error: 'AI не ответил за отведённое время. Попробуйте отправить более короткий запрос или повторить позже.', code: 'timeout' };
1095
+ sendTerminal('error', errorData);
1096
+ await persistFailedTurn(`⚠️ ${errorData.error}`);
1097
+ } else if (!clientGone) {
1098
+ const errorData = { error: 'AI streaming request failed.', code: 'stream_error' };
1099
+ sendTerminal('error', errorData);
1100
+ await persistFailedTurn(`⚠️ ${errorData.error}`);
1101
+ } else if (isAbort) {
1102
+ await persistFailedTurn(finalReply || '⚠️ Generation cancelled.');
1103
+ }
1104
+ } finally {
1105
+ if (heartbeat) { clearInterval(heartbeat); heartbeat = null; }
1106
+ res.removeListener('close', onConnClosed);
1107
+ streamFinished = true;
1108
+ }
1109
+ return;
1110
+ } catch (err) {
1111
+ // Pre-flight failure AFTER the SSE headers went out must still
1112
+ // honor the terminal contract; before that, plain JSON errors
1113
+ // apply (handled by the returns above).
1114
+ console.error('[AI STREAM] Error:', err.message);
1115
+ if (terminalSent || res.headersSent) {
1116
+ sendTerminal('error', { error: 'AI streaming request failed.', code: 'stream_error' });
1117
+ return;
1118
+ }
1119
+ if (err.code === 'ENDPOINT_NOT_PUBLIC') {
1120
+ return res.status(502).json({ error: err.message });
1121
+ }
1122
+ res.status(500).json({ error: err.message });
1123
+ }
1124
+
1125
+ // ── local helpers (per-request) ──
1126
+ // Persist a successful turn: identical merge semantics to the
1127
+ // non-streaming route (full stored history + user + assistant).
1128
+ async function persistSuccessTurn(prevMessages, userText, replyText, toolCalls) {
1129
+ try {
1130
+ const updatedMessages = [
1131
+ ...prevMessages,
1132
+ ...(userText ? [{ role: 'user', content: userText, timestamp: Date.now() }] : []),
1133
+ { role: 'assistant', content: replyText, tool_calls: toolCalls || [], timestamp: Date.now() },
1134
+ ];
1135
+ await sessionRepo.setMessages(activeSessionId, updatedMessages);
1136
+ } catch (persistErr) {
1137
+ console.error('[AI STREAM] Failed to persist turn:', persistErr.message);
1138
+ }
1139
+ }
1140
+ });
1141
+
1142
+ // Reply post-processing shared by both branches of the stream route:
1143
+ // the exact strip/extract/apply pipeline of the non-streaming chat route
1144
+ // (think blocks, tool_call remnants, content-embedded tool calls, patch
1145
+ // application with validation, and the honest no-result fallback).
1146
+ function processChatReply(rawContent, structuredToolCalls, bookData, bookId) {
1147
+ let replyText = rawContent || '';
1148
+ replyText = replyText.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
1149
+ replyText = replyText.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
1150
+ replyText = replyText.replace(/<\/?tool_call[^>]*>/gi, '').trim();
1151
+ replyText = replyText.replace(/tool_call[^>]*>/gi, '').trim();
1152
+ replyText = replyText.replace(/\/?tool_call\b/gi, '').trim();
1153
+ replyText = replyText.replace(/[a-z]*_call[^>]*>/gi, '').trim();
1154
+
1155
+ let contentToolCalls = [];
1156
+ if ((structuredToolCalls || []).length === 0) {
1157
+ const result = extractToolCallsFromContent(replyText);
1158
+ contentToolCalls = result.toolCalls;
1159
+ replyText = result.cleanedContent;
1160
+ }
1161
+ if (replyText && replyText.length < 30 && (!/[\w\u0400-\u04FF]{3,}/.test(replyText) || /_call/i.test(replyText))) {
1162
+ replyText = '';
1163
+ }
1164
+ const toolCalls = [...contentToolCalls, ...(structuredToolCalls || [])];
1165
+
1166
+ let patches = [];
1167
+ const toolResults = [];
1168
+ let lastEditError = null;
1169
+
1170
+ if (toolCalls.length > 0) {
1171
+ for (const tc of toolCalls) {
1172
+ if (tc.function.name === 'edit_book') {
1173
+ try {
1174
+ const args = JSON.parse(tc.function.arguments);
1175
+ const patchResult = chatEngine.applyPatchesValidated(bookData, args.patches || []);
1176
+ if (patchResult.errors.length > 0) {
1177
+ const errMsg = patchResult.errors.join('; ');
1178
+ toolResults.push({ tool: 'edit_book', error: errMsg, validation_errors: patchResult.validation_errors });
1179
+ lastEditError = errMsg;
1180
+ } else {
1181
+ patches = args.patches || [];
1182
+ toolResults.push({ tool: 'edit_book', applied: patches.length, book_id: bookId });
1183
+ }
1184
+ } catch (parseErr) {
1185
+ toolResults.push({ tool: 'edit_book', error: parseErr.message });
1186
+ lastEditError = parseErr.message;
1187
+ }
1188
+ } else {
1189
+ toolResults.push({ tool: tc.function.name, result: 'Tool executed (no handler)' });
1190
+ }
1191
+ }
1192
+ }
1193
+
1194
+ if (patches.length > 0 && bookData) {
1195
+ try {
1196
+ const patchResult = chatEngine.applyPatchesValidated(bookData, patches);
1197
+ if (patchResult.errors.length > 0) {
1198
+ if (!lastEditError) lastEditError = patchResult.errors.join('; ');
1199
+ patches = [];
1200
+ toolResults.push({ tool: 'edit_book', error: lastEditError, validation_errors: patchResult.validation_errors, rejected: true });
1201
+ } else if (patchResult.result) {
1202
+ // ONE save semantics through the AssistantPorts seam (the
1203
+ // same persistBook as the non-streaming route — no
1204
+ // duplicated targeted-save fallback).
1205
+ persistBook(bookId, patchResult.result);
1206
+ log('[AI STREAM] Book updated (via persistBook):', patches.length, 'patches applied to', bookId);
1207
+ }
1208
+ } catch (saveErr) {
1209
+ console.error('[AI STREAM] Failed to save updated book:', saveErr.message);
1210
+ if (!lastEditError) lastEditError = saveErr.message;
1211
+ patches = [];
1212
+ }
1213
+ }
1214
+
1215
+ if (!replyText && toolCalls.length > 0) {
1216
+ if (lastEditError) {
1217
+ replyText = `⚠️ Edit error: ${lastEditError}`;
1218
+ } else if (patches.length > 0) {
1219
+ replyText = `✅ Changes applied: ${patches.length} patch(es) to the book.`;
1220
+ } else {
1221
+ replyText = `🤖 Processed ${toolCalls.length} tool call(s).`;
1222
+ }
1223
+ }
1224
+ if (!replyText && toolCalls.length === 0) {
1225
+ replyText = '⚠️ The assistant returned no result. Please try again.';
1226
+ }
1227
+
1228
+ const validationErrors = toolResults.flatMap(tr => tr.validation_errors || []);
1229
+ return { replyText, toolCalls, toolResults, patches, validationErrors };
1230
+ }
1231
+
1232
+ log('[ROUTES] AI routes loaded');
1233
+ };