briyah 2.0.4 → 2.0.5

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.
Files changed (66) hide show
  1. package/README.md +12 -1
  2. package/data/common/config/markup +1 -1
  3. package/data/common/config/story_models.json +3 -3
  4. package/data/common/prompts/illustrator/describe_scene.prompt +4 -4
  5. package/data/common/prompts/perceive.prompt +1 -1
  6. package/data/packs/dnd5e/prompts/battle_master/perceive.prompt +1 -1
  7. package/data/packs/dnd5e/prompts/campaign_designer/perceive.prompt +1 -1
  8. package/data/packs/dnd5e/prompts/character_creator/perceive.prompt +795 -787
  9. package/data/packs/dnd5e/prompts/dungeon_master/defaults_config.json +2 -1
  10. package/data/packs/dnd5e/prompts/dungeon_master/perceive.prompt +1 -1
  11. package/data/packs/dnd5e/rooms/campaign.json +18 -15
  12. package/data/packs/dnd5e/rooms/table.json +17 -16
  13. package/dist-sdk/server/src/ai/LLM/anthropic.service.js +1 -1
  14. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +22 -0
  15. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +60 -16
  16. package/dist-sdk/server/src/ai/LLM/blank-image.d.ts +36 -0
  17. package/dist-sdk/server/src/ai/LLM/blank-image.js +80 -0
  18. package/dist-sdk/server/src/ai/LLM/deepseek.service.js +1 -1
  19. package/dist-sdk/server/src/ai/LLM/fal.service.js +1 -1
  20. package/dist-sdk/server/src/ai/LLM/googleai.service.js +1 -1
  21. package/dist-sdk/server/src/ai/LLM/grok.service.js +1 -1
  22. package/dist-sdk/server/src/ai/LLM/openai.service.js +1 -1
  23. package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +1 -1
  24. package/dist-sdk/server/src/ai/LLM/together.service.js +1 -1
  25. package/dist-sdk/server/src/ai/agent-config.d.ts +0 -1
  26. package/dist-sdk/server/src/ai/agent-store.service.js +2 -4
  27. package/dist-sdk/server/src/ai/agent.d.ts +1 -2
  28. package/dist-sdk/server/src/ai/agent.js +1 -3
  29. package/dist-sdk/server/src/app/user-service-factory.js +8 -2
  30. package/dist-sdk/server/src/app.controller.d.ts +33 -0
  31. package/dist-sdk/server/src/app.controller.js +93 -2
  32. package/dist-sdk/server/src/app.service.d.ts +49 -4
  33. package/dist-sdk/server/src/app.service.js +101 -16
  34. package/dist-sdk/server/src/auth/jwt-auth.guard.js +26 -0
  35. package/dist-sdk/server/src/packs/pack-instantiation.service.js +5 -0
  36. package/dist-sdk/server/src/packs/pack-manifest.d.ts +14 -0
  37. package/dist-sdk/server/src/packs/pack-manifest.js +11 -0
  38. package/dist-sdk/server/src/room/illustration/illustration.service.d.ts +211 -0
  39. package/dist-sdk/server/src/room/illustration/illustration.service.js +771 -0
  40. package/dist-sdk/server/src/room/illustration/illustration.types.d.ts +101 -0
  41. package/dist-sdk/server/src/room/illustration/illustration.types.js +2 -0
  42. package/dist-sdk/server/src/room/room-config.d.ts +58 -1
  43. package/dist-sdk/server/src/room/room-config.js +19 -0
  44. package/dist-sdk/server/src/room/room-factory.d.ts +8 -0
  45. package/dist-sdk/server/src/room/room-factory.js +11 -0
  46. package/dist-sdk/server/src/room/room-store.service.d.ts +8 -0
  47. package/dist-sdk/server/src/room/room-store.service.js +43 -2
  48. package/dist-sdk/server/src/room/room.d.ts +103 -1
  49. package/dist-sdk/server/src/room/room.js +240 -4
  50. package/dist-sdk/server/src/rpg/rpg.service.js +5 -1
  51. package/dist-sdk/server/src/story/story.service.d.ts +24 -65
  52. package/dist-sdk/server/src/story/story.service.js +105 -458
  53. package/dist-sdk/server/src/tools/core/illustrate.tool.d.ts +14 -0
  54. package/dist-sdk/server/src/tools/core/illustrate.tool.js +80 -0
  55. package/dist-sdk/server/src/tools/core/index.js +2 -1
  56. package/dist-sdk/server/src/tools/native-tool.types.d.ts +90 -0
  57. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +9 -0
  58. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +5 -0
  59. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +30 -0
  60. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +75 -0
  61. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +11 -2
  62. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +36 -5
  63. package/dist-sdk/server/src/tools/tool-execution.service.js +91 -21
  64. package/dist-sdk/shared/types/app.types.d.ts +43 -0
  65. package/dist-sdk/shared/types/app.types.js +15 -1
  66. package/package.json +1 -1
@@ -65,6 +65,7 @@ const yauzl = __importStar(require("yauzl"));
65
65
  const message_1 = require("../room/message");
66
66
  const errors_1 = require("../common/errors");
