@animastor/assistant 0.2.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,60 @@
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
+
36
+ ## 0.3.0 (2026-11-18, unpublished)
37
+
38
+ VBook 4 step 4 (animastor-docs `architecture/VBOOK_FORMAT_V4.md` §8.2). **Breaking.**
39
+
40
+ - `edit_book` addresses heroes by id: `/heroes/<hero_id>/…` — the segment after
41
+ `/heroes/` is an id, never an array index; the guard (`normalizeHeroPatches`,
42
+ inside `applyPatches`) turns it into the index. `add /heroes/<new_id>` appends a
43
+ hero. Refused with a hint: `/characters`, `/voices`, `/behaviors`,
44
+ `/behavior_rules`, `/mentions`, `/behavior`; computed `/hero_issues`,
45
+ `/scene_list`; replacing / removing the whole `/heroes`; index addressing;
46
+ the id / schema / rev of a hero; `voice.reference` (only the hero card pins a
47
+ reference); removing the narrator.
48
+ - `add` creates missing intermediate objects (`/heroes/<id>/behaviour/profile`).
49
+ - Edit-mode prompt and the `edit_book` tool describe heroes; participants are
50
+ mapped from `heroes` (exact name or id, case-insensitive — nothing fuzzy).
51
+ - Removed: `normalizeBehaviorPatches` and the character-delete cascade of
52
+ `behavior.json` v2 (rules live in the hero file and go with it).
53
+ - `chatRequestExtras(input, ai)` — the model extras plus the provider's
54
+ `disable_thinking` / `reasoning_effort` through the injected
55
+ `deps.withReasoning` (the host's `ai-reasoning.js`); both chat routes use it.
56
+ Without the injection the body is the one of 0.2.0.
57
+
3
58
  ## 0.2.0 (2026-11-10, unpublished)
4
59
 
5
60
  - Edit-mode prompt and `edit_book` tool describe behavior.json schema v2:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@animastor/assistant",
3
- "version": "0.2.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",
@@ -20,12 +20,13 @@ module.exports = function(app, redis, deps) {
20
20
  utils,
21
21
  } = deps;
22
22
  const { log } = utils;
23
- // Token budget, provider-gated enable_thinking, the one-shot
23
+ // Token budget, provider-gated enable_thinking (+ the provider's reasoning
24
+ // settings — chatEngine.chatRequestExtras), the one-shot
24
25
  // "Unsupported parameter" retry and upstream error text — package
25
26
  // logic (request-extras.cjs) carried by the engine.
26
27
  const {
27
28
  MAX_TOKENS_WITH_TOOLS, MAX_TOKENS_PLAIN,
28
- buildChatRequestExtras, describeUpstreamError, fetchChatCompletion,
29
+ describeUpstreamError, fetchChatCompletion,
29
30
  } = chatEngine.requestExtras;
30
31
  // The ports seam is the single host contract of the Assistant contour.
31
32
  const {
@@ -385,7 +386,8 @@ module.exports = function(app, redis, deps) {
385
386
 
386
387
  }
387
388
 
388
- const bookContext = chatEngine.buildBookContext(bookData);
389
+ const canEdit = tools.length > 0;
390
+ const bookContext = chatEngine.buildBookContext(bookData, { canEdit });
389
391
  if (bookContext) {
390
392
  // Connector per-message cap is 32 KB (ai-connector
391
393
  // lib/chat.cjs maxMessageChars, mirrored by the transport) —
@@ -395,7 +397,7 @@ module.exports = function(app, redis, deps) {
395
397
  const withinConnectorBudget = bookContext.length <= CONNECTOR_BOOK_CONTEXT_BUDGET;
396
398
  systemPrompt += '\n\n' + (ai.transport !== 'connector' || withinConnectorBudget
397
399
  ? bookContext
398
- : chatEngine.buildCompactBookContext(bookData));
400
+ : chatEngine.buildCompactBookContext(bookData, { canEdit }));
399
401
  }
400
402
 
401
403
  // Build API messages for AI call
@@ -420,6 +422,8 @@ module.exports = function(app, redis, deps) {
420
422
  }
421
423
 
422
424
  let aiResponse;
425
+ let processed = null;
426
+ let retried = false;
423
427
  if (ai.transport === 'connector') {
424
428
  // Local AI Connector path (LAC §9): the completion rides the
425
429
  // connector's authenticated WS session — no server-side URL,
@@ -480,141 +484,34 @@ module.exports = function(app, redis, deps) {
480
484
  // or owner detail rides the API response.
481
485
  aiSource = ai.source === 'shared' ? 'shared' : 'private-local';
482
486
  } else {
483
- const controller = new AbortController();
484
- const timeout = setTimeout(() => controller.abort(), AI_FETCH_TIMEOUT_MS);
485
- const { response, errText } = await fetchChatCompletion(safeFetch, `${ai.baseUrl}/chat/completions`, {
486
- method: 'POST',
487
- headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ai.apiKey}` },
488
- signal: controller.signal,
489
- validatePublic: ai.validatePublic,
490
- }, {
491
- model: ai.model,
492
- messages: apiMessages,
493
- tools: tools.length > 0 ? tools : undefined,
494
- tool_choice: tools.length > 0 ? 'auto' : undefined,
495
- ...buildChatRequestExtras({ model: ai.model, baseUrl: ai.baseUrl, tools }),
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,
496
492
  });
497
- clearTimeout(timeout);
498
-
499
- if (!response.ok) {
500
- const upstreamError = describeUpstreamError(response.status, errText); // key-masked
493
+ if (turn.error) {
494
+ const upstreamError = describeUpstreamError(turn.error.status, turn.error.errText); // key-masked
501
495
  console.error('[AI]', upstreamError);
502
496
  return res.status(502).json({ error: upstreamError, code: 'upstream_error' });
503
497
  }
504
-
505
- aiResponse = await response.json();
506
- }
507
- const aiMessage = aiResponse.choices?.[0]?.message;
508
- let replyText = aiMessage?.content || '';
509
- // Strip AI chain-of-thought reasoning blocks — internal, not for the UI
510
- replyText = replyText.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
511
- // Strip tool_call & tool_call markers that some models leak into content
512
- replyText = replyText.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
513
- replyText = replyText.replace(/<\/?tool_call[^>]*>/gi, '').trim();
514
- // Also strip partial tool_call remnants without the opening '<' (e.g. 'tool_call>')
515
- replyText = replyText.replace(/tool_call[^>]*>/gi, '').trim();
516
- replyText = replyText.replace(/\/?tool_call\b/gi, '').trim();
517
- // Catch any remaining tool_call-like fragments where leading chars may be missing
518
- // (e.g. 'ool_call>' — Qwen3 sometimes outputs partial tag remnants)
519
- replyText = replyText.replace(/[a-z]*_call[^>]*>/gi, '').trim();
520
- // Only extract tool calls from content if model didn't return structured tool_calls
521
- // (avoids duplicates — Qwen3 sometimes puts tool_call JSON in both places)
522
- const structuredToolCalls = aiMessage?.tool_calls || [];
523
- let contentToolCalls = [];
524
- if (structuredToolCalls.length === 0) {
525
- const result = extractToolCallsFromContent(replyText);
526
- contentToolCalls = result.toolCalls;
527
- replyText = result.cleanedContent;
498
+ processed = turn.processed;
499
+ retried = turn.retried;
500
+ aiResponse = turn.aiResponse;
528
501
  }
529
- // If after stripping, the reply is just garbage remnants (e.g. 'ool_call>', 'tool_call>'),
530
- // treat as empty so the fallback message below kicks in.
531
- // A remnant is considered garbage if:
532
- // - it has no real word of 3+ letters, OR
533
- // - it contains '_call' (a tool_call-like fragment)
534
- if (replyText && replyText.length < 30 && (!/[\w\u0400-\u04FF]{3,}/.test(replyText) || /_call/i.test(replyText))) {
535
- replyText = '';
536
- }
537
- const toolCalls = [...contentToolCalls, ...structuredToolCalls];
538
-
539
- // Handle tool calls
540
- let patches = [];
541
- let toolResults = [];
542
- let lastEditError = null;
543
-
544
- if (toolCalls.length > 0) {
545
- for (const tc of toolCalls) {
546
- if (tc.function.name === 'edit_book') {
547
- try {
548
- const args = JSON.parse(tc.function.arguments);
549
- // Validated application: patch → contract validation →
550
- // result. A structurally broken result (e.g. voices.json
551
- // becoming a string instead of an object) is rejected
552
- // here and never reaches the save block below.
553
- const patchResult = chatEngine.applyPatchesValidated(bookData, args.patches || []);
554
- if (patchResult.errors.length > 0) {
555
- const errMsg = patchResult.errors.join('; ');
556
- toolResults.push({ tool: 'edit_book', error: errMsg, validation_errors: patchResult.validation_errors });
557
- lastEditError = errMsg;
558
- } else {
559
- patches = args.patches || [];
560
- toolResults.push({ tool: 'edit_book', applied: patches.length, book_id: bookId });
561
- }
562
- } catch (parseErr) {
563
- toolResults.push({ tool: 'edit_book', error: parseErr.message });
564
- lastEditError = parseErr.message;
565
- }
566
- } else {
567
- toolResults.push({ tool: tc.function.name, result: 'Tool executed (no handler)' });
568
- }
569
- }
570
- }
571
-
572
- // Save patches if any were applied
573
- if (patches.length > 0 && bookData) {
574
- try {
575
- // Re-apply with validation (defense in depth): the save block
576
- // is the last gate before disk — an invalid candidate state
577
- // must never be written and must not be reported as applied.
578
- const patchResult = chatEngine.applyPatchesValidated(bookData, patches);
579
- if (patchResult.errors.length > 0) {
580
- // Reject the whole mutation: keep previous canonical state,
581
- // report the failure to the assistant/user, apply nothing.
582
- if (!lastEditError) lastEditError = patchResult.errors.join('; ');
583
- patches = [];
584
- toolResults.push({ tool: 'edit_book', error: lastEditError, validation_errors: patchResult.validation_errors, rejected: true });
585
- } else if (patchResult.result) {
586
- // ONE save semantics through the AssistantPorts seam:
587
- // full bundle save when chapters are intact, targeted
588
- // file save (chapters skipped) on a corrupted load.
589
- persistBook(bookId, patchResult.result);
590
- log('[AI] Book updated (via persistBook):', patches.length, 'patches applied to', bookId);
591
- }
592
- } catch (saveErr) {
593
- console.error('[AI] Failed to save updated book:', saveErr.message);
594
- if (!lastEditError) lastEditError = saveErr.message;
595
- // Nothing was persisted — do not report success.
596
- patches = [];
597
- }
598
- }
599
-
600
- // Build a user-visible reply when the AI returned empty content but tool calls were processed
601
- if (!replyText && toolCalls.length > 0) {
602
- if (lastEditError) {
603
- replyText = `⚠️ Edit error: ${lastEditError}`;
604
- } else if (patches.length > 0) {
605
- replyText = `✅ Changes applied: ${patches.length} patch(es) to the book.`;
606
- } else {
607
- replyText = `🤖 Processed ${toolCalls.length} tool call(s).`;
608
- }
609
- }
610
-
611
- // No content AND no tool calls — the model produced nothing usable
612
- // (e.g. a reasoning model burned the whole max_tokens budget on
613
- // reasoning). Report it honestly instead of returning an empty
614
- // reply that UIs render as a fake "tool executed" message.
615
- if (!replyText && toolCalls.length === 0) {
616
- 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
+ });
617
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;
618
515
 
619
516
  // Update session messages: merge with stored history
620
517
  const updatedMessages = [
@@ -629,15 +526,13 @@ module.exports = function(app, redis, deps) {
629
526
  // file/resource that failed the bundle contract, so a corrective
630
527
  // patch ("почини voices.json") lands in the very next turn —
631
528
  // the error reply is stored in session history for that purpose.
632
- const validationErrors = toolResults
633
- .flatMap(tr => tr.validation_errors || []);
634
-
635
529
  res.json({
636
530
  reply: replyText,
637
531
  tool_calls: toolCalls,
638
532
  tool_results: toolResults,
639
533
  patches_applied: patches.length,
640
534
  validation_errors: validationErrors,
535
+ edit_outcome: editOutcome,
641
536
  session_id: activeSessionId,
642
537
  ai_source: aiSource || (ai.source === 'workspace' ? 'cloud' : (ai.source === 'system' ? 'system' : ai.source)),
643
538
  });
@@ -868,14 +763,15 @@ module.exports = function(app, redis, deps) {
868
763
  });
869
764
  }
870
765
 
871
- const bookContext = chatEngine.buildBookContext(bookData);
766
+ const canEdit = tools.length > 0;
767
+ const bookContext = chatEngine.buildBookContext(bookData, { canEdit });
872
768
  if (bookContext) {
873
769
  // Same connector per-message cap as the non-streaming route —
874
770
  // oversized book JSON falls back to the compact summary.
875
771
  const withinConnectorBudget = bookContext.length <= CONNECTOR_BOOK_CONTEXT_BUDGET;
876
772
  systemPrompt += '\n\n' + (ai.transport !== 'connector' || withinConnectorBudget
877
773
  ? bookContext
878
- : chatEngine.buildCompactBookContext(bookData));
774
+ : chatEngine.buildCompactBookContext(bookData, { canEdit }));
879
775
  }
880
776
 
881
777
  let apiMessages;
@@ -996,7 +892,13 @@ module.exports = function(app, redis, deps) {
996
892
  // canonical text replaces any streamed approximation
997
893
  // client-side (converge-on-terminal semantics — the same
998
894
  // contract as OpenAI SSE clients).
999
- 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
+ });
1000
902
  finalReply = processed.replyText;
1001
903
  terminalPayload = {
1002
904
  reply: finalReply,
@@ -1004,6 +906,7 @@ module.exports = function(app, redis, deps) {
1004
906
  tool_results: processed.toolResults,
1005
907
  patches_applied: processed.patches.length,
1006
908
  validation_errors: processed.validationErrors,
909
+ edit_outcome: processed.editOutcome,
1007
910
  session_id: activeSessionId,
1008
911
  ai_source: aiSource.value,
1009
912
  finish_reason: cres.finishReason || 'stop',
@@ -1013,41 +916,27 @@ module.exports = function(app, redis, deps) {
1013
916
  } else {
1014
917
  // Cloud provider branch: the existing non-streaming
1015
918
  // upstream call, re-emitted as ONE delta + terminal. No
1016
- // second upstream protocol; cloud behavior unchanged.
1017
- const controller = new AbortController();
1018
- const onOuterAbort = () => controller.abort();
1019
- abort.signal.addEventListener('abort', onOuterAbort, { once: true });
1020
- const timeout = setTimeout(() => controller.abort(), clampStreamTimeoutMs(req.body?.timeout_ms));
1021
- let response, errText;
1022
- try {
1023
- ({ response, errText } = await fetchChatCompletion(safeFetch, `${ai.baseUrl}/chat/completions`, {
1024
- method: 'POST',
1025
- headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ai.apiKey}` },
1026
- signal: controller.signal,
1027
- validatePublic: ai.validatePublic,
1028
- }, {
1029
- model: ai.model,
1030
- messages: apiMessages,
1031
- tools: tools.length > 0 ? tools : undefined,
1032
- tool_choice: tools.length > 0 ? 'auto' : undefined,
1033
- ...buildChatRequestExtras({ model: ai.model, baseUrl: ai.baseUrl, tools }),
1034
- }));
1035
- } finally {
1036
- clearTimeout(timeout);
1037
- abort.signal.removeEventListener('abort', onOuterAbort);
1038
- }
1039
-
1040
- if (!response.ok) {
1041
- 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
1042
929
  console.error('[AI STREAM]', errorData.error);
1043
930
  if (!clientGone) sendTerminal('error', errorData);
1044
931
  await persistFailedTurn(`⚠️ ${errorData.error}`);
1045
932
  return;
1046
933
  }
