@animastor/assistant 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,565 @@
1
+ // ======================================================
2
+ // @animastor/assistant — CHAT ENGINE
3
+ // ======================================================
4
+ // AI chat engine — system prompts, book context building,
5
+ // mode-specific tool definitions, AI response parsing,
6
+ // and JSON patch application.
7
+ //
8
+ // Physically extracted from backend/src/services/chat-engine.cjs
9
+ // (docs/architecture/ai-assistant-extraction.md). The bundle-contract
10
+ // validator arrives ONLY through injection (deps.validateBundleObject) —
11
+ // the host ../book/bundle-validator.cjs require is gone with the move;
12
+ // the composition root binds the shared validator instance. The AI
13
+ // assistant profile (persona) is host-owned CONTENT: the composition root
14
+ // READS the host markdown file and injects the resulting string via
15
+ // deps.aiProfile — the package never knows the path, the file name or the
16
+ // filesystem. The chat fallback base URL (an operator env knob) is passed
17
+ // as deps.aiApiBaseUrl.
18
+ // The package holds no host imports, no fs and no ambient env reads —
19
+ // pure Assistant logic only.
20
+
21
+ module.exports = function(config, deps = {}) {
22
+ const { validateBundleObject } = deps;
23
+ if (typeof validateBundleObject !== 'function') {
24
+ throw new Error('chatEngine: deps.validateBundleObject is required (composition-root bound)');
25
+ }
26
+ // AI assistant profile CONTENT — injected by the composition root (the
27
+ // host owns the persona file and reads it). Absent/empty → built-in
28
+ // fallback profile, the same behavior as the historical missing file.
29
+ const AI_PROFILE = typeof deps.aiProfile === 'string' ? deps.aiProfile.trim() : '';
30
+ // Chat fallback base URL — injected by the composition root (operator
31
+ // env knob). The literal default is the last-resort contract value.
32
+ const AI_API_BASE_URL = deps.aiApiBaseUrl || 'https://integrate.api.nvidia.com/v1';
33
+
34
+ // ── Mode-specific system prompts ──────────────────
35
+ const MODE_PROMPTS = {
36
+ 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.',
37
+ 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.',
38
+ edit: [
39
+ 'You are an Editor. You can modify scenes, characters, locations, behavior, and book structure.',
40
+ 'Use the `edit_book` tool to apply changes. Always confirm changes with the user before applying.',
41
+ '',
42
+ '## Scene Participants',
43
+ '`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": ...}.',
44
+ 'Example: `["yura", "svetlana"]` — NOT `["Юра", "yura"]` and NOT `{"item": ["yura", "svetlana"]}`.',
45
+ '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.',
46
+ '',
47
+ '## Character Behavior',
48
+ 'Each character can have a Behavior entry in the book data under `behaviors` (keyed by character_id).',
49
+ 'Behavior describes HOW a character acts — their mannerisms, habits, and reactions.',
50
+ '',
51
+ 'Behavior schema:',
52
+ '```json',
53
+ '{',
54
+ ' "<character_id>": {',
55
+ ' "baseline": "How the character normally behaves — characteristic manner of movement, expressions, gestures, posture, speech patterns.",',
56
+ ' "quirks": ["Repeated characteristic habit or mannerism."],',
57
+ ' "reactions": [',
58
+ ' {',
59
+ ' "trigger": "A situation or emotional state.",',
60
+ ' "reaction": "The observable behavioral response."',
61
+ ' }',
62
+ ' ]',
63
+ ' }',
64
+ '}',
65
+ '```',
66
+ '',
67
+ 'Field meanings:',
68
+ '- **baseline**: how the character behaves NORMALLY — characteristic manner of movement, expressions, gestures, posture, speech rhythm.',
69
+ '- **quirks**: recurring habits or mannerisms specific to this character (one string per entry).',
70
+ '- **reactions**: trigger→reaction patterns. `trigger` = situation or state; `reaction` = observable behavioral response.',
71
+ '',
72
+ 'When the user asks to create or modify character behavior:',
73
+ '1. Find the character by character_id from `characters` in the book data.',
74
+ '2. Study the character passport (appearance, clothes, description) to understand their personality.',
75
+ '3. Create behavior that matches the character personality — distinct, specific, believable.',
76
+ '4. Use `edit_book` to write to `/behaviors/{character_id}` with the full behavior object.',
77
+ '5. Do NOT create a new character. Do NOT modify passport or voice unless asked.',
78
+ '',
79
+ 'Example user request: "Придумай поведение для Юры и Светланы."',
80
+ 'Agent action: find characters Yuri and Svetlana, analyze passports, write individualized baseline/quirks/reactions via edit_book.',
81
+ ].join('\n'),
82
+ 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.',
83
+ extraction: 'You are an Extraction specialist. Extract structured entities from the text such as characters, objects, locations, and key terms.',
84
+ validation: 'You are a Validation specialist. Check book JSON for correctness, completeness, and integrity. Verify required fields, cross-references, scene links, and data consistency. Return a list of violations with severity levels.',
85
+ };
86
+
87
+ // ── Topic-specific system prompts ─────────────────
88
+ const TOPIC_PROMPTS = {
89
+ book: 'You are a creative assistant helping with a visual book project. Answer questions about the book, its plot, characters, and structure.',
90
+ 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.',
91
+ characters: 'You are a character development assistant. Help design, refine, and track characters for the visual book.',
92
+ script: 'You are a scriptwriting assistant. Help with plot structure, narrative flow, scene transitions, and story arc.',
93
+ };
94
+
95
+ /**
96
+ * Build a system prompt from structured fields (mode, topic, language, position).
97
+ * Replaces the client-side system prompt assembly in AiAssistantFragment.
98
+ */
99
+ function buildChatSystemPrompt({ mode, topic, lang, bookData, chapterId, sceneId, unitIndex, modelName }) {
100
+ const appName = 'Animastor';
101
+ const modeKey = mode || 'conversation';
102
+ const topicKey = topic || 'book';
103
+ const modePrompt = MODE_PROMPTS[modeKey] || MODE_PROMPTS.conversation;
104
+ const topicPrompt = TOPIC_PROMPTS[topicKey] || TOPIC_PROMPTS.book;
105
+
106
+ // Resolve position context from book data
107
+ let positionContext = '';
108
+ if (bookData) {
109
+ try {
110
+ const chapters = bookData.chapters || [];
111
+ // If chapterId is not provided, find the chapter that contains sceneId
112
+ // Modern lazy-book chapters carry `chapter_id`; legacy parse.js
113
+ // chapters carry `chapter`. Normalize so position context resolves
114
+ // for both formats.
115
+ const chIdOf = c => c.chapter_id ?? c.chapter;
116
+ const resolvedChapterId = chapterId || (sceneId
117
+ ? chIdOf(chapters.find(c => c.scenes?.some(s => s.scene_id === sceneId)))
118
+ : null);
119
+ if (!resolvedChapterId) { positionContext = ''; }
120
+ else {
121
+ const ch = chapters.find(c => chIdOf(c) === resolvedChapterId);
122
+ const isSpecial = ch?.type === 'cover' || ch?.type === 'prologue';
123
+ const chTitle = ch?.chapter_title || '';
124
+ let chName = chapterId;
125
+ if (isSpecial) {
126
+ chName = chTitle || ch?.type || chapterId;
127
+ } else if (chTitle) {
128
+ chName = chTitle;
129
+ } else if (ch?.display_number != null) {
130
+ chName = `Chapter ${ch.display_number}`;
131
+ }
132
+
133
+ let scName = '';
134
+ let unitDesc = '';
135
+ if (sceneId) {
136
+ const scenes = ch?.scenes || [];
137
+ const sc = scenes.find(s => s.scene_id === sceneId);
138
+ const scIdx = scenes.indexOf(sc) + 1;
139
+ if (scIdx > 0) {
140
+ const titleSuffix = sc?.scene_title ? ` — ${sc.scene_title}` : '';
141
+ scName = `Scene ${scIdx}${titleSuffix}`;
142
+ }
143
+ if (unitIndex != null && unitIndex >= 0) {
144
+ const units = sc?.units || [];
145
+ const unit = units[unitIndex];
146
+ if (unit) {
147
+ const typeLabel = unit.type ? unit.type.charAt(0).toUpperCase() + unit.type.slice(1) : 'Unit';
148
+ const textSnippet = unit.text ? unit.text.slice(0, 60).replace(/[\n\r]/g, ' ') : '';
149
+ unitDesc = textSnippet ? `${typeLabel} — "${textSnippet}"` : `${typeLabel} ${unitIndex + 1}`;
150
+ } else {
151
+ unitDesc = `Unit ${unitIndex + 1}`;
152
+ }
153
+ }
154
+ }
155
+
156
+ const parts = [`Current position: ${chName}`];
157
+ if (scName) parts.push(scName);
158
+ if (unitDesc) parts.push(unitDesc);
159
+ positionContext = parts.join(' / ');
160
+ }
161
+ } catch (_) {
162
+ // Silent fallback — position context is optional
163
+ }
164
+ }
165
+
166
+ // Language instruction
167
+ let langInstruction = '';
168
+ switch (lang) {
169
+ case 'ru':
170
+ langInstruction = '\n\nIMPORTANT: Always reply in Russian. Use Russian for all responses regardless of the user\'s language.';
171
+ break;
172
+ case 'en':
173
+ langInstruction = '';
174
+ break;
175
+ case 'auto':
176
+ default:
177
+ langInstruction = '\n\nIMPORTANT: Always reply in the user\'s language. If they write in Russian, reply in Russian. If they write in English, reply in English.';
178
+ break;
179
+ }
180
+
181
+ const parts = [
182
+ '## Identity',
183
+ `You are **${appName}** — an intelligent assistant for creating visual books on the Animastor platform.`,
184
+ `Always introduce yourself as ${appName}. When greeting users, say you are ${appName}, their visual book assistant — NOT any other AI assistant or service.`,
185
+ `Your AI model identifier is: ${modelName || 'AI model'}. If asked about your model, architecture, or origin, respond ONLY with this exact identifier. Never use any other model name.`,
186
+ '',
187
+ '## Mission',
188
+ 'Help users create, edit, and publish multimedia visual books. Assist with plot development, character design, scene structuring, and all aspects of the Animastor platform.',
189
+ '',
190
+ `Mode: ${modeKey.charAt(0).toUpperCase() + modeKey.slice(1)}`,
191
+ modePrompt,
192
+ '',
193
+ `Topic: ${topicKey.charAt(0).toUpperCase() + topicKey.slice(1)}`,
194
+ topicPrompt,
195
+ ];
196
+ if (positionContext) {
197
+ parts.push('');
198
+ parts.push(`Current context: ${positionContext}`);
199
+ }
200
+ if (langInstruction) {
201
+ parts.push('');
202
+ parts.push(langInstruction.trim());
203
+ }
204
+
205
+ return parts.join('\n');
206
+ }
207
+
208
+ // ── System prompt (fallback for legacy clients) ────
209
+ // The persona CONTENT is host-owned and injected as a ready string
210
+ // (deps.aiProfile) — the package has no fs, no path and no knowledge of
211
+ // the host persona file. No injected content → the built-in profile
212
+ // fallback, same as a missing file historically.
213
+ function loadSystemPrompt() {
214
+ if (AI_PROFILE) return AI_PROFILE;
215
+ return `# AI Assistant Profile: Анимастор
216
+
217
+ ## Identity
218
+ Ты — **Анимастор**, умный помощник для создания интерактивных историй и книг на платформе Animastor.
219
+
220
+ ## Mission
221
+ Ты помогаешь пользователям создавать, редактировать и публиковать мультимедийные книги.
222
+
223
+ ## Capabilities
224
+ - Помогаешь придумывать сюжеты, персонажей, диалоги и сценарии
225
+ - Разбиваешь текст на сцены, главы, описываешь визуальные и аудио-элементы
226
+ - Объясняешь формат .vbook и процесс генерации
227
+ - Отвечаешь на вопросы по платформе
228
+ - Предлагаешь креативные идеи
229
+
230
+ ## Rules
231
+ - Всегда представляешься как Анимастор
232
+ - Не выдаёшь себя за человека
233
+ - Отвечаешь на том же языке, на котором к тебе обратились
234
+ - Если вопрос вне твоей компетенции — честно говоришь об этом`;
235
+ }
236
+
237
+ // ── Book context builder ──────────────────────────
238
+ function buildBookContext(bookData) {
239
+ if (!bookData) return '';
240
+ const isLocked = bookData.manifest?.locked === true;
241
+ const lines = [];
242
+ lines.push(`Locked: ${isLocked}`);
243
+ lines.push('');
244
+ lines.push('Below is the full book JSON data. Read it, modify it as needed, and return the full changed version in your response.');
245
+ lines.push('');
246
+ lines.push('```json');
247
+ lines.push(JSON.stringify(bookData, null, 2));
248
+ lines.push('```');
249
+ return lines.join('\n');
250
+ }
251
+
252
+ /**
253
+ * Compact structural summary of the book — bounded well below the Local AI
254
+ * Connector per-message cap (32 KB, lib/chat.cjs maxMessageChars). Used
255
+ * when the full book JSON cannot ride the system message (connector
256
+ * transport): structure, ids and titles survive; unit texts are omitted.
257
+ * @param {object|null} bookData
258
+ * @returns {string} '' when no book data
259
+ */
260
+ function buildCompactBookContext(bookData) {
261
+ if (!bookData) return '';
262
+ const MAX_CHAPTERS = 40;
263
+ const MAX_SCENES_PER_CHAPTER = 40;
264
+ const lines = [];
265
+ lines.push('Full book JSON is too large for this transport — use this structural summary instead.');
266
+ lines.push(`Book: ${bookData.book?.title || bookData.manifest?.title || 'Untitled'}`);
267
+ lines.push(`Locked: ${bookData.manifest?.locked === true}`);
268
+ const characters = Array.isArray(bookData.characters) ? bookData.characters : [];
269
+ if (characters.length > 0) {
270
+ const names = characters.slice(0, 30).map((c) => `${c.id || c.character_id || '?'}${c.name ? ` (${c.name})` : ''}`).join(', ');
271
+ lines.push(`Characters: ${names}`);
272
+ }
273
+ const chapters = Array.isArray(bookData.chapters) ? bookData.chapters : [];
274
+ lines.push(`Chapters: ${chapters.length}`);
275
+ chapters.slice(0, MAX_CHAPTERS).forEach((ch, i) => {
276
+ const scenes = Array.isArray(ch.scenes) ? ch.scenes : [];
277
+ lines.push(`- Chapter ${i + 1}${ch.chapter_id ? ` [${ch.chapter_id}]` : ''}${ch.title ? ` "${ch.title}"` : ''}: ${scenes.length} scene(s)`);
278
+ scenes.slice(0, MAX_SCENES_PER_CHAPTER).forEach((sc, j) => {
279
+ lines.push(` - Scene ${j + 1} [${sc.scene_id || '?'}]${sc.scene_title ? ` "${sc.scene_title}"` : ''} (${sc.type || 'default'})`);
280
+ });
281
+ });
282
+ return lines.join('\n');
283
+ }
284
+
285
+ // ── Tool definitions ──────────────────────────────
286
+ const EDIT_BOOK_TOOL = {
287
+ type: 'function',
288
+ function: {
289
+ name: 'edit_book',
290
+ 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/{character_id} for character behavior. Do NOT call if the book is locked.',
291
+ parameters: {
292
+ type: 'object',
293
+ properties: {
294
+ patches: {
295
+ type: 'array',
296
+ description: 'List of JSON Patch operations',
297
+ items: {
298
+ type: 'object',
299
+ properties: {
300
+ op: { type: 'string', enum: ['replace', 'add', 'remove'], description: 'Operation type' },
301
+ path: { type: 'string', description: 'JSON path like /book/title, /chapters/0/scenes/1/units/0/text, /behaviors/character_id/baseline' },
302
+ value: { description: 'New value (for replace/add)' },
303
+ },
304
+ required: ['op', 'path'],
305
+ },
306
+ },
307
+ },
308
+ required: ['patches'],
309
+ },
310
+ },
311
+ };
312
+
313
+ // ── Mode-specific tool selection ──────────────────
314
+ // Only 'edit' carries a tool (EDIT_BOOK_TOOL — the one with a real
315
+ // backend handler). Every other mode is text-only: the remaining tool
316
+ // definitions (storyboard / import_book / extract_entities /
317
+ // validate_book) never had handlers (ai-routes.cjs replies
318
+ // 'Tool executed (no handler)'), so exposing them only taught models to
319
+ // burn tokens on calls that did nothing.
320
+ function getToolsForMode(mode, bookId, isLocked) {
321
+ if (mode === 'edit' && !isLocked) return [EDIT_BOOK_TOOL];
322
+ return [];
323
+ }
324
+
325
+ // ── AI response parsing ───────────────────────────
326
+ function parseAIResponse(text) {
327
+ if (!text) return { reply: '', patches: [] };
328
+
329
+ // Strip AI chain-of-thought reasoning blocks — not meant for the UI
330
+ text = text.replace(/<think>[\s\S]*?<\/think>/g, '').trim();
331
+
332
+ const patches = [];
333
+ const regex = /```patches\n([\s\S]*?)```/g;
334
+ let match;
335
+ let cleanText = text;
336
+
337
+ while ((match = regex.exec(text)) !== null) {
338
+ try {
339
+ const parsed = JSON.parse(match[1].trim());
340
+ if (Array.isArray(parsed)) {
341
+ patches.push(...parsed);
342
+ } else {
343
+ patches.push(parsed);
344
+ }
345
+ } catch (e) {
346
+ console.warn('[AI] Failed to parse patches block:', e.message);
347
+ }
348
+ cleanText = cleanText.replace(match[0], '').trim();
349
+ }
350
+
351
+ // Also look for inline JSON patches (single { ... } with op/path)
352
+ const inlineRegex = /\{(?:[^{}]|(?:\{[^{}]*\}))*\}/g;
353
+ let inlineMatch;
354
+ while ((inlineMatch = inlineRegex.exec(text)) !== null) {
355
+ try {
356
+ const parsed = JSON.parse(inlineMatch[0]);
357
+ if (parsed.op && parsed.path) {
358
+ patches.push(parsed);
359
+ }
360
+ } catch (e) { /* not a valid patch object */ }
361
+ }
362
+
363
+ return { reply: cleanText.trim(), patches };
364
+ }
365
+
366
+ // ── JSON path resolver ────────────────────────────
367
+ function resolvePath(obj, pathStr) {
368
+ const parts = pathStr.split('/').filter(Boolean);
369
+ let current = obj;
370
+ for (let i = 0; i < parts.length - 1; i++) {
371
+ const key = parts[i];
372
+ if (current[key] === undefined || current[key] === null) {
373
+ try {
374
+ const num = parseInt(key, 10);
375
+ if (!isNaN(num) && Array.isArray(current)) {
376
+ current = current[num];
377
+ } else {
378
+ current = current[key];
379
+ }
380
+ } catch {
381
+ return { parent: null, key: null, value: undefined };
382
+ }
383
+ } else {
384
+ current = current[key];
385
+ }
386
+ }
387
+ const lastKey = parts[parts.length - 1];
388
+ return { parent: current, key: lastKey, value: current ? current[lastKey] : undefined };
389
+ }
390
+
391
+ // ── JSON Patch application ────────────────────────
392
+ function applyPatches(obj, patches) {
393
+ const result = JSON.parse(JSON.stringify(obj));
394
+ const errors = [];
395
+
396
+ for (const patch of patches) {
397
+ const { op, path: pathStr, value } = patch;
398
+ const { parent, key, value: oldValue } = resolvePath(result, pathStr);
399
+
400
+ if (!parent && op !== 'add') {
401
+ errors.push(`Cannot resolve path: ${pathStr}`);
402
+ continue;
403
+ }
404
+
405
+ try {
406
+ switch (op) {
407
+ case 'replace':
408
+ if (key !== null && key in parent) {
409
+ parent[key] = value;
410
+ } else {
411
+ errors.push(`Path not found for replace: ${pathStr}`);
412
+ }
413
+ break;
414
+
415
+ case 'add':
416
+ if (key === '-') {
417
+ if (Array.isArray(parent)) {
418
+ parent.push(value);
419
+ } else {
420
+ errors.push(`Cannot append to non-array: ${pathStr}`);
421
+ }
422
+ } else if (key && key.match(/^\d+$/)) {
423
+ const idx = parseInt(key, 10);
424
+ if (Array.isArray(parent)) {
425
+ parent.splice(idx, 0, value);
426
+ } else {
427
+ errors.push(`Cannot insert at index in non-array: ${pathStr}`);
428
+ }
429
+ } else if (parent && key) {
430
+ parent[key] = value;
431
+ } else {
432
+ errors.push(`Invalid add path: ${pathStr}`);
433
+ }
434
+ break;
435
+
436
+ case 'remove':
437
+ if (key && key.match(/^\d+$/)) {
438
+ const idx = parseInt(key, 10);
439
+ if (Array.isArray(parent)) {
440
+ parent.splice(idx, 1);
441
+ } else {
442
+ errors.push(`Cannot remove index from non-array: ${pathStr}`);
443
+ }
444
+ } else if (parent && key && key in parent) {
445
+ delete parent[key];
446
+ } else {
447
+ errors.push(`Path not found for remove: ${pathStr}`);
448
+ }
449
+ break;
450
+
451
+ default:
452
+ errors.push(`Unknown operation: ${op}`);
453
+ }
454
+ } catch (e) {
455
+ errors.push(`Error applying ${op} at ${pathStr}: ${e.message}`);
456
+ }
457
+ }
458
+
459
+ return { result, errors };
460
+ }
461
+
462
+ // ── Deterministic scene-participants guard ─────────
463
+ // Models frequently produce `scene.participants` in the wrong shape when
464
+ // editing (e.g. {"item": [...]} — a JSON-Schema `items` hallucination, or
465
+ // display names ["Юра","yura"] instead of IDs). Left alone, those values
466
+ // would either corrupt the canonical state ({"item": ...} passed the old
467
+ // contract check) or leave the user's "IDs only" request half-done.
468
+ // This normalizer runs over EVERY scene after patches are applied, so a
469
+ // partial or malformed model patch can never leave the field broken:
470
+ // - {"item": x} → unwrapped to x
471
+ // - bare string → wrapped into an array
472
+ // - display name (Юра) → mapped to its character_id (yura)
473
+ // - duplicates → removed, order preserved
474
+ function normalizeBookParticipants(book) {
475
+ if (!book || !Array.isArray(book.chapters)) return book;
476
+ const lookup = new Map();
477
+ if (Array.isArray(book.characters)) {
478
+ for (const ch of book.characters) {
479
+ if (!ch || typeof ch !== 'object') continue;
480
+ const id = ch.id;
481
+ if (typeof id === 'string' && id) {
482
+ lookup.set(id.toLowerCase(), id);
483
+ if (typeof ch.name === 'string' && ch.name) {
484
+ lookup.set(ch.name.toLowerCase(), id);
485
+ }
486
+ }
487
+ }
488
+ }
489
+ const normalizeOne = (value) => {
490
+ if (value === null || value === undefined) return value;
491
+ let arr;
492
+ if (typeof value === 'object' && !Array.isArray(value) && value.item !== undefined) {
493
+ arr = value.item;
494
+ } else {
495
+ arr = value;
496
+ }
497
+ if (typeof arr === 'string') arr = [arr];
498
+ if (!Array.isArray(arr)) return value; // unfixable — left for the validator to reject
499
+ const out = [];
500
+ for (const item of arr) {
501
+ if (typeof item !== 'string') continue;
502
+ const s = item.trim();
503
+ if (!s) continue;
504
+ const resolved = lookup.get(s.toLowerCase()) || s;
505
+ if (!out.includes(resolved)) out.push(resolved);
506
+ }
507
+ return out;
508
+ };
509
+ for (const chapter of book.chapters) {
510
+ if (!chapter || typeof chapter !== 'object' || !Array.isArray(chapter.scenes)) continue;
511
+ for (const scene of chapter.scenes) {
512
+ if (scene && typeof scene === 'object' && 'participants' in scene) {
513
+ scene.participants = normalizeOne(scene.participants);
514
+ }
515
+ }
516
+ }
517
+ return book;
518
+ }
519
+
520
+ // ── Patch application with bundle-contract validation ──
521
+ // Pipeline: AI patch → apply ops → normalize participants → validate
522
+ // contract → only a valid result is returned as candidate canonical
523
+ // state. On violation the result is withheld (null) so no caller can
524
+ // persist broken JSON; errors name the failing file/resource so the
525
+ // assistant (or the user) can issue a corrective patch in the next turn.
526
+ function applyPatchesValidated(obj, patches) {
527
+ const { result, errors } = applyPatches(obj, patches);
528
+ if (errors.length > 0) {
529
+ return { result: null, errors, validation_errors: [] };
530
+ }
531
+ // Deterministic guard: unwrap {"item": x}, map names → character_id,
532
+ // dedupe — across ALL scenes, not just the ones the model patched.
533
+ normalizeBookParticipants(result);
534
+ const validation = validateBundleObject(result);
535
+ if (!validation.valid) {
536
+ return {
537
+ result: null,
538
+ errors: [`Bundle validation failed: ${validation.errors.join('; ')}`],
539
+ validation_errors: validation.errors,
540
+ };
541
+ }
542
+ return { result, errors, validation_errors: [] };
543
+ }
544
+
545
+ // `applyPatches` is kept exported for tests/legacy callers; AI mutation
546
+ // routes use `applyPatchesValidated` (see ai-routes.cjs).
547
+ return {
548
+ AI_PROFILE,
549
+ AI_API_BASE_URL,
550
+ loadSystemPrompt,
551
+ buildChatSystemPrompt,
552
+ buildBookContext,
553
+ buildCompactBookContext,
554
+ getToolsForMode,
555
+ parseAIResponse,
556
+ resolvePath,
557
+ applyPatches,
558
+ applyPatchesValidated,
559
+ normalizeBookParticipants,
560
+ validateBundleObject,
561
+ toolDefinitions: {
562
+ EDIT_BOOK_TOOL,
563
+ },
564
+ };
565
+ };
package/src/index.cjs ADDED
@@ -0,0 +1,66 @@
1
+ // ======================================================
2
+ // @animastor/assistant — PACKAGE ENTRYPOINT (public API)
3
+ // ======================================================
4
+ // The AI Assistant contour of the Animastor backend, physically extracted
5
+ // from the host (backend/src/services/chat-engine.cjs +
6
+ // backend/src/routes/ai-routes.cjs — deleted by the extraction commit;
7
+ // docs/architecture/ai-assistant-extraction.md).
8
+ //
9
+ // The package owns:
10
+ // - the chat ENGINE: persona/system prompt assembly, book context
11
+ // builders (full + compact), mode/topic prompts, the edit_book tool
12
+ // definition, AI response parsing and the JSON patch pipeline with
13
+ // bundle-contract validation (applyPatchesValidated) and the
14
+ // deterministic scene-participants normalizer;
15
+ // - the /api/v1/ai/* HTTP CONTOUR: session CRUD (list/get/create/rename/
16
+ // delete/messages), the non-streaming chat route and the SSE stream
17
+ // route (meta/delta/done/error contract unchanged), tool-call
18
+ // orchestration (structured + content-embedded), the connector
19
+ // shared-inference path and the cloud-provider path;
20
+ // - the CONTRACTS: the AssistantPorts interface (the host seam —
21
+ // loadBook/persistBook/validate/resolveChatAI/sessionRepo/purgeForBook/
22
+ // chatTransport/log) and the chat-session repository interface.
23
+ //
24
+ // The package imports NOTHING from the backend host: no config, no
25
+ // services, no middleware, no PG/Redis internals, no backend storage, no
26
+ // Book/lazyBook/bundle-validator requires, no host transport-service
27
+ // requires. Every host leg — book read/write, bundle
28
+ // validation, provider resolution, session persistence, the SSRF-guarded
29
+ // fetch, connector shared inference, the AI-source token mapping and the
30
+ // persona profile CONTENT — arrives as an injected dependency at
31
+ // registration time, wired at the composition root (backend.cjs).
32
+ //
33
+ // Public API:
34
+ // const { createChatEngine, createAssistantRoutes,
35
+ // assertAssistantPorts, assertSessionRepo } =
36
+ // require('@animastor/assistant');
37
+ // const chatEngine = createChatEngine(config, {
38
+ // validateBundleObject, // host bundle-validator binding
39
+ // aiProfile, // host persona CONTENT (host reads the file)
40
+ // aiApiBaseUrl, // optional chat fallback base URL (env knob)
41
+ // });
42
+ // createAssistantRoutes(app, redis, { chatEngine, assistantPorts, utils });
43
+ //
44
+ // This entrypoint is the ONLY public surface: the package.json export map
45
+ // exposes exactly this root ("." → "./src/index.cjs") and every other
46
+ // subpath is blocked. Host code must not deep-import internals
47
+ // (@animastor/assistant/...) — guarded by
48
+ // backend/tests/architecture/assistant-package-boundary.test.js.
49
+ //
50
+ // Guards: backend/tests/architecture/assistant-contour.test.js (A1–A7),
51
+ // backend/tests/architecture/assistant-package-boundary.test.js
52
+ // (PB1–PB4 — package closure, no reverse imports, manifest freeze),
53
+ // backend/tests/architecture/chat-transport.test.js (SSE/tools/
54
+ // abort contract on the moved contour).
55
+
56
+ const createChatEngine = require('./chat-engine.cjs');
57
+ const createAssistantRoutes = require('./assistant-routes.cjs');
58
+ const { assertAssistantPorts } = require('./assistant-ports-contract.cjs');
59
+ const { assertSessionRepo } = require('./session-repo-contract.cjs');
60
+
61
+ module.exports = {
62
+ createChatEngine,
63
+ createAssistantRoutes,
64
+ assertAssistantPorts,
65
+ assertSessionRepo,
66
+ };