67
67
  const logger_1 = require("../common/logger");
68
+ const illustration_service_1 = require("../room/illustration/illustration.service");
68
69
  /**
69
70
  * Service handling business logic for stories
70
71
  * Works alongside StoryStoreService which handles persistence
@@ -78,13 +79,14 @@ let StoryService = class StoryService {
78
79
  userPaths;
79
80
  agentFactory;
80
81
  roomFactory;
82
+ illustration;
81
83
  // Map to store story-specific artifact services
82
84
  storyArtifactServices = new Map();
83
85
  // Tracks stories with an in-flight chapter progression so we can reject
84
86
  // concurrent calls. The UI disables the Next Chapter button, but that
85
87
  // protection is best-effort (double-click race, HTTP retry, multiple tabs).
86
88
  chaptersInProgress = new Set();
87
- constructor(storyStore, agentStore, roomStore, progressService, messageService, userPaths, agentFactory, roomFactory) {
89
+ constructor(storyStore, agentStore, roomStore, progressService, messageService, userPaths, agentFactory, roomFactory, illustration) {
88
90
  this.storyStore = storyStore;
89
91
  this.agentStore = agentStore;
90
92
  this.roomStore = roomStore;
@@ -93,6 +95,50 @@ let StoryService = class StoryService {
93
95
  this.userPaths = userPaths;
94
96
  this.agentFactory = agentFactory;
95
97
  this.roomFactory = roomFactory;
98
+ this.illustration = illustration;
99
+ }
100
+ /**
101
+ * Describes a story to the illustration pipeline.
102
+ *
103
+ * The indirection is what keeps existing stories untouched by the extraction:
104
+ * this reports the artifacts directory a story's images are already in and the
105
+ * `/api/stories/...` URL already baked into its saved message bodies, so
106
+ * nothing moves and no stored transcript goes stale.
107
+ */
108
+ illustrationTarget(storyId) {
109
+ const { agentsDir } = this.getStoryStorageDirs(storyId);
110
+ const artifacts = this.getStoryArtifactService(storyId);
111
+ const story = () => this.storyStore.getStory(storyId);
112
+ return {
113
+ key: storyId,
114
+ label: story()?.name ?? 'Story',
115
+ agentsDir,
116
+ artifacts,
117
+ imageUrl: (artifactId) => `/api/stories/${storyId}/artifacts/${artifactId}`,
118
+ imageName: (sequence) => `Story image - ${sequence}`,
119
+ scenario: () => story()?.scenario || '',
120
+ // A story is narrated, which is the wording describe_scene.prompt was
121
+ // written around; keeping this true renders it exactly as before.
122
+ narrated: true,
123
+ imageModelName: () => story()?.imageModelName,
124
+ agentIds: () => {
125
+ const s = story();
126
+ return {
127
+ illustratorAgentId: s?.illustratorAgentId,
128
+ artistAgentId: s?.artistAgentId,
129
+ artistEditAgentId: s?.artistEditAgentId,
130
+ };
131
+ },
132
+ saveAgentIds: (ids) => {
133
+ const s = story();
134
+ if (!s)
135
+ return;
136
+ s.illustratorAgentId = ids.illustratorAgentId;
137
+ s.artistAgentId = ids.artistAgentId;
138
+ s.artistEditAgentId = ids.artistEditAgentId;
139
+ this.storyStore.updateStoryMetadata(storyId, s);
140
+ },
141
+ };
96
142
  }