1047
- const aiResponse = await response.json();
1048
- const aiMessage = aiResponse.choices?.[0]?.message;
1049
- let replyText = aiMessage?.content || '';
1050
- 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
+ });
1051
940
  finalReply = processed.replyText;
1052
941
  if (finalReply && !clientGone) writeEvent('delta', { delta: finalReply });
1053
942
  terminalPayload = {
@@ -1056,6 +945,7 @@ module.exports = function(app, redis, deps) {
1056
945
  tool_results: processed.toolResults,
1057
946
  patches_applied: processed.patches.length,
1058
947
  validation_errors: processed.validationErrors,
948
+ edit_outcome: processed.editOutcome,
1059
949
  session_id: activeSessionId,
1060
950
  ai_source: aiSource.value,
1061
951
  finish_reason: aiResponse.choices?.[0]?.finish_reason || 'stop',
@@ -1124,11 +1014,29 @@ module.exports = function(app, redis, deps) {
1124
1014
  }
1125
1015
  });
1126
1016
 
1127
- // Reply post-processing shared by both branches of the stream route:
1128
- // the exact strip/extract/apply pipeline of the non-streaming chat route
1129
- // (think blocks, tool_call remnants, content-embedded tool calls, patch
1130
- // application with validation, and the honest no-result fallback).
1131
- 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;
1132
1040
  let replyText = rawContent || '';
