@animastor/assistant 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.3.0 (2026-11-18, unpublished)
4
+
5
+ VBook 4 step 4 (animastor-docs `architecture/VBOOK_FORMAT_V4.md` §8.2). **Breaking.**
6
+
7
+ - `edit_book` addresses heroes by id: `/heroes/<hero_id>/…` — the segment after
8
+ `/heroes/` is an id, never an array index; the guard (`normalizeHeroPatches`,
9
+ inside `applyPatches`) turns it into the index. `add /heroes/<new_id>` appends a
10
+ hero. Refused with a hint: `/characters`, `/voices`, `/behaviors`,
11
+ `/behavior_rules`, `/mentions`, `/behavior`; computed `/hero_issues`,
12
+ `/scene_list`; replacing / removing the whole `/heroes`; index addressing;
13
+ the id / schema / rev of a hero; `voice.reference` (only the hero card pins a
14
+ reference); removing the narrator.
15
+ - `add` creates missing intermediate objects (`/heroes/<id>/behaviour/profile`).
16
+ - Edit-mode prompt and the `edit_book` tool describe heroes; participants are
17
+ mapped from `heroes` (exact name or id, case-insensitive — nothing fuzzy).
18
+ - Removed: `normalizeBehaviorPatches` and the character-delete cascade of
19
+ `behavior.json` v2 (rules live in the hero file and go with it).
20
+ - `chatRequestExtras(input, ai)` — the model extras plus the provider's
21
+ `disable_thinking` / `reasoning_effort` through the injected
22
+ `deps.withReasoning` (the host's `ai-reasoning.js`); both chat routes use it.
23
+ Without the injection the body is the one of 0.2.0.
24
+
3
25
  ## 0.2.0 (2026-11-10, unpublished)
4
26
 
5
27
  - 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.0",
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 {
@@ -492,7 +493,7 @@ module.exports = function(app, redis, deps) {
492
493
  messages: apiMessages,
493
494
  tools: tools.length > 0 ? tools : undefined,
494
495
  tool_choice: tools.length > 0 ? 'auto' : undefined,
495
- ...buildChatRequestExtras({ model: ai.model, baseUrl: ai.baseUrl, tools }),
496
+ ...chatEngine.chatRequestExtras({ model: ai.model, baseUrl: ai.baseUrl, tools }, ai),
496
497
  });
497
498
  clearTimeout(timeout);
498
499
 
@@ -1030,7 +1031,7 @@ module.exports = function(app, redis, deps) {
1030
1031
  messages: apiMessages,
1031
1032
  tools: tools.length > 0 ? tools : undefined,
1032
1033
  tool_choice: tools.length > 0 ? 'auto' : undefined,
1033
- ...buildChatRequestExtras({ model: ai.model, baseUrl: ai.baseUrl, tools }),
1034
+ ...chatEngine.chatRequestExtras({ model: ai.model, baseUrl: ai.baseUrl, tools }, ai),
1034
1035
  }));