97
143
  /**
98
144
  * Gets the progress emitter for a story
@@ -446,20 +492,35 @@ let StoryService = class StoryService {
446
492
  }
447
493
  // Create artist agent (text-to-image: portraits and scene references) from
448
494
  // the entry's generation model.
449
- const artist = this.createArtistAgent(storyInfo.id, storyAgentsDir, storyArtifactService, imageModelName, 'Artist', 'generation');
495
+ const artist = this.illustration.createArtistAgent({
496
+ label: storyInfo.name,
497
+ agentsDir: storyAgentsDir,
498
+ artifacts: storyArtifactService,
499
+ imageModelName,
500
+ nickname: 'Artist',
501
+ variant: 'generation',
502
+ });
450
503
  // Create artist edit agent (image-to-image: story images with reference
451
504
  // images) from the same entry's editing model.
452
- const artistEdit = this.createArtistAgent(storyInfo.id, storyAgentsDir, storyArtifactService, imageModelName, 'Artist (Edit)', 'editing');
505
+ const artistEdit = this.illustration.createArtistAgent({
506
+ label: storyInfo.name,
507
+ agentsDir: storyAgentsDir,
508
+ artifacts: storyArtifactService,
509
+ imageModelName,
510
+ nickname: 'Artist (Edit)',
511
+ variant: 'editing',
512
+ });
453
513
  // Create illustrator agent (only if artist exists)
454
514
  let illustrator = null;
455
515
  if (artist) {
456
- illustrator = this.agentFactory.createAgent(modelConfig.moderatorService, `${storyTitle} - Illustrator`, // Agent name = "[story title] - [nickname]"
457
- 'Illustrator', 'Visual artist for generating scene illustrations', 'illustrator', modelConfig.moderatorModel, storyAgentsDir, storyArtifactService);
458
- illustrator.reasoningEffort = 'low';
459
- illustrator.maxHistoryMessages = 10;
460
- illustrator.promptCacheTTL = 60;
461
- illustrator.ownerRoomId = storyInfo.id;
462
- illustrator.save();
516
+ illustrator = this.illustration.createIllustratorAgent({
517
+ label: storyTitle,
518
+ agentsDir: storyAgentsDir,
519
+ artifacts: storyArtifactService,
520
+ service: modelConfig.moderatorService,
521
+ model: modelConfig.moderatorModel,
522
+ ownerRoomId: storyInfo.id,
523
+ });
463
524
  logger_1.logger.log(`Created illustrator agent: ${illustrator.agentName}`);
464
525
  }
465
526
  // PHASE 2: Create narrator agent
@@ -878,7 +939,10 @@ let StoryService = class StoryService {
878
939
  generateOpeningSceneImage(storyInfo, room) {
879
940
  return Promise.all(this.generateCharacterPortraits(storyInfo, room))
880
941
  .then(() => {
881
- return this.generateSceneIllustration(storyInfo.id, 'Opening Scene');
942
+ // The room holds the scenario as its situation at this point; the
943
+ // story's own copy is still empty, which is what used to reach the
944
+ // illustrator here.
945
+ return this.illustrateStorySituation(storyInfo.id, room, room.getSituation() || 'Opening Scene');
882
946
  })
883
947
  .then(() => {
884
948
  this.progressService.emitProgress(storyInfo.id, 'opening-scene', 'Generating opening scene image...');
@@ -2218,114 +2282,6 @@ let StoryService = class StoryService {
2218
2282
  logger_1.logger.log(`Updated portraits for ${changedAgents.length} characters`);
2219
2283
  }
2220
2284
  }
2221
- /**
2222
- * Looks up image model configuration by name for one variant. Each consolidated
2223
- * entry in image_models.json carries a `generation` block (text-to-image) and an
2224
- * `editing` block (image-to-image); this returns the service/model for the
2225
- * requested variant.
2226
- * @param modelName The name from image_models.json
2227
- * @param variant Which model to resolve: 'generation' or 'editing'
2228
- * @returns {service, model} or null if disabled/not found
2229
- */
2230
- getImageModelConfig(modelName, variant = 'generation') {
2231
- try {
2232
- // No model name → images disabled
2233
- if (!modelName) {
2234
- return null;
2235
- }
2236
- // Load image_models.json
2237
- const imageModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'image_models.json');
2238
- const imageModels = JSON.parse(fs.readFileSync(imageModelsPath, 'utf8'));
2239
- // Find selected entry
2240
- const entry = imageModels.find((m) => m.name === modelName);
2241
- if (!entry) {
2242
- logger_1.logger.warn(`Image model not found: ${modelName}`);
2243
- return null;
2244
- }
2245
- // Resolve the requested variant. "No images" (and any entry missing the
2246
- // variant) yields null, which disables that artist agent.
2247
- const variantConfig = entry[variant];
2248
- if (!variantConfig || !variantConfig.service || !variantConfig.model) {
2249
- logger_1.logger.log(`No ${variant} model for "${modelName}" (images disabled)`);
2250
- return null;
2251
- }
2252
- return {
2253
- service: variantConfig.service,
2254
- model: variantConfig.model,
2255
- };
2256
- }
2257
- catch (error) {
2258
- logger_1.logger.error('Error loading image model config:', error);
2259
- return null;
2260
- }
2261
- }
2262
- /**
2263
- * Looks up the image generation properties (API params plus centsPerImage)
2264
- * for an agent's model from image_models.json. This is read fresh at call
2265
- * time rather than stored on the Agent — only the modelName is persisted.
2266
- *
2267
- * @param agent The artist or artistEdit agent
2268
- * @returns The merged imageProperties to pass to generateImage/editImage,
2269
- * or an empty object if the model isn't in image_models.json
2270
- */
2271
- getImagePropertiesForAgent(agent) {
2272
- try {
2273
- const imageModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'image_models.json');
2274
- const imageModels = JSON.parse(fs.readFileSync(imageModelsPath, 'utf8'));
2275
- // The Artist (Edit) agent uses each entry's editing block; the Artist uses
2276
- // the generation block. The same model id can appear under both variants
2277
- // (e.g. GPT Image edits with itself), so resolve by the agent's role first.
2278
- const isEditAgent = (agent.agentNickname ?? '').toLowerCase().includes('edit');
2279
- const preferred = isEditAgent ? 'editing' : 'generation';
2280
- const fallback = isEditAgent ? 'generation' : 'editing';
2281
- const findVariant = (variant) => {
2282
- const entry = imageModels.find((m) => m[variant]?.model === agent.modelName);
2283
- return entry ? entry[variant] : null;
2284
- };
2285
- const variantConfig = findVariant(preferred) ?? findVariant(fallback);
2286
- if (!variantConfig) {
2287
- logger_1.logger.warn(`No image_models.json entry for "${agent.modelName}"; image generation may fail`);
2288
- return {};
2289
- }
2290
- return {
2291
- ...(variantConfig.imageProperties ?? {}),
2292
- ...(variantConfig.centsPerImage != null
2293
- ? { centsPerImage: variantConfig.centsPerImage }
2294
- : {}),
2295
- };
2296
- }
2297
- catch (error) {
2298
- logger_1.logger.error('Error loading image properties for agent:', error);
2299
- return {};
2300
- }
2301
- }
2302
- /**
2303
- * Creates the artist agent for a story
2304
- * The artist agent is persistent and saved to disk for cost tracking
2305
- * @param storyId The story ID
2306
- * @param storyAgentsDir The story agents directory
2307
- * @param storyArtifactService The story artifact service
2308
- * @param imageModelName The consolidated image model name from image_models.json
2309
- * @param nickname The agent nickname ('Artist' or 'Artist (Edit)')
2310
- * @param variant Which model of the entry to use: 'generation' or 'editing'
2311
- * @returns Artist agent
2312
- */
2313
- createArtistAgent(storyId, storyAgentsDir, storyArtifactService, imageModelName, nickname = 'Artist', variant = 'generation') {
2314
- const storyInfo = this.storyStore.getStory(storyId);
2315
- // Look up image model configuration for this variant
2316
- const imageConfig = this.getImageModelConfig(imageModelName, variant);
2317
- // If no valid config (or "No images"), return null
2318
- if (!imageConfig) {
2319
- logger_1.logger.log(`Artist agent creation skipped (${nickname}): images disabled`);
2320
- return null;
2321
- }
2322
- const artistAgent = this.agentFactory.createAgent(imageConfig.service, `${storyInfo.name} - ${nickname}`, nickname, 'AI artist for generating character portraits and scene illustrations', 'default', imageConfig.model, storyAgentsDir, storyArtifactService);
2323
- artistAgent.maxHistoryMessages = 10;
2324
- artistAgent.promptCacheTTL = 0;
2325
- artistAgent.save();
2326
- logger_1.logger.log(`Created artist agent: ${artistAgent.agentName} (${imageConfig.service}/${imageConfig.model})`);
2327
- return artistAgent;
2328
- }
2329
2285
  /**
2330
2286
  * Generates portrait image for a character
2331
2287
  * @param room The story room
@@ -2339,60 +2295,7 @@ let StoryService = class StoryService {
2339
2295
  const storyInfo = this.storyStore.getStory(storyId);
2340
2296
  const character = storyInfo.characters.find((c) => c.name === characterAgent.agentNickname);
2341
2297
  const characterProfile = profileArtifact?.body || character?.description || '';
2342
- return this.generatePortraitForName(storyId, characterAgent.agentNickname, characterProfile, characterAgent);
2343
- }
2344
- /**
2345
- * Generates a portrait for a character by name + profile, without requiring a character agent.
2346
- * Used for both real characters (delegated from generateCharacterPortrait) and for minor
2347
- * characters named by the illustrator that have no agent backing them.
2348
- *
2349
- * @param storyId The story ID
2350
- * @param characterName The character's display name (used for the Portrait - <name> artifact)
2351
- * @param characterProfile A profile or brief description used to author the visual prompt
2352
- * @param promptAgent Agent used to run describe_character. Defaults to the artist when omitted.
2353
- * @returns Artifact ID of the generated portrait, or null on failure
2354
- */
2355
- async generatePortraitForName(storyId, characterName, characterProfile, promptAgent) {
2356
- try {
2357
- if (!characterProfile) {
2358
- logger_1.logger.warn(`No profile for ${characterName}, skipping portrait`);
2359
- return null;
2360
- }
2361
- const storyInfo = this.storyStore.getStory(storyId);
2362
- const scenario = storyInfo?.scenario || '';
2363
- const storyArtifactService = this.getStoryArtifactService(storyId);
2364
- const artistAgent = await this.agentStore.getAgent(storyInfo.artistAgentId);
2365
- if (!artistAgent) {
2366
- logger_1.logger.warn(`Artist agent not found: ${storyInfo.artistAgentId}`);
2367
- return null;
2368
- }
2369
- // Ensure the artist saves images to this story's artifact service, not the default one.
2370
- artistAgent.artifactService = storyArtifactService;
2371
- const describeAgent = promptAgent || artistAgent;
2372
- const visualDescription = await describeAgent.preparedPrompt('describe_character', {
2373
- characterName,
2374
- characterProfile,
2375
- scenario,
2376
- }, false);
2377
- if (!visualDescription || typeof visualDescription !== 'string') {
2378
- logger_1.logger.warn(`Failed to generate visual description for ${characterName}`);
2379
- return null;
2380
- }
2381
- const imageResult = await artistAgent.generateImage(visualDescription, this.getImagePropertiesForAgent(artistAgent));
2382
- if (imageResult.error) {
2383
- return null;
2384
- }
2385
- artistAgent.save();
2386
- const artifactId = imageResult.artifactId;
2387
- storyArtifactService.renameArtifact(artifactId, `Portrait - ${characterName}`);
2388
- storyArtifactService.updateArtifactDescription(artifactId, visualDescription);
2389
- logger_1.logger.log(`Generated portrait for ${characterName}: ${artifactId}`);
2390
- return artifactId;
2391
- }
2392
- catch (error) {
2393
- logger_1.logger.error(`Error generating portrait for ${characterName}:`, error);
2394
- return null;
2395
- }
2298
+ return this.illustration.portrait(this.illustrationTarget(storyId), characterAgent.agentNickname, characterProfile, room, characterAgent);
2396
2299
  }