1133
1041
  replyText = replyText.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
1134
1042
  replyText = replyText.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
@@ -1137,81 +1045,200 @@ module.exports = function(app, redis, deps) {
1137
1045
  replyText = replyText.replace(/\/?tool_call\b/gi, '').trim();
1138
1046
  replyText = replyText.replace(/[a-z]*_call[^>]*>/gi, '').trim();
1139
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).
1140
1050
  let contentToolCalls = [];
1141
1051
  if ((structuredToolCalls || []).length === 0) {
1142
1052
  const result = extractToolCallsFromContent(replyText);
1143
1053
  contentToolCalls = result.toolCalls;
1144
1054
  replyText = result.cleanedContent;
1145
1055
  }
1146
- 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))) {
1147
1058
  replyText = '';
1148
1059
  }
1149
1060
  const toolCalls = [...contentToolCalls, ...(structuredToolCalls || [])];
1150
1061
 
1151
- let patches = [];
1152
1062
  const toolResults = [];
1153
- let lastEditError = null;
1154
-
1155
- if (toolCalls.length > 0) {
1156
- for (const tc of toolCalls) {
1157
- if (tc.function.name === 'edit_book') {
1158
- try {
1159
- const args = JSON.parse(tc.function.arguments);
1160
- const patchResult = chatEngine.applyPatchesValidated(bookData, args.patches || []);
1161
- if (patchResult.errors.length > 0) {
1162
- const errMsg = patchResult.errors.join('; ');
1163
- toolResults.push({ tool: 'edit_book', error: errMsg, validation_errors: patchResult.validation_errors });
1164
- 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 || [];
1165
1095
  } else {
1166
- patches = args.patches || [];
1167
- 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 });
1168
1099
  }
1169
- } catch (parseErr) {
1170
- toolResults.push({ tool: 'edit_book', error: parseErr.message });
1171
- lastEditError = parseErr.message;
1172
1100
  }
1173
- } else {
1174
- toolResults.push({ tool: tc.function.name, result: 'Tool executed (no handler)' });
1101
+ } catch (parseErr) {
1102
+ err = `invalid edit_book arguments: ${parseErr.message}`;
1175
1103
  }