1035
1036
  } finally {
1036
1037
  clearTimeout(timeout);
@@ -32,57 +32,67 @@ 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.',
51
+ 'You are an Editor. You can modify scenes, heroes, locations, behaviour, and book structure.',
42
52
  'Use the `edit_book` tool to apply changes. Always confirm changes with the user before applying.',
43
53
  '',
54
+ '## Heroes (VBook 4)',
55
+ 'Every character of the book — including the narrator — is a hero: one object in `heroes` (one file `characters/<id>.json`).',
56
+ 'A hero is addressed by its id, NEVER by an array index: `/heroes/<hero_id>/<field>`.',
57
+ 'Hero fields: `name`, `role`, `aliases` (how the author names the hero in the text), `notes` (for people only),',
58
+ '`passport` {appearance, clothes, video_tokens: 1-4 short visible features}, `looks` (named passport overrides),',
59
+ '`voice` {timbre, manner, reference}, `behaviour` {profile: {baseline, quirks, reactions}, rules: [...]}.',
60
+ 'Never write `voice.reference` (a pinned audio file — only the hero card pins it), `id`, `schema`, `rev` or `hero_issues`.',
61
+ 'A new hero: `add /heroes/<new_id>` with the whole hero object (`schema: "animastor.character/1"`, `id` equal to <new_id>).',
62
+ 'The narrator (`/heroes/narrator`) cannot be removed.',
63
+ 'The paths `/characters`, `/voices`, `/behaviors`, `/mentions` do not exist any more — they are refused.',
64
+ '',
44
65
  '## 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": ...}.',
66
+ '`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
67
  'Example: `["yura", "svetlana"]` — NOT `["Юра", "yura"]` and NOT `{"item": ["yura", "svetlana"]}`.',
47
68
  '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
69
  '',
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:',
70
+ '## Hero Behaviour',
71
+ 'The character of a hero lives in `/heroes/<hero_id>/behaviour/profile`:',
55
72
  '```json',
56
73
  '{',
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
- ' }',
74
+ ' "baseline": "How the hero normally behaves — characteristic manner of movement, expressions, gestures, posture, speech patterns.",',
75
+ ' "quirks": ["Repeated characteristic habit or mannerism."],',
76
+ ' "reactions": [',
77
+ ' { "trigger": "A situation or emotional state.", "reaction": "The observable behavioral response." }',
78
+ ' ]',
69
79
  '}',
70
80
  '```',
71
- '',
72
81
  '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).',
82
+ '- **baseline**: how the hero behaves NORMALLY — characteristic manner of movement, expressions, gestures, posture, speech rhythm.',
83
+ '- **quirks**: recurring habits or mannerisms specific to this hero (one string per entry).',
75
84
  '- **reactions**: trigger→reaction patterns. `trigger` = situation or state; `reaction` = observable behavioral response.',
85
+ 'Do not touch `behaviour.rules` unless the user explicitly asks about behaviour rules.',
76
86
  '',
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.',
87
+ 'When the user asks to create or modify the behaviour of a hero:',
88
+ '1. Find the hero by id (or by `name` / `aliases`) in `heroes`.',
89
+ '2. Study the passport (appearance, clothes) and notes to understand the personality.',
90
+ '3. Create behaviour that matches the personality — distinct, specific, believable.',
91
+ '4. Use `edit_book` with `add /heroes/<hero_id>/behaviour/profile` and the full profile object (add creates or replaces).',
92
+ '5. Do NOT create a new hero. Do NOT modify passport or voice unless asked.',
83
93
  '',
84
94
  'Example user request: "Придумай поведение для Юры и Светланы."',
85
- 'Agent action: find characters Yuri and Svetlana, analyze passports, write individualized baseline/quirks/reactions via edit_book.',
95
+ 'Agent action: find heroes yura and svetlana, analyze passports, write individualized baseline/quirks/reactions via edit_book.',
86
96
  ].join('\n'),
87
97
  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
98
  extraction: 'You are an Extraction specialist. Extract structured entities from the text such as characters, objects, locations, and key terms.',