2397
2300
  async updateCharacterPortrait(room, characterAgent, storyId, updateDescription = false) {
2398
2301
  try {
@@ -2406,26 +2309,16 @@ let StoryService = class StoryService {
2406
2309
  logger_1.logger.warn(`No profile for ${characterAgent.agentNickname}, skipping appearance update`);
2407
2310
  return null;
2408
2311
  }
2409
- const storyArtifactService = this.getStoryArtifactService(storyId);
2410
- // Resolve the edit artist (may be absent when images are disabled
2411
- // for this story).
2412
- const artistEditAgent = storyInfo.artistEditAgentId
2413
- ? await this.agentStore.getAgent(storyInfo.artistEditAgentId)
2414
- : null;
2415
- const hasArtist = !!artistEditAgent;
2416
- if (artistEditAgent) {
2417
- artistEditAgent.artifactService = storyArtifactService;
2418
- }
2312
+ const target = this.illustrationTarget(storyId);
2313
+ // The edit artist may be absent when images are disabled for this story.
2314
+ const hasArtist = !!storyInfo.artistEditAgentId;
2419
2315
  // When we don't need to refresh the description and there's no
2420
2316
  // artist, there is nothing to do — bail before spending any tokens.
2421
2317
  if (!updateDescription && !hasArtist) {
2422
2318
  logger_1.logger.warn(`No edit artist configured for story ${storyId}, skipping portrait update`);
2423
2319
  return null;
2424
2320
  }
2425
- const portraitName = `Portrait - ${characterAgent.agentNickname}`;
2426
- const existingPortrait = hasArtist
2427
- ? storyArtifactService.listArtifacts().find((a) => a.name === portraitName)
2428
- : undefined;
2321
+ const existingPortrait = hasArtist && this.illustration.hasPortrait(target, characterAgent.agentNickname);
2429
2322
  // Fast path: image-only update (e.g. chapter progression) where the
2430
2323
  // character has no portrait yet — generate one from scratch without
2431
2324
  // running the update_portrait prompt.
@@ -2474,277 +2367,13 @@ let StoryService = class StoryService {
2474
2367
  logger_1.logger.warn(`No existing portrait for ${characterAgent.agentNickname}, generating from scratch`);
2475
2368
  return this.generateCharacterPortrait(room, characterAgent, storyId);
2476
2369
  }
2477
- const imageResult = await artistEditAgent.editImage(visualDescription, this.getImagePropertiesForAgent(artistEditAgent), [existingPortrait.artifactId]);
2478
- if (imageResult.error) {
2479
- return null;
2480
- }
2481
- storyArtifactService.deleteArtifact(existingPortrait.artifactId);
2482
- artistEditAgent.save();
2483
- const artifactId = imageResult.artifactId;
2484
- storyArtifactService.renameArtifact(artifactId, portraitName);
2485
- storyArtifactService.updateArtifactDescription(artifactId, visualDescription);
2486
- logger_1.logger.log(`Updated portrait for ${characterAgent.agentNickname}: ${artifactId}`);
2487
- return artifactId;
2370
+ return this.illustration.updatePortrait(target, characterAgent.agentNickname, visualDescription, room);
2488
2371
  }
2489
2372
  catch (error) {
2490
2373
  logger_1.logger.error(`Error updating portrait for ${characterAgent.agentNickname}:`, error);
2491
2374
  return null;
2492
2375
  }
2493
2376
  }