1176
1104
  }
1105
+ if (err) {
1106
+ editErrors.push(err);
1107
+ toolResults.push({ tool: 'edit_book', error: err, validation_errors: validationErrors });
1108
+ }
1177
1109
  }
1178
1110
 
1179
- 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) {
1180
1115
  try {
1181
- const patchResult = chatEngine.applyPatchesValidated(bookData, patches);
1182
- if (patchResult.errors.length > 0) {
1183
- if (!lastEditError) lastEditError = patchResult.errors.join('; ');
1184
- patches = [];
1185
- toolResults.push({ tool: 'edit_book', error: lastEditError, validation_errors: patchResult.validation_errors, rejected: true });
1186
- } else if (patchResult.result) {
1187
- // ONE save semantics through the AssistantPorts seam (the
1188
- // same persistBook as the non-streaming route — no
1189
- // duplicated targeted-save fallback).
1190
- persistBook(bookId, patchResult.result);
1191
- log('[AI STREAM] Book updated (via persistBook):', patches.length, 'patches applied to', bookId);
1192
- }
1116
+ persistBook(bookId, workingBook);
1117
+ patches = appliedPatches;
1118
+ log(`${logTag} Book updated (via persistBook):`, patches.length, 'patches applied to', bookId);
1193
1119
  } catch (saveErr) {
1194
- console.error('[AI STREAM] Failed to save updated book:', saveErr.message);
1195
- if (!lastEditError) lastEditError = saveErr.message;
1196
- 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 });
1197
1124
  }
1198
1125
  }
1199
1126
 
1200
- if (!replyText && toolCalls.length > 0) {
1201
- if (lastEditError) {
1202
- replyText = `⚠️ Edit error: ${lastEditError}`;
1203
- } else if (patches.length > 0) {
1204
- replyText = `✅ Changes applied: ${patches.length} patch(es) to the book.`;
1205
- } else {
1206
- replyText = `🤖 Processed ${toolCalls.length} tool call(s).`;
1207
- }
1208
- }
1209
- if (!replyText && toolCalls.length === 0) {
1210
- 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.';
1211
1147
  }
1212
1148
 
1213
1149
  const validationErrors = toolResults.flatMap(tr => tr.validation_errors || []);
1214
- 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 */ }
1215
1242
  }
1216
1243
 
1217
1244
  log('[ROUTES] AI routes loaded');