@@ -93,7 +103,7 @@ module.exports = function(config, deps = {}) {
93
103
  const TOPIC_PROMPTS = {
94
104
  book: 'You are a creative assistant helping with a visual book project. Answer questions about the book, its plot, characters, and structure.',
95
105
  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.',
106
+ 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
107
  script: 'You are a scriptwriting assistant. Help with plot structure, narrative flow, scene transitions, and story arc.',
98
108
  };
99
109
 
@@ -270,10 +280,10 @@ module.exports = function(config, deps = {}) {
270
280
  lines.push('Full book JSON is too large for this transport — use this structural summary instead.');
271
281
  lines.push(`Book: ${bookData.book?.title || bookData.manifest?.title || 'Untitled'}`);
272
282
  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}`);
283
+ const heroes = Array.isArray(bookData.heroes) ? bookData.heroes : [];
284
+ if (heroes.length > 0) {
285
+ const names = heroes.slice(0, 30).map((h) => `${(h && h.id) || '?'}${h && h.name ? ` (${h.name})` : ''}`).join(', ');
286
+ lines.push(`Heroes: ${names}`);
277
287
  }
278
288
  const chapters = Array.isArray(bookData.chapters) ? bookData.chapters : [];
279
289
  lines.push(`Chapters: ${chapters.length}`);
@@ -292,7 +302,7 @@ module.exports = function(config, deps = {}) {
292
302
  type: 'function',
293
303
  function: {
294
304
  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.',
305
+ 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
306
  parameters: {
297
307
  type: 'object',
298
308
  properties: {
@@ -303,7 +313,7 @@ module.exports = function(config, deps = {}) {
303
313
  type: 'object',
304
314
  properties: {
305
315
  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' },
316
+ 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
317
  value: { description: 'New value (for replace/add)' },
308
318
  },
309
319
  required: ['op', 'path'],
@@ -393,13 +403,33 @@ module.exports = function(config, deps = {}) {
393
403
  return { parent: current, key: lastKey, value: current ? current[lastKey] : undefined };
394
404
  }
395
405
 
406
+ function ensureObjectParents(obj, pathStr) {
407
+ const parts = String(pathStr || '').split('/').filter(Boolean);
408
+ let current = obj;
409
+ for (let i = 0; i < parts.length - 1; i++) {
410
+ if (current === null || typeof current !== 'object') return;
411
+ const key = Array.isArray(current) && /^\d+$/.test(parts[i]) ? Number(parts[i]) : parts[i];
412
+ if (current[key] === undefined || current[key] === null) {
413
+ if (Array.isArray(current) || /^\d+$/.test(parts[i + 1]) || parts[i + 1] === '-') return;
414
+ current[key] = {};
415
+ }
416
+ current = current[key];
417
+ }
418
+ }
419
+
396
420
  // ── JSON Patch application ────────────────────────
397
421
  function applyPatches(obj, patches) {
398
422
  const result = JSON.parse(JSON.stringify(obj));
399
423
  const errors = [];
424
+ const guarded = normalizeHeroPatches(result, patches || []);
425
+ errors.push(...guarded.errors);
426
+ if (guarded.errors.length > 0) return { result, errors };
400
427
 
401
- for (const patch of normalizeBehaviorPatches(obj, patches || [])) {
428
+ for (const patch of guarded.patches) {
402
429
  const { op, path: pathStr, value } = patch;
430
+ // `add` creates missing intermediate OBJECTS (never arrays): adding
431
+ // /heroes/<id>/behaviour/profile to a hero without behaviour works
432
+ if (op === 'add') ensureObjectParents(result, pathStr);
403
433
  const { parent, key, value: oldValue } = resolvePath(result, pathStr);
404
434
 
405
435
  if (!parent && op !== 'add') {
@@ -461,35 +491,9 @@ module.exports = function(config, deps = {}) {
461
491
  }
462
492
  }
463
493
 
464
- cascadeDeletedCharacterBehaviors(obj, result);
465
494
  return { result, errors };
466
495
  }
467
496
 
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
497
  // ── Deterministic scene-participants guard ─────────
494
498
  // Models frequently produce `scene.participants` in the wrong shape when
495
499
  // editing (e.g. {"item": [...]} — a JSON-Schema `items` hallucination, or
@@ -500,13 +504,14 @@ module.exports = function(config, deps = {}) {
500
504
  // partial or malformed model patch can never leave the field broken:
501
505
  // - {"item": x} → unwrapped to x
502
506
  // - bare string → wrapped into an array
503
- // - display name (Юра) → mapped to its character_id (yura)
507
+ // - display name (Юра) → mapped to its hero id (yura) — the EXACT name
508
+ // (case-insensitive) of a hero, nothing fuzzy
504
509
  // - duplicates → removed, order preserved
505
510
  function normalizeBookParticipants(book) {
506
511
  if (!book || !Array.isArray(book.chapters)) return book;
507
512
  const lookup = new Map();
508
- if (Array.isArray(book.characters)) {
509
- for (const ch of book.characters) {
513
+ if (Array.isArray(book.heroes)) {
514
+ for (const ch of book.heroes) {
510
515
  if (!ch || typeof ch !== 'object') continue;
511
516
  const id = ch.id;
512
517
  if (typeof id === 'string' && id) {
@@ -554,42 +559,100 @@ module.exports = function(config, deps = {}) {
554
559
  // state. On violation the result is withheld (null) so no caller can
555
560
  // persist broken JSON; errors name the failing file/resource so the
556
561
  // 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;
582
- }
583
- return { ...patch, value: { ...stored, characters } };
562
+ // ── Hero path guard (VBOOK_FORMAT_V4 §8.2) ─────────
563
+ // `heroes` is an array in memory, but the segment after /heroes/ is a HERO
564
+ // ID, never an array index: the guard turns /heroes/<id>/… into
565
+ // /heroes/<index>/… before the patches run. Refused (with a hint):
566
+ // - the 3.1 maps /characters, /voices, /behaviors, /behavior_rules,
567
+ // /mentions, /behavior;
568
+ // - computed fields: /hero_issues, /scene_list, /heroes/<id>/rev;
569
+ // - replacing or removing the whole /heroes list (a stale list would
570
+ // wipe the cast) and indexes /heroes/-, /heroes/<n> addressing;
571
+ // - removing the narrator; changing a hero's id or schema;
572
+ // - writing voice.reference (only the hero card pins a reference).
573
+ // `add /heroes/<new_id>` appends a new hero (its value.id must be <new_id>).
574
+ const LEGACY_ROOTS = ['characters', 'voices', 'behaviors', 'behavior_rules', 'mentions', 'behavior'];
575
+ const COMPUTED_ROOTS = ['hero_issues', 'scene_list'];
576
+ const LEGACY_HINT = 'VBook 4 keeps every character in `heroes`: use /heroes/<hero_id>/… (for example /heroes/yura/behaviour/profile)';
577
+ function normalizeHeroPatches(book, patches) {
578
+ const errors = [];
579
+ const out = [];
580
+ const heroes = book && Array.isArray(book.heroes) ? book.heroes : null;
581
+ const indexOf = (id) => (heroes ? heroes.findIndex((h) => h && h.id === id) : -1);
582
+ const added = new Set();
583
+ for (const patch of Array.isArray(patches) ? patches : []) {
584
+ if (!patch || typeof patch.path !== 'string') { out.push(patch); continue; }
585
+ const parts = patch.path.split('/');
586
+ const root = parts[1];
587
+ if (LEGACY_ROOTS.includes(root)) {
588
+ errors.push(`Path ${patch.path} is not part of VBook 4. ${LEGACY_HINT}`);
589
+ continue;
590
+ }
591
+ if (COMPUTED_ROOTS.includes(root)) {
592
+ errors.push(`Path ${patch.path} is computed by the server and cannot be written`);
593
+ continue;
594
+ }
595
+ if (root !== 'heroes') { out.push(patch); continue; }
596
+ if (parts.length < 3 || parts[2] === '') {
597
+ errors.push(`Path ${patch.path}: the whole heroes list cannot be ${patch.op === 'remove' ? 'removed' : 'replaced'} — edit one hero: /heroes/<hero_id>/…`);
598
+ continue;
599
+ }
600
+ const heroId = parts[2];
601
+ const rest = parts.slice(3);
602
+ if (heroId === '-') {
603
+ errors.push(`Path ${patch.path}: heroes are addressed by id — add a new hero with add /heroes/<new_id>`);
604
+ continue;
605
+ }
606
+ if (!/^[a-z0-9]+(?:_[a-z0-9]+)*$/.test(heroId) || heroId.length > 64) {
607
+ errors.push(`Path ${patch.path}: "${heroId}" is not a hero id (latin snake_case; the segment after /heroes/ is an id, not an index)`);
608
+ continue;
609
+ }
610
+ const field = rest[0];
611
+ if (field === 'id' || field === 'schema' || field === 'rev') {
612
+ errors.push(`Path ${patch.path}: ${field} of a hero cannot be changed`);
613
+ continue;
614
+ }
615
+ if (field === 'voice' && (rest[1] === 'reference' || ((patch.op === 'add' || patch.op === 'replace') && rest.length === 1
616
+ && patch.value && typeof patch.value === 'object' && 'reference' in patch.value))) {
617
+ errors.push(`Path ${patch.path}: voice.reference is pinned only from the hero card`);
618
+ continue;
619
+ }
620
+ const idx = indexOf(heroId);
621
+ if (rest.length === 0) {
622
+ if (patch.op === 'remove') {
623
+ if (heroId === 'narrator') { errors.push('The narrator cannot be removed'); continue; }
624
+ if (idx < 0) { errors.push(`Hero ${heroId} not found`); continue; }
625
+ out.push({ ...patch, path: `/heroes/${idx}` });
626
+ continue;
627
+ }
628
+ const value = patch.value;
629
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
630
+ errors.push(`Path ${patch.path}: a hero is an object`);
631
+ continue;
632
+ }
633
+ if (value.id !== undefined && value.id !== heroId) {
634
+ errors.push(`Path ${patch.path}: value.id "${value.id}" differs from the id in the path`);
635
+ continue;
636
+ }
637
+ if (value.voice && typeof value.voice === 'object' && 'reference' in value.voice) {
638
+ const current = idx >= 0 ? heroes[idx] : null;
639
+ const same = current && current.voice && JSON.stringify(current.voice.reference) === JSON.stringify(value.voice.reference);
640
+ if (!same) { errors.push(`Path ${patch.path}: voice.reference is pinned only from the hero card`); continue; }
584
641
  }
585
- return patch;
642
+ const hero = { schema: 'animastor.character/1', ...value, id: heroId };
643
+ if (patch.op === 'add' && idx < 0 && !added.has(heroId)) {
644
+ added.add(heroId);
645
+ out.push({ op: 'add', path: '/heroes/-', value: hero });
646
+ continue;
647
+ }
648
+ if (idx < 0) { errors.push(`Hero ${heroId} not found`); continue; }
649
+ out.push({ op: 'replace', path: `/heroes/${idx}`, value: hero });
650
+ continue;
586
651
  }
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
- });
652
+ if (idx < 0) { errors.push(`Hero ${heroId} not found (add it first: add /heroes/${heroId})`); continue; }
653
+ out.push({ ...patch, path: `/heroes/${idx}/${rest.join('/')}` });
654
+ }
655
+ return { patches: out, errors };
593
656
  }
594
657
 
595
658
  function applyPatchesValidated(obj, patches) {
@@ -625,8 +688,9 @@ module.exports = function(config, deps = {}) {
625
688
  resolvePath,
626
689
  applyPatches,
627
690
  applyPatchesValidated,
628
- normalizeBehaviorPatches,
691
+ normalizeHeroPatches,
629
692
  normalizeBookParticipants,
693
+ chatRequestExtras,
630
694
  validateBundleObject,
631
695
  toolDefinitions: {
632
696
  EDIT_BOOK_TOOL,