@animastor/assistant 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.1 (2026-11-22, unpublished)
4
+
5
+ Honest edit turns (animastor-docs `CHANGELOG.md` 2026-11-22;
6
+ reports/2026-11-22/assistant-edit-bug.md). The assistant answered "Done. I've
7
+ added … as Scene 2" while nothing was saved: the model never called
8
+ `edit_book`, and the routes relayed its text as is.
9
+
10
+ - Book context is a **read-only snapshot**: the header no longer asks the model
11
+ to "return the full changed version in your response"; in an edit turn it
12
+ points at `edit_book`, otherwise it says the book cannot be changed in this
13
+ mode (`buildBookContext(book, { canEdit })`, `buildCompactBookContext` too).
14
+ - Edit-mode prompt: call `edit_book` in the same turn (no "always confirm
15
+ first"), never claim a change without the call; paths of chapters / scenes /
16
+ units (`add /chapters/<i>/scenes/-`, unit fields `text`, `audio`, `image`,
17
+ `video.action`).
18
+ - One reply pipeline for both chat routes (`processChatReply`) with
19
+ `edit_outcome`: `applied` | `rejected` | `claimed_not_applied` | `none` —
20
+ new additive field of the `/ai/chat` response and of the SSE `done` frame.
21
+ A rejected or unsaved edit replaces the model's text with
22
+ "⚠️ The book was NOT changed: <reason>"; a claim without the tool call
23
+ (`looksLikeChangeClaim`: "Done", "I've added", "Готово", "добавил…", a
24
+ pasted book JSON) gets ONE corrective retry on cloud providers, then
25
+ "⚠️ The book was NOT changed …".
26
+ - Several `edit_book` calls in one turn apply cumulatively and are saved once.
27
+ - `edit_book` outside an edit-capable turn (other mode, locked book) is
28
+ refused — a content-embedded call was applied in any mode before.
29
+ - A scene / unit added without ids gets `sc-`/`iu-` + 8 hex
30
+ (`assignMissingIds`, inside `applyPatchesValidated`); `participants`
31
+ defaults to `[]`.
32
+ - Empty reply with `finish_reason=length` says the budget ran out.
33
+ - One diagnostic log line per turn (`turn session=… edit=… patches=…`, no
34
+ prompt/reply text) and the reason of a not-applied edit.
35
+
3
36
  ## 0.3.0 (2026-11-18, unpublished)
4
37
 
5
38
  VBook 4 step 4 (animastor-docs `architecture/VBOOK_FORMAT_V4.md` §8.2). **Breaking.**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@animastor/assistant",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Animastor Assistant — the AI assistant contour of the Animastor backend, physically extracted from the host: chat engine (persona/system prompts, book context, mode tools, JSON patch pipeline with bundle-contract validation), the /api/v1/ai/* HTTP contour (sessions CRUD, non-streaming chat, SSE streaming with meta/delta/done/error frames, tool-call orchestration) and the chat-session repository contract. The package reaches the host (book read/write, bundle validation, provider resolution, session persistence, shared-inference transport, logging) ONLY through the injected AssistantPorts seam — no PG, no Book internals, no filesystem, no provider gateway inside.",
5
5
  "keywords": [
6
6
  "animastor",
@@ -386,7 +386,8 @@ module.exports = function(app, redis, deps) {
386
386
 
387
387
  }
388
388
 
389
- const bookContext = chatEngine.buildBookContext(bookData);
389
+ const canEdit = tools.length > 0;
390
+ const bookContext = chatEngine.buildBookContext(bookData, { canEdit });
390
391
  if (bookContext) {
391
392
  // Connector per-message cap is 32 KB (ai-connector
392
393
  // lib/chat.cjs maxMessageChars, mirrored by the transport) —
@@ -396,7 +397,7 @@ module.exports = function(app, redis, deps) {
396
397
  const withinConnectorBudget = bookContext.length <= CONNECTOR_BOOK_CONTEXT_BUDGET;
397
398
  systemPrompt += '\n\n' + (ai.transport !== 'connector' || withinConnectorBudget
398
399
  ? bookContext
399
- : chatEngine.buildCompactBookContext(bookData));
400
+ : chatEngine.buildCompactBookContext(bookData, { canEdit }));
400
401
  }
401
402
 
402
403
  // Build API messages for AI call
@@ -421,6 +422,8 @@ module.exports = function(app, redis, deps) {
421
422
  }
422
423
 
423
424
  let aiResponse;
425
+ let processed = null;
426
+ let retried = false;
424
427
  if (ai.transport === 'connector') {
425
428
  // Local AI Connector path (LAC §9): the completion rides the
426
429
  // connector's authenticated WS session — no server-side URL,
@@ -481,141 +484,34 @@ module.exports = function(app, redis, deps) {
481
484
  // or owner detail rides the API response.
482
485
  aiSource = ai.source === 'shared' ? 'shared' : 'private-local';
483
486
  } else {
484
- const controller = new AbortController();
485
- const timeout = setTimeout(() => controller.abort(), AI_FETCH_TIMEOUT_MS);
486
- const { response, errText } = await fetchChatCompletion(safeFetch, `${ai.baseUrl}/chat/completions`, {
487
- method: 'POST',
488
- headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ai.apiKey}` },
489
- signal: controller.signal,
490
- validatePublic: ai.validatePublic,
491
- }, {
492
- model: ai.model,
493
- messages: apiMessages,
494
- tools: tools.length > 0 ? tools : undefined,
495
- tool_choice: tools.length > 0 ? 'auto' : undefined,
496
- ...chatEngine.chatRequestExtras({ model: ai.model, baseUrl: ai.baseUrl, tools }, ai),
487
+ // Cloud provider: the edit turn (with the one corrective
488
+ // retry when the model claimed a change without calling
489
+ // edit_book) — shared with the stream route.
490
+ const turn = await runCloudTurn(ai, apiMessages, tools, bookData, bookId, {
491
+ canEdit, logTag: '[AI]', timeoutMs: AI_FETCH_TIMEOUT_MS,
497
492
  });
498
- clearTimeout(timeout);
499
-
500
- if (!response.ok) {
501
- const upstreamError = describeUpstreamError(response.status, errText); // key-masked
493
+ if (turn.error) {
494
+ const upstreamError = describeUpstreamError(turn.error.status, turn.error.errText); // key-masked
502
495
  console.error('[AI]', upstreamError);
503
496
  return res.status(502).json({ error: upstreamError, code: 'upstream_error' });
504
497
  }
505
-
506
- aiResponse = await response.json();
507
- }
508
- const aiMessage = aiResponse.choices?.[0]?.message;
509
- let replyText = aiMessage?.content || '';
510
- // Strip AI chain-of-thought reasoning blocks — internal, not for the UI
511
- replyText = replyText.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
512
- // Strip tool_call & tool_call markers that some models leak into content
513
- replyText = replyText.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
514
- replyText = replyText.replace(/<\/?tool_call[^>]*>/gi, '').trim();
515
- // Also strip partial tool_call remnants without the opening '<' (e.g. 'tool_call>')
516
- replyText = replyText.replace(/tool_call[^>]*>/gi, '').trim();
517
- replyText = replyText.replace(/\/?tool_call\b/gi, '').trim();
518
- // Catch any remaining tool_call-like fragments where leading chars may be missing
519
- // (e.g. 'ool_call>' — Qwen3 sometimes outputs partial tag remnants)
520
- replyText = replyText.replace(/[a-z]*_call[^>]*>/gi, '').trim();
521
- // Only extract tool calls from content if model didn't return structured tool_calls
522
- // (avoids duplicates — Qwen3 sometimes puts tool_call JSON in both places)
523
- const structuredToolCalls = aiMessage?.tool_calls || [];
524
- let contentToolCalls = [];
525
- if (structuredToolCalls.length === 0) {
526
- const result = extractToolCallsFromContent(replyText);
527
- contentToolCalls = result.toolCalls;
528
- replyText = result.cleanedContent;
498
+ processed = turn.processed;
499
+ retried = turn.retried;
500
+ aiResponse = turn.aiResponse;
529
501
  }
530
- // If after stripping, the reply is just garbage remnants (e.g. 'ool_call>', 'tool_call>'),
531
- // treat as empty so the fallback message below kicks in.
532
- // A remnant is considered garbage if:
533
- // - it has no real word of 3+ letters, OR
534
- // - it contains '_call' (a tool_call-like fragment)
535
- if (replyText && replyText.length < 30 && (!/[\w\u0400-\u04FF]{3,}/.test(replyText) || /_call/i.test(replyText))) {
536
- replyText = '';
537
- }
538
- const toolCalls = [...contentToolCalls, ...structuredToolCalls];
539
-
540
- // Handle tool calls
541
- let patches = [];
542
- let toolResults = [];
543
- let lastEditError = null;
544
-
545
- if (toolCalls.length > 0) {
546
- for (const tc of toolCalls) {
547
- if (tc.function.name === 'edit_book') {
548
- try {
549
- const args = JSON.parse(tc.function.arguments);
550
- // Validated application: patch → contract validation →
551
- // result. A structurally broken result (e.g. voices.json
552
- // becoming a string instead of an object) is rejected
553
- // here and never reaches the save block below.
554
- const patchResult = chatEngine.applyPatchesValidated(bookData, args.patches || []);
555
- if (patchResult.errors.length > 0) {
556
- const errMsg = patchResult.errors.join('; ');
557
- toolResults.push({ tool: 'edit_book', error: errMsg, validation_errors: patchResult.validation_errors });
558
- lastEditError = errMsg;
559
- } else {
560
- patches = args.patches || [];
561
- toolResults.push({ tool: 'edit_book', applied: patches.length, book_id: bookId });
562
- }
563
- } catch (parseErr) {
564
- toolResults.push({ tool: 'edit_book', error: parseErr.message });
565
- lastEditError = parseErr.message;
566
- }
567
- } else {
568
- toolResults.push({ tool: tc.function.name, result: 'Tool executed (no handler)' });
569
- }
570
- }
571
- }
572
-
573
- // Save patches if any were applied
574
- if (patches.length > 0 && bookData) {
575
- try {
576
- // Re-apply with validation (defense in depth): the save block
577
- // is the last gate before disk — an invalid candidate state
578
- // must never be written and must not be reported as applied.
579
- const patchResult = chatEngine.applyPatchesValidated(bookData, patches);
580
- if (patchResult.errors.length > 0) {
581
- // Reject the whole mutation: keep previous canonical state,
582
- // report the failure to the assistant/user, apply nothing.
583
- if (!lastEditError) lastEditError = patchResult.errors.join('; ');
584
- patches = [];
585
- toolResults.push({ tool: 'edit_book', error: lastEditError, validation_errors: patchResult.validation_errors, rejected: true });
586
- } else if (patchResult.result) {
587
- // ONE save semantics through the AssistantPorts seam:
588
- // full bundle save when chapters are intact, targeted
589
- // file save (chapters skipped) on a corrupted load.
590
- persistBook(bookId, patchResult.result);
591
- log('[AI] Book updated (via persistBook):', patches.length, 'patches applied to', bookId);
592
- }
593
- } catch (saveErr) {
594
- console.error('[AI] Failed to save updated book:', saveErr.message);
595
- if (!lastEditError) lastEditError = saveErr.message;
596
- // Nothing was persisted — do not report success.
597
- patches = [];
598
- }
599
- }
600
-
601
- // Build a user-visible reply when the AI returned empty content but tool calls were processed
602
- if (!replyText && toolCalls.length > 0) {
603
- if (lastEditError) {
604
- replyText = `⚠️ Edit error: ${lastEditError}`;
605
- } else if (patches.length > 0) {
606
- replyText = `✅ Changes applied: ${patches.length} patch(es) to the book.`;
607
- } else {
608
- replyText = `🤖 Processed ${toolCalls.length} tool call(s).`;
609
- }
610
- }
611
-
612
- // No content AND no tool calls — the model produced nothing usable
613
- // (e.g. a reasoning model burned the whole max_tokens budget on
614
- // reasoning). Report it honestly instead of returning an empty
615
- // reply that UIs render as a fake "tool executed" message.
616
- if (!replyText && toolCalls.length === 0) {
617
- replyText = '⚠️ The assistant returned no result. Please try again.';
502
+ if (!processed) {
503
+ // Connector reply: no structured tool_calls (Phase-4 contract) —
504
+ // content-embedded tool calls are extracted by processChatReply.
505
+ const aiMessage = aiResponse.choices?.[0]?.message;
506
+ processed = processChatReply(aiMessage?.content || '', aiMessage?.tool_calls || [], bookData, bookId, {
507
+ canEdit, logTag: '[AI]', finishReason: aiResponse.choices?.[0]?.finish_reason || null,
508
+ });
618
509
  }
510
+ logTurn('[AI]', {
511
+ sessionId: activeSessionId, mode: sessionMode, ai, processed, retried,
512
+ finishReason: aiResponse?.choices?.[0]?.finish_reason || null,
513
+ });
514
+ const { replyText, toolCalls, toolResults, patches, validationErrors, editOutcome } = processed;
619
515
 
620
516
  // Update session messages: merge with stored history
621
517
  const updatedMessages = [
@@ -630,15 +526,13 @@ module.exports = function(app, redis, deps) {
630
526
  // file/resource that failed the bundle contract, so a corrective
631
527
  // patch ("почини voices.json") lands in the very next turn —
632
528
  // the error reply is stored in session history for that purpose.
633
- const validationErrors = toolResults
634
- .flatMap(tr => tr.validation_errors || []);
635
-
636
529
  res.json({
637
530
  reply: replyText,
638
531
  tool_calls: toolCalls,
639
532
  tool_results: toolResults,
640
533
  patches_applied: patches.length,
641
534
  validation_errors: validationErrors,
535
+ edit_outcome: editOutcome,
642
536
  session_id: activeSessionId,
643
537
  ai_source: aiSource || (ai.source === 'workspace' ? 'cloud' : (ai.source === 'system' ? 'system' : ai.source)),
644
538
  });
@@ -869,14 +763,15 @@ module.exports = function(app, redis, deps) {
869
763
  });
870
764
  }
871
765
 
872
- const bookContext = chatEngine.buildBookContext(bookData);
766
+ const canEdit = tools.length > 0;
767
+ const bookContext = chatEngine.buildBookContext(bookData, { canEdit });
873
768
  if (bookContext) {
874
769
  // Same connector per-message cap as the non-streaming route —
875
770
  // oversized book JSON falls back to the compact summary.
876
771
  const withinConnectorBudget = bookContext.length <= CONNECTOR_BOOK_CONTEXT_BUDGET;
877
772
  systemPrompt += '\n\n' + (ai.transport !== 'connector' || withinConnectorBudget
878
773
  ? bookContext
879
- : chatEngine.buildCompactBookContext(bookData));
774
+ : chatEngine.buildCompactBookContext(bookData, { canEdit }));
880
775
  }
881
776
 
882
777
  let apiMessages;
@@ -997,7 +892,13 @@ module.exports = function(app, redis, deps) {
997
892
  // canonical text replaces any streamed approximation
998
893
  // client-side (converge-on-terminal semantics — the same
999
894
  // contract as OpenAI SSE clients).
1000
- const processed = processChatReply(cres.content || '', [], bookData, bookId);
895
+ const processed = processChatReply(cres.content || '', [], bookData, bookId, {
896
+ canEdit, logTag: '[AI STREAM]', finishReason: cres.finishReason || null,
897
+ });
898
+ logTurn('[AI STREAM]', {
899
+ sessionId: activeSessionId, mode: sessionMode, ai, processed, retried: false,
900
+ finishReason: cres.finishReason || null,
901
+ });
1001
902
  finalReply = processed.replyText;
1002
903
  terminalPayload = {
1003
904
  reply: finalReply,
@@ -1005,6 +906,7 @@ module.exports = function(app, redis, deps) {
1005
906
  tool_results: processed.toolResults,
1006
907
  patches_applied: processed.patches.length,
1007
908
  validation_errors: processed.validationErrors,
909
+ edit_outcome: processed.editOutcome,
1008
910
  session_id: activeSessionId,
1009
911
  ai_source: aiSource.value,
1010
912
  finish_reason: cres.finishReason || 'stop',
@@ -1014,41 +916,27 @@ module.exports = function(app, redis, deps) {
1014
916
  } else {
1015
917
  // Cloud provider branch: the existing non-streaming
1016
918
  // upstream call, re-emitted as ONE delta + terminal. No
1017
- // second upstream protocol; cloud behavior unchanged.
1018
- const controller = new AbortController();
1019
- const onOuterAbort = () => controller.abort();
1020
- abort.signal.addEventListener('abort', onOuterAbort, { once: true });
1021
- const timeout = setTimeout(() => controller.abort(), clampStreamTimeoutMs(req.body?.timeout_ms));
1022
- let response, errText;
1023
- try {
1024
- ({ response, errText } = await fetchChatCompletion(safeFetch, `${ai.baseUrl}/chat/completions`, {
1025
- method: 'POST',
1026
- headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ai.apiKey}` },
1027
- signal: controller.signal,
1028
- validatePublic: ai.validatePublic,
1029
- }, {
1030
- model: ai.model,
1031
- messages: apiMessages,
1032
- tools: tools.length > 0 ? tools : undefined,
1033
- tool_choice: tools.length > 0 ? 'auto' : undefined,
1034
- ...chatEngine.chatRequestExtras({ model: ai.model, baseUrl: ai.baseUrl, tools }, ai),
1035
- }));
1036
- } finally {
1037
- clearTimeout(timeout);
1038
- abort.signal.removeEventListener('abort', onOuterAbort);
1039
- }
1040
-
1041
- if (!response.ok) {
1042
- const errorData = { error: describeUpstreamError(response.status, errText), code: 'upstream_error' }; // key-masked
919
+ // second upstream protocol; cloud behavior unchanged —
920
+ // except the one corrective retry of an edit turn whose
921
+ // reply claimed a change without calling edit_book.
922
+ const turn = await runCloudTurn(ai, apiMessages, tools, bookData, bookId, {
923
+ canEdit, logTag: '[AI STREAM]',
924
+ timeoutMs: clampStreamTimeoutMs(req.body?.timeout_ms),
925
+ signal: abort.signal,
926
+ });
927
+ if (turn.error) {
928
+ const errorData = { error: describeUpstreamError(turn.error.status, turn.error.errText), code: 'upstream_error' }; // key-masked
1043
929
  console.error('[AI STREAM]', errorData.error);
1044
930
  if (!clientGone) sendTerminal('error', errorData);
1045
931
  await persistFailedTurn(`⚠️ ${errorData.error}`);
1046
932
  return;
1047
933
  }
1048
- const aiResponse = await response.json();
1049
- const aiMessage = aiResponse.choices?.[0]?.message;
1050
- let replyText = aiMessage?.content || '';
1051
- const processed = processChatReply(replyText, aiMessage?.tool_calls || [], bookData, bookId);
934
+ const aiResponse = turn.aiResponse;
935
+ const processed = turn.processed;
936
+ logTurn('[AI STREAM]', {
937
+ sessionId: activeSessionId, mode: sessionMode, ai, processed, retried: turn.retried,
938
+ finishReason: aiResponse.choices?.[0]?.finish_reason || null,
939
+ });
1052
940
  finalReply = processed.replyText;
1053
941
  if (finalReply && !clientGone) writeEvent('delta', { delta: finalReply });
1054
942
  terminalPayload = {
@@ -1057,6 +945,7 @@ module.exports = function(app, redis, deps) {
1057
945
  tool_results: processed.toolResults,
1058
946
  patches_applied: processed.patches.length,
1059
947
  validation_errors: processed.validationErrors,
948
+ edit_outcome: processed.editOutcome,
1060
949
  session_id: activeSessionId,
1061
950
  ai_source: aiSource.value,
1062
951
  finish_reason: aiResponse.choices?.[0]?.finish_reason || 'stop',
@@ -1125,11 +1014,29 @@ module.exports = function(app, redis, deps) {
1125
1014
  }
1126
1015
  });
1127
1016
 
1128
- // Reply post-processing shared by both branches of the stream route:
1129
- // the exact strip/extract/apply pipeline of the non-streaming chat route
1130
- // (think blocks, tool_call remnants, content-embedded tool calls, patch
1131
- // application with validation, and the honest no-result fallback).
1132
- function processChatReply(rawContent, structuredToolCalls, bookData, bookId) {
1017
+ // Reply post-processing shared by BOTH chat routes (non-streaming and
1018
+ // stream, every transport): think blocks, tool_call remnants,
1019
+ // content-embedded tool calls, edit_book application with validation,
1020
+ // ONE save through persistBook, and the honest reply.
1021
+ //
1022
+ // Honest edit outcome (0.3.1, reports/2026-11-22/assistant-edit-bug.md):
1023
+ // the user-visible reply never says a change happened unless it was
1024
+ // saved. editOutcome:
1025
+ // 'applied' — patches validated AND persisted;
1026
+ // 'rejected' — edit_book was called, nothing was saved
1027
+ // (path guard, contract validation, save error);
1028
+ // the model's own text (often "Done") is
1029
+ // replaced by the error;
1030
+ // 'claimed_not_applied' — edit_book was offered, NOT called, and the
1031
+ // reply claims a change / pastes a changed JSON;
1032
+ // the reply is replaced by "NOT changed";
1033
+ // 'none' — no edit involved.
1034
+ // edit_book outside an edit-capable turn (other mode, locked book) is
1035
+ // refused — before 0.3.1 a content-embedded call was applied in any mode.
1036
+ function processChatReply(rawContent, structuredToolCalls, bookData, bookId, opts = {}) {
1037
+ const canEdit = opts.canEdit === true;
1038
+ const logTag = opts.logTag || '[AI]';
1039
+ const finishReason = opts.finishReason || null;
1133
1040
  let replyText = rawContent || '';
1134
1041
  replyText = replyText.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
1135
1042
  replyText = replyText.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
@@ -1138,81 +1045,200 @@ module.exports = function(app, redis, deps) {
1138
1045
  replyText = replyText.replace(/\/?tool_call\b/gi, '').trim();
1139
1046
  replyText = replyText.replace(/[a-z]*_call[^>]*>/gi, '').trim();
1140
1047
 
1048
+ // Only extract tool calls from content if the model didn't return
1049
+ // structured tool_calls (Qwen3 sometimes puts them in both places).
1141
1050
  let contentToolCalls = [];
1142
1051
  if ((structuredToolCalls || []).length === 0) {
1143
1052
  const result = extractToolCallsFromContent(replyText);
1144
1053
  contentToolCalls = result.toolCalls;
1145
1054
  replyText = result.cleanedContent;
1146
1055
  }
1147
- if (replyText && replyText.length < 30 && (!/[\w\u0400-\u04FF]{3,}/.test(replyText) || /_call/i.test(replyText))) {
1056
+ // Garbage remnants ('ool_call>' …) count as an empty reply.
1057
+ if (replyText && replyText.length < 30 && (!/[\wЀ-ӿ]{3,}/.test(replyText) || /_call/i.test(replyText))) {
1148
1058
  replyText = '';
1149
1059
  }
1150
1060
  const toolCalls = [...contentToolCalls, ...(structuredToolCalls || [])];
1151
1061
 
1152
- let patches = [];
1153
1062
  const toolResults = [];
1154
- let lastEditError = null;
1155
-
1156
- if (toolCalls.length > 0) {
1157
- for (const tc of toolCalls) {
1158
- if (tc.function.name === 'edit_book') {
1159
- try {
1160
- const args = JSON.parse(tc.function.arguments);
1161
- const patchResult = chatEngine.applyPatchesValidated(bookData, args.patches || []);
1162
- if (patchResult.errors.length > 0) {
1163
- const errMsg = patchResult.errors.join('; ');
1164
- toolResults.push({ tool: 'edit_book', error: errMsg, validation_errors: patchResult.validation_errors });
1165
- lastEditError = errMsg;
1063
+ const editErrors = [];
1064
+ const appliedPatches = [];
1065
+ let editCalled = false;
1066
+ // Every edit_book call of the turn applies on top of the previous
1067
+ // one (cumulative), validated each time; the book is saved ONCE.
1068
+ let workingBook = bookData;
1069
+
1070
+ for (const tc of toolCalls) {
1071
+ const name = tc && tc.function && tc.function.name;
1072
+ if (name !== 'edit_book') {
1073
+ toolResults.push({ tool: name, result: 'Tool executed (no handler)' });
1074
+ continue;
1075
+ }
1076
+ editCalled = true;
1077
+ let err = null;
1078
+ let validationErrors = [];
1079
+ if (!canEdit) {
1080
+ err = 'the book cannot be changed in this mode (switch to the Edit mode; a locked book cannot be edited)';
1081
+ } else if (!bookData) {
1082
+ err = 'the book could not be loaded';
1083
+ } else {
1084
+ try {
1085
+ const rawArgs = tc.function.arguments;
1086
+ const args = typeof rawArgs === 'string' ? JSON.parse(rawArgs || '{}') : (rawArgs || {});
1087
+ const list = Array.isArray(args.patches) ? args.patches : [];
1088
+ if (list.length === 0) {
1089
+ err = 'edit_book was called without patches';
1090
+ } else {
1091
+ const patchResult = chatEngine.applyPatchesValidated(workingBook, list);
1092
+ if (patchResult.errors.length > 0 || !patchResult.result) {
1093
+ err = patchResult.errors.join('; ') || 'the patches were rejected';
1094
+ validationErrors = patchResult.validation_errors || [];
1166
1095
  } else {
1167
- patches = args.patches || [];
1168
- toolResults.push({ tool: 'edit_book', applied: patches.length, book_id: bookId });
1096
+ workingBook = patchResult.result;
1097
+ appliedPatches.push(...list);
1098
+ toolResults.push({ tool: 'edit_book', applied: list.length, book_id: bookId });
1169
1099
  }
1170
- } catch (parseErr) {
1171
- toolResults.push({ tool: 'edit_book', error: parseErr.message });
1172
- lastEditError = parseErr.message;
1173
1100
  }
1174
- } else {
1175
- toolResults.push({ tool: tc.function.name, result: 'Tool executed (no handler)' });
1101
+ } catch (parseErr) {
1102
+ err = `invalid edit_book arguments: ${parseErr.message}`;
1176
1103
  }
1177
1104
  }
1105
+ if (err) {
1106
+ editErrors.push(err);
1107
+ toolResults.push({ tool: 'edit_book', error: err, validation_errors: validationErrors });
1108
+ }
1178
1109
  }
1179
1110
 
1180
- if (patches.length > 0 && bookData) {
1111
+ // ONE save through the AssistantPorts seam (full bundle save when the
1112
+ // chapters are intact, targeted file save on a corrupted load).
1113
+ let patches = [];
1114
+ if (appliedPatches.length > 0) {
1181
1115
  try {
1182
- const patchResult = chatEngine.applyPatchesValidated(bookData, patches);
1183
- if (patchResult.errors.length > 0) {
1184
- if (!lastEditError) lastEditError = patchResult.errors.join('; ');
1185
- patches = [];
1186
- toolResults.push({ tool: 'edit_book', error: lastEditError, validation_errors: patchResult.validation_errors, rejected: true });
1187
- } else if (patchResult.result) {
1188
- // ONE save semantics through the AssistantPorts seam (the
1189
- // same persistBook as the non-streaming route — no
1190
- // duplicated targeted-save fallback).
1191
- persistBook(bookId, patchResult.result);
1192
- log('[AI STREAM] Book updated (via persistBook):', patches.length, 'patches applied to', bookId);
1193
- }
1116
+ persistBook(bookId, workingBook);
1117
+ patches = appliedPatches;
1118
+ log(`${logTag} Book updated (via persistBook):`, patches.length, 'patches applied to', bookId);
1194
1119
  } catch (saveErr) {
1195
- console.error('[AI STREAM] Failed to save updated book:', saveErr.message);
1196
- if (!lastEditError) lastEditError = saveErr.message;
1197
- patches = [];
1120
+ console.error(`${logTag} Failed to save updated book:`, saveErr.message);
1121
+ const err = `the book could not be saved: ${saveErr.message}`;
1122
+ editErrors.push(err);
1123
+ toolResults.push({ tool: 'edit_book', error: err, rejected: true });
1198
1124
  }
1199
1125
  }
1200
1126
 
1201
- if (!replyText && toolCalls.length > 0) {
1202
- if (lastEditError) {
1203
- replyText = `⚠️ Edit error: ${lastEditError}`;
1204
- } else if (patches.length > 0) {
1205
- replyText = `✅ Changes applied: ${patches.length} patch(es) to the book.`;
1206
- } else {
1207
- replyText = `🤖 Processed ${toolCalls.length} tool call(s).`;
1208
- }
1209
- }
1210
- if (!replyText && toolCalls.length === 0) {
1211
- replyText = '⚠️ The assistant returned no result. Please try again.';
1127
+ let editOutcome = 'none';
1128
+ if (patches.length > 0) editOutcome = 'applied';
1129
+ else if (editCalled) editOutcome = 'rejected';
1130
+ else if (canEdit && chatEngine.looksLikeChangeClaim(replyText)) editOutcome = 'claimed_not_applied';
1131
+
1132
+ if (editOutcome === 'applied') {
1133
+ if (!replyText) replyText = `✅ Changes applied: ${patches.length} change(s) to the book.`;
1134
+ if (editErrors.length > 0) replyText += `\n\n⚠️ Some changes were NOT applied: ${editErrors.join('; ')}`;
1135
+ } else if (editOutcome === 'rejected') {
1136
+ replyText = `⚠️ The book was NOT changed: ${editErrors.join('; ')}`;
1137
+ } else if (editOutcome === 'claimed_not_applied') {
1138
+ replyText = '⚠️ The book was NOT changed: the assistant described the edit but did not apply it. Please repeat the request.';
1139
+ } else if (!replyText && toolCalls.length > 0) {
1140
+ replyText = `🤖 Processed ${toolCalls.length} tool call(s).`;
1141
+ } else if (!replyText) {
1142
+ // No content AND no tool calls. finish_reason=length: a reasoning
1143
+ // model spent the whole budget before answering.
1144
+ replyText = finishReason === 'length'
1145
+ ? '⚠️ The assistant ran out of its answer budget before replying — nothing was changed. Please try again or shorten the request.'
1146
+ : '⚠️ The assistant returned no result. Please try again.';
1212
1147
  }
1213
1148
 
1214
1149
  const validationErrors = toolResults.flatMap(tr => tr.validation_errors || []);
1215
- return { replyText, toolCalls, toolResults, patches, validationErrors };
1150
+ return { replyText, toolCalls, toolResults, patches, validationErrors, editOutcome, editErrors };
1151
+ }
1152
+
1153
+ // One cloud /chat/completions call (SSRF-guarded fetch, the provider's
1154
+ // body extras, the one-shot "Unsupported parameter" retry). Returns
1155
+ // { ok:true, aiResponse } or { ok:false, status, errText }; aborts
1156
+ // (timeout / outer signal) throw AbortError as before.
1157
+ async function cloudChatCompletion(ai, messages, tools, { timeoutMs, signal } = {}) {
1158
+ const controller = new AbortController();
1159
+ const onOuterAbort = () => controller.abort();
1160
+ if (signal) {
1161
+ if (signal.aborted) controller.abort();
1162
+ else signal.addEventListener('abort', onOuterAbort, { once: true });
1163
+ }
1164
+ const timeout = setTimeout(() => controller.abort(), timeoutMs || AI_FETCH_TIMEOUT_MS);
1165
+ try {
1166
+ const { response, errText } = await fetchChatCompletion(safeFetch, `${ai.baseUrl}/chat/completions`, {
1167
+ method: 'POST',
1168
+ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ai.apiKey}` },
1169
+ signal: controller.signal,
1170
+ validatePublic: ai.validatePublic,
1171
+ }, {
1172
+ model: ai.model,
1173
+ messages,
1174
+ tools: tools.length > 0 ? tools : undefined,
1175
+ tool_choice: tools.length > 0 ? 'auto' : undefined,
1176
+ ...chatEngine.chatRequestExtras({ model: ai.model, baseUrl: ai.baseUrl, tools }, ai),
1177
+ });
1178
+ if (!response.ok) return { ok: false, status: response.status, errText };
1179
+ return { ok: true, aiResponse: await response.json() };
1180
+ } finally {
1181
+ clearTimeout(timeout);
1182
+ if (signal) signal.removeEventListener('abort', onOuterAbort);
1183
+ }
1184
+ }
1185
+
1186
+ // Minimum time left in the request window for the corrective retry.
1187
+ const EDIT_RETRY_MIN_MS = 5_000;
1188
+
1189
+ // A cloud chat turn: the call, the post-processing and — when edit_book
1190
+ // was offered, NOT called, and the reply claims a change — ONE corrective
1191
+ // call ("you did not call edit_book…") inside the same time window. If
1192
+ // the retry still applies nothing, the honest "NOT changed" reply of the
1193
+ // first pass stays.
1194
+ async function runCloudTurn(ai, apiMessages, tools, bookData, bookId, { canEdit, logTag, timeoutMs, signal }) {
1195
+ const deadline = Date.now() + timeoutMs;
1196
+ const first = await cloudChatCompletion(ai, apiMessages, tools, { timeoutMs, signal });
1197
+ if (!first.ok) return { error: first };
1198
+ const msg1 = first.aiResponse.choices?.[0]?.message;
1199
+ const processed = processChatReply(msg1?.content || '', msg1?.tool_calls || [], bookData, bookId, {
1200
+ canEdit, logTag, finishReason: first.aiResponse.choices?.[0]?.finish_reason || null,
1201
+ });
1202
+ if (processed.editOutcome !== 'claimed_not_applied') {
1203
+ return { processed, aiResponse: first.aiResponse, retried: false };
1204
+ }
1205
+ const left = deadline - Date.now();
1206
+ if (left < EDIT_RETRY_MIN_MS) {
1207
+ log(`${logTag} edit retry skipped for ${bookId}: ${left} ms left in the request window`);
1208
+ return { processed, aiResponse: first.aiResponse, retried: false };
1209
+ }
1210
+ const retryMessages = [
1211
+ ...apiMessages,
1212
+ { role: 'assistant', content: msg1?.content || '' },
1213
+ { role: 'user', content: chatEngine.EDIT_RETRY_PROMPT },
1214
+ ];
1215
+ const second = await cloudChatCompletion(ai, retryMessages, tools, { timeoutMs: left, signal });
1216
+ if (!second.ok) {
1217
+ console.error(`${logTag} edit retry failed upstream: ${second.status}`);
1218
+ return { processed, aiResponse: first.aiResponse, retried: true };
1219
+ }
1220
+ const msg2 = second.aiResponse.choices?.[0]?.message;
1221
+ const again = processChatReply(msg2?.content || '', msg2?.tool_calls || [], bookData, bookId, {
1222
+ canEdit, logTag, finishReason: second.aiResponse.choices?.[0]?.finish_reason || null,
1223
+ });
1224
+ if (again.editOutcome === 'applied' || again.editOutcome === 'rejected') {
1225
+ return { processed: again, aiResponse: second.aiResponse, retried: true };
1226
+ }
1227
+ return { processed, aiResponse: first.aiResponse, retried: true };
1228
+ }
1229
+
1230
+ // One diagnostic line per chat turn — no prompt or reply text, only the
1231
+ // shape of the answer (the 19.11 investigation had nothing to go on).
1232
+ function logTurn(logTag, { sessionId, mode, ai, processed, retried, finishReason }) {
1233
+ try {
1234
+ log(`${logTag} turn session=${sessionId} mode=${mode} source=${chatAiSourceToken(ai)} model=${ai.model || '-'}`
1235
+ + ` finish=${finishReason || '-'} reply_chars=${(processed.replyText || '').length}`
1236
+ + ` tool_calls=${processed.toolCalls.length} edit=${processed.editOutcome}`
1237
+ + ` patches=${processed.patches.length}${retried ? ' retry=1' : ''}`);
1238
+ if (processed.editErrors && processed.editErrors.length > 0) {
1239
+ log(`${logTag} edit_book not applied (session=${sessionId}): ${processed.editErrors.join('; ').slice(0, 500)}`);
1240
+ }
1241
+ } catch (_) { /* diagnostics never break a turn */ }
1216
1242
  }
1217
1243
 
1218
1244
  log('[ROUTES] AI routes loaded');
@@ -49,7 +49,19 @@ module.exports = function(config, deps = {}) {
49
49
  import: 'You are an Import specialist. Convert arbitrary text into Animastor book structure. Analyze the text and automatically determine chapters, scenes, and units. If a book is already open, decide whether the text is a new chapter, continuation of current chapter, or extension of current scene. If no book is open, create a new book with manifest, metadata, chapters, scenes, and units. The user must NOT manually mark chapters/scenes/units — determine the structure from content. Always produce a valid Animastor book JSON.',
50
50
  edit: [
51
51
  'You are an Editor. You can modify scenes, heroes, locations, behaviour, and book structure.',
52
- 'Use the `edit_book` tool to apply changes. Always confirm changes with the user before applying.',
52
+ 'The ONLY way to change the book is a call of the `edit_book` tool with JSON Patch operations.',
53
+ 'When the user asks for a change, call `edit_book` in this same turn. Ask a question instead only when the request is genuinely ambiguous.',
54
+ 'Text or JSON written in your reply changes NOTHING: never paste a modified book, chapter, scene or unit as JSON instead of calling the tool.',
55
+ 'Never say that a change is done ("Done", "I have added…", "Готово", "Добавил…") unless you called `edit_book` in this turn — the server reports the real result to the user.',
56
+ '',
57
+ '## Chapters, scenes and units',
58
+ '`chapters` is an array addressed by index: `/chapters/<chapter_index>/scenes/<scene_index>/units/<unit_index>/<field>` (indexes start at 0).',
59
+ 'A new scene: `add /chapters/<chapter_index>/scenes/-` with the whole scene object, for example',
60
+ '`{"scene_id": "sc-1a2b3c4d", "scene_title": "Title", "type": "narration", "participants": [], "units": [{"id": "iu-5e6f7a8b", "type": "narration", "text": "Unit text."}]}`.',
61
+ 'Ids: `sc-` / `iu-` followed by 8 lowercase hex characters, unique in the book (the server assigns them when they are missing).',
62
+ 'Unit fields: `text`, `audio` {speaker, text}, `image` {shot, prompt, negative}, `video` {action}.',
63
+ 'Use `add` to set a field that may not exist yet (`add /chapters/0/scenes/1/units/0/video/action` creates `video`); `replace` works only on an existing field.',
64
+ 'Several changes — several operations in ONE `edit_book` call.',
53
65
  '',
54
66
  '## Heroes (VBook 4)',
55
67
  'Every character of the book — including the narrator — is a hero: one object in `heroes` (one file `characters/<id>.json`).',
@@ -250,13 +262,25 @@ module.exports = function(config, deps = {}) {
250
262
  }
251
263
 
252
264
  // ── Book context builder ──────────────────────────
253
- function buildBookContext(bookData) {
265
+ // The book JSON is a READ-ONLY snapshot for the model. Until 0.3.1 the
266
+ // header said "modify it as needed, and return the full changed version
267
+ // in your response" — models did exactly that (a ```json block with the
268
+ // changed scene + "Done") instead of calling edit_book, and nothing was
269
+ // saved (reports/2026-11-22/assistant-edit-bug.md).
270
+ // opts.canEdit — edit_book is offered in this turn (edit mode, unlocked).
271
+ function bookContextHeader(canEdit) {
272
+ return canEdit
273
+ ? 'Below is the current book JSON — a READ-ONLY snapshot. To change the book call the `edit_book` tool; a JSON or text in your reply changes nothing.'
274
+ : 'Below is the current book JSON for reference. In this mode you cannot change the book — if the user asks for a change, tell them to switch to the Edit mode.';
275
+ }
276
+
277
+ function buildBookContext(bookData, opts = {}) {
254
278
  if (!bookData) return '';
255
279
  const isLocked = bookData.manifest?.locked === true;
256
280
  const lines = [];
257
281
  lines.push(`Locked: ${isLocked}`);
258
282
  lines.push('');
259
- lines.push('Below is the full book JSON data. Read it, modify it as needed, and return the full changed version in your response.');
283
+ lines.push(bookContextHeader(opts.canEdit === true));
260
284
  lines.push('');
261
285
  lines.push('```json');
262
286
  lines.push(JSON.stringify(bookData, null, 2));
@@ -272,12 +296,13 @@ module.exports = function(config, deps = {}) {
272
296
  * @param {object|null} bookData
273
297
  * @returns {string} '' when no book data
274
298
  */
275
- function buildCompactBookContext(bookData) {
299
+ function buildCompactBookContext(bookData, opts = {}) {
276
300
  if (!bookData) return '';
277
301
  const MAX_CHAPTERS = 40;
278
302
  const MAX_SCENES_PER_CHAPTER = 40;
279
303
  const lines = [];
280
304
  lines.push('Full book JSON is too large for this transport — use this structural summary instead.');
305
+ lines.push(bookContextHeader(opts.canEdit === true));
281
306
  lines.push(`Book: ${bookData.book?.title || bookData.manifest?.title || 'Untitled'}`);
282
307
  lines.push(`Locked: ${bookData.manifest?.locked === true}`);
283
308
  const heroes = Array.isArray(bookData.heroes) ? bookData.heroes : [];
@@ -655,11 +680,94 @@ module.exports = function(config, deps = {}) {
655
680
  return { patches: out, errors };
656
681
  }
657
682
 
683
+ // ── Server-assigned ids for scenes / units added by a patch ──
684
+ // A model adding a scene often omits scene_id / unit ids (or the whole
685
+ // `units`/`participants` arrays). Such a scene passed the contract but
686
+ // was unaddressable afterwards (no scene_id → no chunk, no generation,
687
+ // no editor route). Missing ids get `sc-`/`iu-` + 8 hex, unique in the
688
+ // book; existing ids are never touched.
689
+ function randomHex8() {
690
+ let s = '';
691
+ for (let i = 0; i < 8; i++) s += Math.floor(Math.random() * 16).toString(16);
692
+ return s;
693
+ }
694
+
695
+ function assignMissingIds(book) {
696
+ if (!book || !Array.isArray(book.chapters)) return book;
697
+ const used = new Set();
698
+ const scenesOf = (ch) => (ch && Array.isArray(ch.scenes) ? ch.scenes : []);
699
+ for (const ch of book.chapters) {
700
+ for (const sc of scenesOf(ch)) {
701
+ if (!sc || typeof sc !== 'object') continue;
702
+ if (typeof sc.scene_id === 'string' && sc.scene_id) used.add(sc.scene_id);
703
+ for (const u of Array.isArray(sc.units) ? sc.units : []) {
704
+ if (u && typeof u.id === 'string' && u.id) used.add(u.id);
705
+ }
706
+ }
707
+ }
708
+ const fresh = (prefix) => {
709
+ let id;
710
+ do { id = `${prefix}-${randomHex8()}`; } while (used.has(id));
711
+ used.add(id);
712
+ return id;
713
+ };
714
+ for (const ch of book.chapters) {
715
+ for (const sc of scenesOf(ch)) {
716
+ if (!sc || typeof sc !== 'object' || Array.isArray(sc)) continue;
717
+ if (typeof sc.scene_id !== 'string' || !sc.scene_id) sc.scene_id = fresh('sc');
718
+ if (sc.participants === undefined) sc.participants = [];
719
+ if (!Array.isArray(sc.units)) continue;
720
+ for (const u of sc.units) {
721
+ if (u && typeof u === 'object' && !Array.isArray(u) && (typeof u.id !== 'string' || !u.id)) {
722
+ u.id = fresh('iu');
723
+ }
724
+ }
725
+ }
726
+ }
727
+ return book;
728
+ }
729
+
730
+ // ── Honest edit outcome (0.3.1) ────────────────────
731
+ // A turn in which edit_book was offered but NOT called, while the reply
732
+ // claims a finished change ("Done. I've added…", "Готово, добавил…") or
733
+ // pastes a changed book/scene JSON, changed nothing — the user must not
734
+ // be told otherwise. Heuristic on purpose: it only decides whether the
735
+ // route asks the model once more and, failing that, replaces the reply
736
+ // with an honest "the book was NOT changed".
737
+ const CLAIM_VERBS_EN = '(?:added|updated|changed|filled(?:\\s+in)?|created|replaced|removed|deleted|set|written|applied|inserted|renamed|modified|edited|fixed|appended)';
738
+ const CHANGE_CLAIM_PATTERNS = [
739
+ /^\s*(?:\*\*)?(?:done|all set|changes applied)\b/i,
740
+ new RegExp(`\\bI(?:'|’)?ve\\s+(?:now\\s+|also\\s+)?${CLAIM_VERBS_EN}\\b`, 'i'),
741
+ new RegExp(`\\bI\\s+have\\s+(?:now\\s+|also\\s+)?${CLAIM_VERBS_EN}\\b`, 'i'),
742
+ new RegExp(`\\b(?:has|have)\\s+(?:now\\s+)?been\\s+${CLAIM_VERBS_EN}\\b`, 'i'),
743
+ /(?:^|[^\p{L}])(?:готово|сделано|добавил[аи]?|обновил[аи]?|изменил[аи]?|заполнил[аи]?|вн[её]с(?:ла|ли)?|создал[аи]?|заменил[аи]?|удалил[аи]?|применил[аи]?|переименовал[аи]?|исправил[аи]?|дописал[аи]?)(?!\p{L})/iu,
744
+ ];
745
+ // A fenced JSON block that looks like book content (a changed scene /
746
+ // unit / hero / patch list) rather than an illustrative snippet.
747
+ const BOOK_JSON_BLOCK = /```(?:json)?\s*[[{][\s\S]*?"(?:scene_id|scenes|units|chapters|heroes|chapter_id|op)"\s*:[\s\S]*?```/i;
748
+
749
+ function looksLikeChangeClaim(text) {
750
+ const t = String(text || '');
751
+ if (!t.trim()) return false;
752
+ if (BOOK_JSON_BLOCK.test(t)) return true;
753
+ // A reply that ends by asking the user ("…чтобы я добавил сцену?",
754
+ // "Shall I add it?") is a question, not a report of a change.
755
+ if (/[??]\s*$/.test(t.replace(/[\s*_`)]+$/, ''))) return false;
756
+ return CHANGE_CLAIM_PATTERNS.some((re) => re.test(t));
757
+ }
758
+
759
+ // The corrective turn the route sends once when the model claimed a
760
+ // change without calling the tool.
761
+ const EDIT_RETRY_PROMPT = 'You have NOT called the `edit_book` tool, so the book is unchanged — nothing you wrote was saved. '
762
+ + 'Call `edit_book` now with the JSON Patch operations that implement the change you described. '
763
+ + 'If you cannot express it as patches, say plainly that the book was not changed.';
764
+
658
765
  function applyPatchesValidated(obj, patches) {
659
766
  const { result, errors } = applyPatches(obj, patches);
660
767
  if (errors.length > 0) {
661
768
  return { result: null, errors, validation_errors: [] };
662
769
  }
770
+ assignMissingIds(result);
663
771
  // Deterministic guard: unwrap {"item": x}, map names → character_id,
664
772
  // dedupe — across ALL scenes, not just the ones the model patched.
665
773
  normalizeBookParticipants(result);
@@ -690,6 +798,9 @@ module.exports = function(config, deps = {}) {
690
798
  applyPatchesValidated,
691
799
  normalizeHeroPatches,
692
800
  normalizeBookParticipants,
801
+ assignMissingIds,
802
+ looksLikeChangeClaim,
803
+ EDIT_RETRY_PROMPT,
693
804
  chatRequestExtras,
694
805
  validateBundleObject,
695
806
  toolDefinitions: {