@@ -32,57 +32,79 @@ module.exports = function(config, deps = {}) {
32
32
  // Chat fallback base URL — injected by the composition root (operator
33
33
  // env knob). The literal default is the last-resort contract value.
34
34
  const AI_API_BASE_URL = deps.aiApiBaseUrl || 'https://integrate.api.nvidia.com/v1';
35
+ // Provider reasoning settings (disable_thinking / reasoning_effort) — the
36
+ // host's ONE helper (ai-reasoning.withReasoning), injected by the
37
+ // composition root so the chat body is built exactly like the analysis
38
+ // body and the provider connection test. Not injected → extras unchanged.
39
+ const withReasoning = typeof deps.withReasoning === 'function' ? deps.withReasoning : (extras) => ({ ...(extras || {}) });
40
+
41
+ /** Token budget + thinking switch of the model, with the provider's reasoning settings on top. */
42
+ function chatRequestExtras(input, ai) {
43
+ return withReasoning(requestExtras.buildChatRequestExtras(input), ai || null);
44
+ }
35
45
 
36
46
  // ── Mode-specific system prompts ──────────────────
37
47
  const MODE_PROMPTS = {
38
48
  conversation: 'You are a creative assistant in Conversational mode. Answer questions, discuss ideas, explain concepts, and brainstorm. Do NOT make any changes to the book — this is a read-only discussion.',
39
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.',
40
50
  edit: [
41
- 'You are an Editor. You can modify scenes, characters, locations, behavior, and book structure.',
42
- 'Use the `edit_book` tool to apply changes. Always confirm changes with the user before applying.',
51
+ 'You are an Editor. You can modify scenes, heroes, locations, behaviour, and book structure.',
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.',
65
+ '',
66
+ '## Heroes (VBook 4)',
67
+ 'Every character of the book — including the narrator — is a hero: one object in `heroes` (one file `characters/<id>.json`).',
68
+ 'A hero is addressed by its id, NEVER by an array index: `/heroes/<hero_id>/<field>`.',
69
+ 'Hero fields: `name`, `role`, `aliases` (how the author names the hero in the text), `notes` (for people only),',
70
+ '`passport` {appearance, clothes, video_tokens: 1-4 short visible features}, `looks` (named passport overrides),',
71
+ '`voice` {timbre, manner, reference}, `behaviour` {profile: {baseline, quirks, reactions}, rules: [...]}.',
72
+ 'Never write `voice.reference` (a pinned audio file — only the hero card pins it), `id`, `schema`, `rev` or `hero_issues`.',
73
+ 'A new hero: `add /heroes/<new_id>` with the whole hero object (`schema: "animastor.character/1"`, `id` equal to <new_id>).',
74
+ 'The narrator (`/heroes/narrator`) cannot be removed.',
75
+ 'The paths `/characters`, `/voices`, `/behaviors`, `/mentions` do not exist any more — they are refused.',
43
76
  '',
44
77
  '## Scene Participants',
45
- '`scene.participants` is ALWAYS a JSON array of character_id strings taken from `characters.json` — never display names, never a bare string, never an object like {"item": ...}.',
78
+ '`scene.participants` is ALWAYS a JSON array of hero ids (character_id) taken from `heroes` — never display names, never a bare string, never an object like {"item": ...}.',
46
79
  'Example: `["yura", "svetlana"]` — NOT `["Юра", "yura"]` and NOT `{"item": ["yura", "svetlana"]}`.',
47
80
  'When the user asks to fix participants across the whole book, apply the change to EVERY scene in EVERY chapter — do not stop after one scene. List one patch per affected scene.',
48
81
  '',
49
- '## Character Behavior',
50
- 'Each character can have a Behavior entry in the book data under `behaviors.characters` (keyed by character_id).',
51
- '`behaviors` is schema v2: `{"schema_version": 2, "rules": [...], "characters": {...}}`. Edit ONLY `behaviors.characters.<character_id>`; never change `schema_version` or `rules` unless the user explicitly asks about behaviour rules.',
52
- 'Behavior describes HOW a character acts — their mannerisms, habits, and reactions.',
53
- '',
54
- 'Behavior schema:',
82
+ '## Hero Behaviour',
83
+ 'The character of a hero lives in `/heroes/<hero_id>/behaviour/profile`:',
55
84
  '```json',
56
85
  '{',
57
- ' "characters": {',
58
- ' "<character_id>": {',
59
- ' "baseline": "How the character normally behaves — characteristic manner of movement, expressions, gestures, posture, speech patterns.",',
60
- ' "quirks": ["Repeated characteristic habit or mannerism."],',
61
- ' "reactions": [',
62
- ' {',
63
- ' "trigger": "A situation or emotional state.",',
64
- ' "reaction": "The observable behavioral response."',
65
- ' }',
66
- ' ]',
67
- ' }',
68
- ' }',
86
+ ' "baseline": "How the hero normally behaves — characteristic manner of movement, expressions, gestures, posture, speech patterns.",',
87
+ ' "quirks": ["Repeated characteristic habit or mannerism."],',
88
+ ' "reactions": [',
89
+ ' { "trigger": "A situation or emotional state.", "reaction": "The observable behavioral response." }',
90
+ ' ]',
69
91
  '}',
70
92
  '```',
71
- '',
72
93
  'Field meanings:',
73
- '- **baseline**: how the character behaves NORMALLY — characteristic manner of movement, expressions, gestures, posture, speech rhythm.',
74
- '- **quirks**: recurring habits or mannerisms specific to this character (one string per entry).',
94
+ '- **baseline**: how the hero behaves NORMALLY — characteristic manner of movement, expressions, gestures, posture, speech rhythm.',
95
+ '- **quirks**: recurring habits or mannerisms specific to this hero (one string per entry).',
75
96
  '- **reactions**: trigger→reaction patterns. `trigger` = situation or state; `reaction` = observable behavioral response.',
97
+ 'Do not touch `behaviour.rules` unless the user explicitly asks about behaviour rules.',
76
98
  '',
77
- 'When the user asks to create or modify character behavior:',
78
- '1. Find the character by character_id from `characters` in the book data.',
79
- '2. Study the character passport (appearance, clothes, description) to understand their personality.',
80
- '3. Create behavior that matches the character personality — distinct, specific, believable.',
81
- '4. Use `edit_book` to write to `/behaviors/characters/{character_id}` with the full behavior object.',
82
- '5. Do NOT create a new character. Do NOT modify passport or voice unless asked.',
99
+ 'When the user asks to create or modify the behaviour of a hero:',
100
+ '1. Find the hero by id (or by `name` / `aliases`) in `heroes`.',
101
+ '2. Study the passport (appearance, clothes) and notes to understand the personality.',
102
+ '3. Create behaviour that matches the personality — distinct, specific, believable.',
103
+ '4. Use `edit_book` with `add /heroes/<hero_id>/behaviour/profile` and the full profile object (add creates or replaces).',
104
+ '5. Do NOT create a new hero. Do NOT modify passport or voice unless asked.',
83
105
  '',
84
106
  'Example user request: "Придумай поведение для Юры и Светланы."',
85
- 'Agent action: find characters Yuri and Svetlana, analyze passports, write individualized baseline/quirks/reactions via edit_book.',
107
+ 'Agent action: find heroes yura and svetlana, analyze passports, write individualized baseline/quirks/reactions via edit_book.',
86
108
  ].join('\n'),
87
109
  director: 'You are a Film Director. Advise on camera angles, composition, lighting, mood, and atmosphere for scenes. You can write into storyboard_elements for the current scene. Think visually and cinematically.',
88
110
  extraction: 'You are an Extraction specialist. Extract structured entities from the text such as characters, objects, locations, and key terms.',
@@ -93,7 +115,7 @@ module.exports = function(config, deps = {}) {
93
115
  const TOPIC_PROMPTS = {
94
116
  book: 'You are a creative assistant helping with a visual book project. Answer questions about the book, its plot, characters, and structure.',
95
117
  scene: 'You are a scene editor assistant. Help refine the current scene: visuals, audio, pacing, and dialogue. Use the current position context (chapter/scene/unit) when relevant.',
96
- characters: 'You are a character development assistant. Help design, refine, and track characters for the visual book.',
118
+ characters: 'You are a character development assistant. Help design, refine, and track the heroes of the visual book (book.heroes — one object per hero, the narrator included).',
97
119
  script: 'You are a scriptwriting assistant. Help with plot structure, narrative flow, scene transitions, and story arc.',
98
120
  };
99
121
 
@@ -240,13 +262,25 @@ module.exports = function(config, deps = {}) {
240
262
  }
241
263
 
242
264
  // ── Book context builder ──────────────────────────
243
- 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 = {}) {
244
278
  if (!bookData) return '';
245
279
  const isLocked = bookData.manifest?.locked === true;
246
280
  const lines = [];
247
281
  lines.push(`Locked: ${isLocked}`);
248
282
  lines.push('');
249
- 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));
250
284
  lines.push('');
251
285
  lines.push('```json');
252
286
  lines.push(JSON.stringify(bookData, null, 2));
@@ -262,18 +296,19 @@ module.exports = function(config, deps = {}) {
262
296
  * @param {object|null} bookData
263
297
  * @returns {string} '' when no book data
264
298
  */
265
- function buildCompactBookContext(bookData) {
299
+ function buildCompactBookContext(bookData, opts = {}) {
266
300
  if (!bookData) return '';
267
301
  const MAX_CHAPTERS = 40;
268
302
  const MAX_SCENES_PER_CHAPTER = 40;
269
303
  const lines = [];
270
304
  lines.push('Full book JSON is too large for this transport — use this structural summary instead.');
305
+ lines.push(bookContextHeader(opts.canEdit === true));
271
306
  lines.push(`Book: ${bookData.book?.title || bookData.manifest?.title || 'Untitled'}`);
272
307
  lines.push(`Locked: ${bookData.manifest?.locked === true}`);
273
- const characters = Array.isArray(bookData.characters) ? bookData.characters : [];
274
- if (characters.length > 0) {
275
- const names = characters.slice(0, 30).map((c) => `${c.id || c.character_id || '?'}${c.name ? ` (${c.name})` : ''}`).join(', ');
276
- lines.push(`Characters: ${names}`);
308
+ const heroes = Array.isArray(bookData.heroes) ? bookData.heroes : [];
309
+ if (heroes.length > 0) {
310
+ const names = heroes.slice(0, 30).map((h) => `${(h && h.id) || '?'}${h && h.name ? ` (${h.name})` : ''}`).join(', ');
311
+ lines.push(`Heroes: ${names}`);
277
312
  }
278
313
  const chapters = Array.isArray(bookData.chapters) ? bookData.chapters : [];
279
314
  lines.push(`Chapters: ${chapters.length}`);
@@ -292,7 +327,7 @@ module.exports = function(config, deps = {}) {
292
327
  type: 'function',
293
328
  function: {
294
329
  name: 'edit_book',
295
- description: 'Apply changes to the current book. Call this when the user asks to edit the book content (title, author, characters, scenes, text, behavior, etc.). Supports writing to /behaviors/characters/{character_id} for character behavior. Do NOT call if the book is locked.',
330
+ description: 'Apply changes to the current book. Call this when the user asks to edit the book content (title, author, heroes, scenes, text, behaviour, etc.). Heroes are addressed by id: /heroes/{hero_id}/... (for example /heroes/yura/behaviour/profile). Do NOT call if the book is locked.',
296
331
  parameters: {
297
332
  type: 'object',
298
333
  properties: {
@@ -303,7 +338,7 @@ module.exports = function(config, deps = {}) {
303
338
  type: 'object',
304
339
  properties: {
305
340
  op: { type: 'string', enum: ['replace', 'add', 'remove'], description: 'Operation type' },
306
- path: { type: 'string', description: 'JSON path like /book/title, /chapters/0/scenes/1/units/0/text, /behaviors/characters/character_id/baseline' },
341
+ path: { type: 'string', description: 'JSON path like /book/title, /chapters/0/scenes/1/units/0/text, /heroes/yura/passport/clothes, /heroes/yura/behaviour/profile' },
307
342
  value: { description: 'New value (for replace/add)' },
308
343
  },
309
344
  required: ['op', 'path'],
@@ -393,13 +428,33 @@ module.exports = function(config, deps = {}) {
393
428
  return { parent: current, key: lastKey, value: current ? current[lastKey] : undefined };
394
429
  }
395
430
 
431
+ function ensureObjectParents(obj, pathStr) {
432
+ const parts = String(pathStr || '').split('/').filter(Boolean);
433
+ let current = obj;
434
+ for (let i = 0; i < parts.length - 1; i++) {
435
+ if (current === null || typeof current !== 'object') return;
436
+ const key = Array.isArray(current) && /^\d+$/.test(parts[i]) ? Number(parts[i]) : parts[i];
437
+ if (current[key] === undefined || current[key] === null) {
438
+ if (Array.isArray(current) || /^\d+$/.test(parts[i + 1]) || parts[i + 1] === '-') return;
439
+ current[key] = {};
440
+ }
441
+ current = current[key];
442
+ }
443
+ }
444
+
396
445
  // ── JSON Patch application ────────────────────────
397
446
  function applyPatches(obj, patches) {
398
447
  const result = JSON.parse(JSON.stringify(obj));
399
448
  const errors = [];
449
+ const guarded = normalizeHeroPatches(result, patches || []);
450
+ errors.push(...guarded.errors);
451
+ if (guarded.errors.length > 0) return { result, errors };
400
452
 
401
- for (const patch of normalizeBehaviorPatches(obj, patches || [])) {
453
+ for (const patch of guarded.patches) {
402
454
  const { op, path: pathStr, value } = patch;
455
+ // `add` creates missing intermediate OBJECTS (never arrays): adding
456
+ // /heroes/<id>/behaviour/profile to a hero without behaviour works
457
+ if (op === 'add') ensureObjectParents(result, pathStr);
403
458
  const { parent, key, value: oldValue } = resolvePath(result, pathStr);
404
459
 
405
460
  if (!parent && op !== 'add') {
@@ -461,35 +516,9 @@ module.exports = function(config, deps = {}) {
461
516
  }
462
517
  }
463
518
 
464
- cascadeDeletedCharacterBehaviors(obj, result);
465
519
  return { result, errors };
466
520
  }
467
521
 
468
- // ── Character-removal cascade for behavior.json v2 ──
469
- // A character removed by the patches (present in obj.characters, gone in
470
- // result.characters) loses its behaviors.characters entry and every rule
471
- // with scope:"character" bound to it — same contract as the editor's
472
- // character removal route. Global rules stay. Legacy (no schema_version)
473
- // in-memory maps only lose the entry.
474
- function cascadeDeletedCharacterBehaviors(before, after) {
475
- if (!after || !after.behaviors || typeof after.behaviors !== 'object') return;
476
- const ids = (list) => new Set((Array.isArray(list) ? list : []).map(c => c && c.id).filter(Boolean));
477
- const was = ids(before && before.characters);
478
- if (was.size === 0) return;
479
- const now = ids(after.characters);
480
- const gone = [...was].filter(id => !now.has(id));
481
- if (gone.length === 0) return;
482
- const bh = after.behaviors;
483
- const isV2 = bh.schema_version != null;
484
- const chars = isV2 ? bh.characters : bh;
485
- for (const id of gone) {
486
- if (chars && typeof chars === 'object') delete chars[id];
487
- if (isV2 && Array.isArray(bh.rules)) {
488
- bh.rules = bh.rules.filter(r => !(r && r.scope === 'character' && r.character_id === id));
489
- }
490
- }
491
- }
492
-
493
522
  // ── Deterministic scene-participants guard ─────────
494
523
  // Models frequently produce `scene.participants` in the wrong shape when
495
524
  // editing (e.g. {"item": [...]} — a JSON-Schema `items` hallucination, or
@@ -500,13 +529,14 @@ module.exports = function(config, deps = {}) {
500
529
  // partial or malformed model patch can never leave the field broken:
501
530
  // - {"item": x} → unwrapped to x
502
531
  // - bare string → wrapped into an array
503
- // - display name (Юра) → mapped to its character_id (yura)
532
+ // - display name (Юра) → mapped to its hero id (yura) — the EXACT name
533
+ // (case-insensitive) of a hero, nothing fuzzy
504
534
  // - duplicates → removed, order preserved
505
535
  function normalizeBookParticipants(book) {
506
536
  if (!book || !Array.isArray(book.chapters)) return book;
507
537
  const lookup = new Map();
508
- if (Array.isArray(book.characters)) {
509
- for (const ch of book.characters) {
538
+ if (Array.isArray(book.heroes)) {
539
+ for (const ch of book.heroes) {
510
540
  if (!ch || typeof ch !== 'object') continue;
511
541
  const id = ch.id;
512
542
  if (typeof id === 'string' && id) {
@@ -554,49 +584,190 @@ module.exports = function(config, deps = {}) {
554
584
  // state. On violation the result is withheld (null) so no caller can
555
585
  // persist broken JSON; errors name the failing file/resource so the
556
586
  // assistant (or the user) can issue a corrective patch in the next turn.
557
- // ── Deterministic behavior.json v2 guard ───────────
558
- // In memory `behaviors` is schema v2 ({schema_version, rules, characters}).
559
- // Models (and older prompts) still write the v2.1 paths, so before the
560
- // patches run:
561
- // /behaviors/<character_id>[/...] → /behaviors/characters/<character_id>[/...]
562
- // add|replace /behaviors with a flat map (schema_version !== 2)
563
- // → the map becomes `characters`,
564
- // stored rules/schema_version survive.
565
- // Runs inside applyPatches, so every caller gets it. Reserved top-level
566
- // keys are never treated as character ids. A legacy
567
- // in-memory book (no schema_version) is left alone — it is migrated on save.
568
- const BEHAVIOR_RESERVED_KEYS = ['schema_version', 'rules', 'characters', 'defaults'];
569
- function normalizeBehaviorPatches(obj, patches) {
570
- const stored = obj && obj.behaviors;
571
- const isV2 = stored && typeof stored === 'object' && !Array.isArray(stored) && stored.schema_version != null;
572
- if (!isV2 || !Array.isArray(patches)) return patches;
573
- return patches.map((patch) => {
574
- if (!patch || typeof patch.path !== 'string') return patch;
575
- const p = patch.path;
576
- if (p === '/behaviors' && (patch.op === 'add' || patch.op === 'replace')) {
577
- const v = patch.value;
578
- if (v && typeof v === 'object' && !Array.isArray(v) && v.schema_version !== 2) {
579
- const characters = {};
580
- for (const [k, entry] of Object.entries(v)) {
581
- if (!BEHAVIOR_RESERVED_KEYS.includes(k)) characters[k] = entry;
587
+ // ── Hero path guard (VBOOK_FORMAT_V4 §8.2) ─────────
588
+ // `heroes` is an array in memory, but the segment after /heroes/ is a HERO
589
+ // ID, never an array index: the guard turns /heroes/<id>/… into
590
+ // /heroes/<index>/… before the patches run. Refused (with a hint):
591
+ // - the 3.1 maps /characters, /voices, /behaviors, /behavior_rules,
592
+ // /mentions, /behavior;
593
+ // - computed fields: /hero_issues, /scene_list, /heroes/<id>/rev;
594
+ // - replacing or removing the whole /heroes list (a stale list would
595
+ // wipe the cast) and indexes /heroes/-, /heroes/<n> addressing;
596
+ // - removing the narrator; changing a hero's id or schema;
597
+ // - writing voice.reference (only the hero card pins a reference).
598
+ // `add /heroes/<new_id>` appends a new hero (its value.id must be <new_id>).
599
+ const LEGACY_ROOTS = ['characters', 'voices', 'behaviors', 'behavior_rules', 'mentions', 'behavior'];
600
+ const COMPUTED_ROOTS = ['hero_issues', 'scene_list'];
601
+ const LEGACY_HINT = 'VBook 4 keeps every character in `heroes`: use /heroes/<hero_id>/… (for example /heroes/yura/behaviour/profile)';
602
+ function normalizeHeroPatches(book, patches) {
603
+ const errors = [];
604
+ const out = [];
605
+ const heroes = book && Array.isArray(book.heroes) ? book.heroes : null;
606
+ const indexOf = (id) => (heroes ? heroes.findIndex((h) => h && h.id === id) : -1);
607
+ const added = new Set();
608
+ for (const patch of Array.isArray(patches) ? patches : []) {
609
+ if (!patch || typeof patch.path !== 'string') { out.push(patch); continue; }
610
+ const parts = patch.path.split('/');
611
+ const root = parts[1];
612
+ if (LEGACY_ROOTS.includes(root)) {
613
+ errors.push(`Path ${patch.path} is not part of VBook 4. ${LEGACY_HINT}`);
614
+ continue;
615
+ }
616
+ if (COMPUTED_ROOTS.includes(root)) {
617
+ errors.push(`Path ${patch.path} is computed by the server and cannot be written`);
618
+ continue;
619
+ }
620
+ if (root !== 'heroes') { out.push(patch); continue; }
621
+ if (parts.length < 3 || parts[2] === '') {
622
+ errors.push(`Path ${patch.path}: the whole heroes list cannot be ${patch.op === 'remove' ? 'removed' : 'replaced'} — edit one hero: /heroes/<hero_id>/…`);
623
+ continue;
624
+ }
625
+ const heroId = parts[2];
626
+ const rest = parts.slice(3);
627
+ if (heroId === '-') {
628
+ errors.push(`Path ${patch.path}: heroes are addressed by id — add a new hero with add /heroes/<new_id>`);
629
+ continue;
630
+ }
631
+ if (!/^[a-z0-9]+(?:_[a-z0-9]+)*$/.test(heroId) || heroId.length > 64) {
632
+ errors.push(`Path ${patch.path}: "${heroId}" is not a hero id (latin snake_case; the segment after /heroes/ is an id, not an index)`);
633
+ continue;
634
+ }
635
+ const field = rest[0];
636
+ if (field === 'id' || field === 'schema' || field === 'rev') {
637
+ errors.push(`Path ${patch.path}: ${field} of a hero cannot be changed`);
638
+ continue;
639
+ }
640
+ if (field === 'voice' && (rest[1] === 'reference' || ((patch.op === 'add' || patch.op === 'replace') && rest.length === 1
641
+ && patch.value && typeof patch.value === 'object' && 'reference' in patch.value))) {
642
+ errors.push(`Path ${patch.path}: voice.reference is pinned only from the hero card`);
643
+ continue;
644
+ }
645
+ const idx = indexOf(heroId);
646
+ if (rest.length === 0) {
647
+ if (patch.op === 'remove') {
648
+ if (heroId === 'narrator') { errors.push('The narrator cannot be removed'); continue; }
649
+ if (idx < 0) { errors.push(`Hero ${heroId} not found`); continue; }
650
+ out.push({ ...patch, path: `/heroes/${idx}` });
651
+ continue;
652
+ }
653
+ const value = patch.value;
654
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
655
+ errors.push(`Path ${patch.path}: a hero is an object`);
656
+ continue;
657
+ }
658
+ if (value.id !== undefined && value.id !== heroId) {
659
+ errors.push(`Path ${patch.path}: value.id "${value.id}" differs from the id in the path`);
660
+ continue;
661
+ }
662
+ if (value.voice && typeof value.voice === 'object' && 'reference' in value.voice) {
663
+ const current = idx >= 0 ? heroes[idx] : null;
664
+ const same = current && current.voice && JSON.stringify(current.voice.reference) === JSON.stringify(value.voice.reference);
665
+ if (!same) { errors.push(`Path ${patch.path}: voice.reference is pinned only from the hero card`); continue; }
666
+ }
667
+ const hero = { schema: 'animastor.character/1', ...value, id: heroId };
668
+ if (patch.op === 'add' && idx < 0 && !added.has(heroId)) {
669
+ added.add(heroId);
670
+ out.push({ op: 'add', path: '/heroes/-', value: hero });
671
+ continue;
672
+ }
673
+ if (idx < 0) { errors.push(`Hero ${heroId} not found`); continue; }
674
+ out.push({ op: 'replace', path: `/heroes/${idx}`, value: hero });
675
+ continue;
676
+ }
677
+ if (idx < 0) { errors.push(`Hero ${heroId} not found (add it first: add /heroes/${heroId})`); continue; }
678
+ out.push({ ...patch, path: `/heroes/${idx}/${rest.join('/')}` });
679
+ }
680
+ return { patches: out, errors };
681
+ }
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');
582
723
  }
583
- return { ...patch, value: { ...stored, characters } };
584
724
  }
585
- return patch;
586
725
  }
587
- const m = /^\/behaviors\/([^/]+)(\/.*)?$/.exec(p);
588
- if (!m) return patch;
589
- const seg = m[1];
590
- if (BEHAVIOR_RESERVED_KEYS.includes(seg)) return patch;
591
- return { ...patch, path: `/behaviors/characters/${seg}${m[2] || ''}` };
592
- });
726
+ }
727
+ return book;
593
728
  }
594
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
+
595
765
  function applyPatchesValidated(obj, patches) {
596
766
  const { result, errors } = applyPatches(obj, patches);
597
767
  if (errors.length > 0) {
598
768
  return { result: null, errors, validation_errors: [] };
599
769
  }
770
+ assignMissingIds(result);
600
771
  // Deterministic guard: unwrap {"item": x}, map names → character_id,
601
772
  // dedupe — across ALL scenes, not just the ones the model patched.
602
773
  normalizeBookParticipants(result);
@@ -625,8 +796,12 @@ module.exports = function(config, deps = {}) {
625
796
  resolvePath,
626
797
  applyPatches,
627
798
  applyPatchesValidated,
628
- normalizeBehaviorPatches,
799
+ normalizeHeroPatches,
629
800
  normalizeBookParticipants,
801
+ assignMissingIds,
802
+ looksLikeChangeClaim,
803
+ EDIT_RETRY_PROMPT,
804
+ chatRequestExtras,
630
805
  validateBundleObject,
631
806
  toolDefinitions: {
632
807
  EDIT_BOOK_TOOL,