2494
- /**
2495
- * Generates scene illustrations based on narrator messages
2496
- */
2497
- async generateSceneIllustration(storyId, situation, allowReference = true, latestNarration) {
2498
- try {
2499
- // 1. Load story and illustrator agent
2500
- const story = this.storyStore.getStory(storyId);
2501
- if (!story?.illustratorAgentId) {
2502
- logger_1.logger.log('No illustrator configured');
2503
- return;
2504
- }
2505
- const illustrator = await this.agentStore.getAgent(story.illustratorAgentId);
2506
- const room = await this.roomStore.getRoom(story.roomId);
2507
- if (!illustrator || !room)
2508
- return;
2509
- // 2. Determine the narration to illustrate and add it to illustrator history.
2510
- // When called from updateStorySituation the triggering narration is passed
2511
- // in directly, because it has not been logged to the room yet (the situation
2512
- // is processed before the moderator relays the message). Other callers
2513
- // (opening scene, reference re-entry) illustrate the latest logged message.
2514
- let narrationText = latestNarration;
2515
- if (!narrationText) {
2516
- const allMessages = room.getLatestRoomMessages(0, true);
2517
- const latestMessage = allMessages[allMessages.length - 1];
2518
- if (!latestMessage) {
2519
- logger_1.logger.warn('No messages in room');
2520
- return;
2521
- }
2522
- narrationText = latestMessage.content;
2523
- }
2524
- // Add narration to illustrator history BEFORE calling prompt
2525
- // Agent maintains rolling window (maxHistoryMessages=10) automatically
2526
- // This leverages Anthropic prompt caching
2527
- illustrator.addToConversationHistory(narrationText, false);
2528
- // 3. Get existing scene artifacts
2529
- const storyArtifactService = this.getStoryArtifactService(storyId);
2530
- const allArtifacts = storyArtifactService.listArtifacts();
2531
- const existingScenes = allArtifacts
2532
- .filter((a) => a.name.startsWith('Scene - '))
2533
- .map((a) => ({
2534
- name: a.name.replace('Scene - ', ''),
2535
- description: a.description || '',
2536
- }));
2537
- // Build the candidate character list from Portrait artifacts so minor characters
2538
- // introduced by the illustrator on earlier turns are reused consistently. We don't
2539
- // touch storyInfo.characters here — those represent agent-backed characters and
2540
- // shouldn't include incidental NPCs named by the illustrator.
2541
- const portraitCharacters = allArtifacts
2542
- .filter((a) => a.name.startsWith('Portrait - '))
2543
- .map((a) => ({
2544
- name: a.name.replace('Portrait - ', ''),
2545
- description: a.description || '',
2546
- }));
2547
- let existingScenesString = existingScenes
2548
- .map((s) => `- ${s.name}: ${s.description}`)
2549
- .join('\n');
2550
- if (!existingScenesString)
2551
- existingScenesString =
2552
- 'No scene reference images have been created yet. (set isReference: true)';
2553
- const situationForScene = `${story.situationTime ? `${story.situationTime} - ` : ''}${story.situation}`;
2554
- let prompt = `**Current Situation**:\n ${situationForScene}\n\n**Existing Scenes**:\n ${existingScenesString}`;
2555
- // 4. Call describe_scene (narrator history already in conversation)
2556
- const sceneAnalysis = await illustrator.instructedPrompt(prompt, 'describe_scene', {
2557
- characters: portraitCharacters,
2558
- }, true, // Don't save this prompt to history
2559
- true);
2560
- illustrator.save();
2561
- if (!sceneAnalysis || !sceneAnalysis.createImage) {
2562
- logger_1.logger.log('Illustrator decided not to create an image for this situation');
2563
- return;
2564
- }
2565
- // 6. Handle response
2566
- if (sceneAnalysis.isReference) {
2567
- if (!allowReference) {
2568
- // Already generated a reference on this chain - stop to avoid an infinite loop.
2569
- logger_1.logger.warn(`Illustrator requested another reference (${sceneAnalysis.sceneName}) after one was just created; skipping to avoid loop`);
2570
- return;
2571
- }
2572
- // Generate scene reference, then call once more (with allowReference=false) to
2573
- // produce the actual story image using the newly created reference.
2574
- const referenceCreated = await this.generateSceneReference(storyId, sceneAnalysis.sceneName, sceneAnalysis.sceneDescription);
2575
- if (referenceCreated) {
2576
- await this.generateSceneIllustration(storyId, situation, false, latestNarration);
2577
- }
2578
- }
2579
- else {
2580
- // Ensure every named character has a portrait BEFORE generating the story image,
2581
- // so the Portrait lookup in generateStoryImage always finds a reference. Minor
2582
- // characters introduced by the illustrator come through newCharacters with a
2583
- // briefDescription we can feed into the agentless portrait path. We pass the
2584
- // illustrator as the prompt agent; describe_character.prompt is shipped in the
2585
- // illustrator folder for this purpose.
2586
- await this.ensureMinorCharacterPortraits(storyId, sceneAnalysis.characterNames || [], sceneAnalysis.newCharacters || [], portraitCharacters.map((c) => c.name), illustrator);
2587
- // Generate story image
2588
- await this.generateStoryImage(storyId, story.turnNumber, sceneAnalysis.imageCaption, sceneAnalysis.sceneName, sceneAnalysis.sceneDescription, sceneAnalysis.characterNames);
2589
- }
2590
- }
2591
- catch (error) {
2592
- logger_1.logger.error('Scene illustration error:', error);
2593
- // Non-blocking - don't throw
2594
- }
2595
- }
2596
- /**
2597
- * Ensures every character named by the illustrator has a Portrait artifact before the
2598
- * story image is generated. Names already present in existingPortraitNames are skipped.
2599
- * Unknown names must have a matching entry in newCharacters (providing briefDescription)
2600
- * — otherwise we cannot generate a portrait and the character is dropped from logging
2601
- * (generateStoryImage's existing fallback will then warn and skip them).
2602
- */
2603
- async ensureMinorCharacterPortraits(storyId, characterNames, newCharacters, existingPortraitNames, promptAgent) {
2604
- const existing = new Set(existingPortraitNames);
2605
- const descriptionsByName = new Map(newCharacters.map((c) => [c.name, c.briefDescription]));
2606
- for (const name of characterNames) {
2607
- if (existing.has(name))
2608
- continue;
2609
- const briefDescription = descriptionsByName.get(name);
2610
- if (!briefDescription) {
2611
- logger_1.logger.warn(`Illustrator named "${name}" but provided no newCharacters entry; portrait will be skipped`);
2612
- continue;
2613
- }
2614
- await this.generatePortraitForName(storyId, name, briefDescription, promptAgent);
2615
- }
2616
- }
2617
- /**
2618
- * Generates scene reference image (environment only)
2619
- */
2620
- async generateSceneReference(storyId, sceneName, sceneDescription) {
2621
- try {
2622
- logger_1.logger.log(`Generating scene reference: ${sceneName}`);
2623
- // Get artist agent by ID from story metadata
2624
- const storyInfo = this.storyStore.getStory(storyId);
2625
- if (!storyInfo || !storyInfo.artistAgentId) {
2626
- logger_1.logger.error(`Cannot generate scene reference: story ${storyId} has no artist agent`);
2627
- return false;
2628
- }
2629
- const artistAgent = await this.agentStore.getAgent(storyInfo.artistAgentId);
2630
- if (!artistAgent) {
2631
- logger_1.logger.error(`Artist agent not found: ${storyInfo.artistAgentId}`);
2632
- return false;
2633
- }
2634
- const storyArtifactService = this.getStoryArtifactService(storyId);
2635
- if (!storyArtifactService) {
2636
- logger_1.logger.error(`Story artifact service not found: ${storyId}`);
2637
- return false;
2638
- }
2639
- artistAgent.artifactService = storyArtifactService;
2640
- const imageResult = await artistAgent.generateImage(sceneDescription, this.getImagePropertiesForAgent(artistAgent));
2641
- if (imageResult.error) {
2642
- logger_1.logger.error(`Scene reference image generation failed for "${sceneName}":`, imageResult.error);
2643
- return false;
2644
- }
2645
- artistAgent.save();
2646
- const artifactId = imageResult.artifactId;
2647
- storyArtifactService.renameArtifact(artifactId, `Scene - ${sceneName}`);
2648
- storyArtifactService.updateArtifactDescription(artifactId, sceneDescription);
2649
- logger_1.logger.log(`Generated scene reference: ${sceneName} (${artifactId})`);
2650
- return true;
2651
- }
2652
- catch (error) {
2653
- logger_1.logger.error('Scene reference generation error:', error);
2654
- return false;
2655
- }
2656
- }
2657
- /**
2658
- * Generates story image (scene + characters)
2659
- */
2660
- async generateStoryImage(storyId, turnNumber, imageCaption, sceneName, sceneDescription, characterNames) {
2661
- try {
2662
- logger_1.logger.log(`Generating story image for turn ${turnNumber}`);
2663
- const storyArtifactService = this.getStoryArtifactService(storyId);
2664
- const allArtifacts = storyArtifactService.listArtifacts();
2665
- // Find scene reference
2666
- const sceneArtifact = allArtifacts.find((a) => a.name === `Scene - ${sceneName}`);
2667
- if (!sceneArtifact) {
2668
- logger_1.logger.warn(`Scene not found: ${sceneName}`);
2669
- return;
2670
- }
2671
- // Get artist agent by ID from story metadata
2672
- const storyInfo = this.storyStore.getStory(storyId);
2673
- if (!storyInfo || !storyInfo.artistAgentId) {
2674
- logger_1.logger.error(`Cannot generate story image: story ${storyId} has no artist agent`);
2675
- return;
2676
- }
2677
- const artistAgent = await this.agentStore.getAgent(storyInfo.artistAgentId);
2678
- if (!artistAgent) {
2679
- logger_1.logger.error(`Artist agent not found: ${storyInfo.artistAgentId}`);
2680
- return;
2681
- }
2682
- artistAgent.artifactService = storyArtifactService;
2683
- // Find character portraits, generating any that are missing
2684
- const room = await this.getStoryRoom(storyId);
2685
- const characterPortraitIds = [];
2686
- for (const charName of characterNames) {
2687
- // Re-read the artifact list each iteration so newly generated portraits are visible
2688
- const currentArtifacts = storyArtifactService.listArtifacts();
2689
- const portrait = currentArtifacts.find((a) => a.name === `Portrait - ${charName}`);
2690
- if (portrait) {
2691
- characterPortraitIds.push(portrait.artifactId);
2692
- }
2693
- else {
2694
- logger_1.logger.warn(`Portrait not found for ${charName}, generating now`);
2695
- const characterAgent = room
2696
- .getAgents()
2697
- .find((a) => a.agentNickname === charName);
2698
- if (characterAgent) {
2699
- const newPortraitId = await this.generateCharacterPortrait(room, characterAgent, storyId);
2700
- if (newPortraitId) {
2701
- characterPortraitIds.push(newPortraitId);
2702
- }
2703
- else {
2704
- logger_1.logger.warn(`Could not generate portrait for ${charName}, skipping`);
2705
- }
2706
- }
2707
- else {
2708
- logger_1.logger.warn(`No agent found for character ${charName}, skipping portrait`);
2709
- }
2710
- }
2711
- }
2712
- // Prepare reference images: scene + portraits
2713
- const referenceImageIds = [sceneArtifact.artifactId, ...characterPortraitIds];
2714
- const editAgent = storyInfo.artistEditAgentId
2715
- ? await this.agentStore.getAgent(storyInfo.artistEditAgentId)
2716
- : null;
2717
- if (editAgent) {
2718
- editAgent.artifactService = storyArtifactService;
2719
- }
2720
- const imageResult = referenceImageIds?.length && editAgent
2721
- ? await editAgent.editImage(sceneDescription, this.getImagePropertiesForAgent(editAgent), referenceImageIds)
2722
- : await artistAgent.generateImage(sceneDescription, this.getImagePropertiesForAgent(artistAgent));
2723
- if (imageResult.error) {
2724
- return;
2725
- }
2726
- artistAgent.save();
2727
- const artifactId = imageResult.artifactId;
2728
- storyArtifactService.renameArtifact(artifactId, `Story image - ${turnNumber}`);
2729
- storyArtifactService.updateArtifactDescription(artifactId, imageCaption);
2730
- logger_1.logger.log(`Generated story image: ${imageCaption} (${artifactId})`);
2731
- // Add image message to room
2732
- try {
2733
- const imgUrl = `/api/stories/${storyId}/artifacts/${artifactId}`;
2734
- const imageMarkdown = `![${imageCaption}](${imgUrl})`;
2735
- const imageMessage = new message_1.RoomMessage(imageCaption, app_types_1.MessageAction.SYSTEM, imageMarkdown);
2736
- room.addRoomMessage(imageMessage);
2737
- logger_1.logger.log(`Added story image message to room`);
2738
- }
2739
- catch (error) {
2740
- logger_1.logger.error('Error adding image message to room:', error);
2741
- // Don't throw - image was generated successfully
2742
- }
2743
- }
2744
- catch (error) {
2745
- logger_1.logger.error('Story image generation error:', error);
2746
- }
2747
- }
2748
2377
  /**
2749
2378
  * Parses the narrator's preamble into structured fields. Extracts each
2750
2379
  * tag's inner text (first occurrence, case-insensitive); missing tags
@@ -2855,11 +2484,27 @@ let StoryService = class StoryService {
2855
2484
  // Generate scene illustration (fire and forget). Pass the narration that
2856
2485
  // triggered this update — it isn't in the room transcript yet (the
2857
2486
  // situation is processed before the moderator relays the message).
2858
- this.generateSceneIllustration(storyId, situationText, true, latestNarration).catch((error) => {
2487
+ this.illustrateStorySituation(storyId, room, situationText, latestNarration).catch((error) => {
2859
2488
  logger_1.logger.error('Illustration generation error:', error);
2860
2489
  // Silently continue
2861
2490
  });
2862
2491
  }
2492
+ /**
2493
+ * Asks the shared illustration pipeline for a picture of the story's current
2494
+ * scene. The situation is passed in rather than read off the room: the room's
2495
+ * copy holds the narrator's raw four-tag preamble, while the story's is the
2496
+ * parsed inner text, and the illustrator wants the latter.
2497
+ */
2498
+ async illustrateStorySituation(storyId, room, situation, narration) {
2499
+ const story = this.storyStore.getStory(storyId);
2500
+ await this.illustration.illustrate(room, this.illustrationTarget(storyId), {
2501
+ situation,
2502
+ situationTime: story?.situationTime,
2503
+ narration,
2504
+ sequence: story?.turnNumber ?? 0,
2505
+ allowReference: true,
2506
+ });
2507
+ }
2863
2508
  /**
2864
2509
  * Generates a complete markdown document of the story
2865
2510
  * Includes metadata, all completed chapters, and current chapter in progress
@@ -2938,16 +2583,17 @@ let StoryService = class StoryService {
2938
2583
  }
2939
2584
  /**
2940
2585
  * Formats room messages as markdown text
2586
+ *
2587
+ * A message's situation is not printed. It restates where the scene stands,
2588
+ * which is useful live and merely repetitive on the page — the narrator sets one
2589
+ * often enough that the document filled up with headings.
2590
+ *
2941
2591
  * @param messages Array of room messages
2942
2592
  * @returns Formatted markdown string
2943
2593
  */
2944
2594
  formatMessagesToMarkdown(messages) {
2945
2595
  let text = '';
2946
2596
  for (const msg of messages) {
2947
- // Add situation updates as section headers
2948
- if (msg.situation) {
2949
- text += `### ${msg.situation}\n\n`;
2950
- }
2951
2597
  // For stories, actions are only 'system' or 'moderate'
2952
2598
  // In both cases, output sender and content
2953
2599
  text += `**${msg.sender}**: ${msg.content}\n\n`;
@@ -3055,5 +2701,6 @@ exports.StoryService = StoryService = __decorate([
3055
2701
  story_message_service_1.StoryMessageService,
3056
2702
  user_paths_service_1.UserPathsService,
3057
2703
  agent_factory_1.AgentFactory,
3058
- room_factory_1.RoomFactory])
2704
+ room_factory_1.RoomFactory,
2705
+ illustration_service_1.IllustrationService])
3059
2706
  ], StoryService);