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
@@ -0,0 +1,771 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
19
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
20
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
21
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
22
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
23
+ };
24
+ var __importStar = (this && this.__importStar) || (function () {
25
+ var ownKeys = function(o) {
26
+ ownKeys = Object.getOwnPropertyNames || function (o) {
27
+ var ar = [];
28
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
29
+ return ar;
30
+ };
31
+ return ownKeys(o);
32
+ };
33
+ return function (mod) {
34
+ if (mod && mod.__esModule) return mod;
35
+ var result = {};
36
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
37
+ __setModuleDefault(result, mod);
38
+ return result;
39
+ };
40
+ })();
41
+ var __metadata = (this && this.__metadata) || function (k, v) {
42
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.IllustrationService = void 0;
46
+ const common_1 = require("@nestjs/common");
47
+ const path = __importStar(require("path"));
48
+ const fs = __importStar(require("fs"));
49
+ const agent_factory_1 = require("../../ai/agent-factory");
50
+ const agent_store_service_1 = require("../../ai/agent-store.service");
51
+ const artifact_service_1 = require("../../ai/artifact.service");
52
+ const user_paths_service_1 = require("../../config/user-paths.service");
53
+ const app_types_1 = require("../../../../shared/types/app.types");
54
+ const logger_1 = require("../../common/logger");
55
+ const blank_image_1 = require("../../ai/LLM/blank-image");
56
+ const room_config_1 = require("../room-config");
57
+ const message_1 = require("../message");
58
+ /** Artifact name prefixes. The pipeline finds its own work by these. */
59
+ const SCENE_PREFIX = 'Scene - ';
60
+ const PORTRAIT_PREFIX = 'Portrait - ';
61
+ /**
62
+ * Turns a scene into a picture and posts it into the room.
63
+ *
64
+ * Lifted wholesale out of StoryService so that stories, RPG campaigns and plain
65
+ * rooms share one implementation. Everything that differs between them is behind
66
+ * {@link IllustrationTarget}; this class never learns what a story is.
67
+ *
68
+ * The shape of the pipeline, unchanged from where it came from:
69
+ *
70
+ * describe_scene → the illustrator decides whether a picture is warranted,
71
+ * names the setting, and writes the image prompt
72
+ * ├ new setting → draw a character-free reference, then run again on top of it
73
+ * └ known setting → make sure every named character has a portrait, then draw
74
+ * the scene with the reference and those portraits as inputs
75
+ * → post `![caption](url)` as a SYSTEM message, which notifies over SSE
76
+ *
77
+ * Nothing here throws at the caller. An illustration is a nicety; failing to make
78
+ * one must never take down the turn that asked for it.
79
+ */
80
+ let IllustrationService = class IllustrationService {
81
+ userPaths;
82
+ agentStore;
83
+ agentFactory;
84
+ /**
85
+ * Targets currently drawing, by key. An image takes minutes and the situation
86
+ * will change several times meanwhile, so overlapping requests are dropped
87
+ * rather than queued.
88
+ */
89
+ inFlight = new Set();
90
+ constructor(userPaths, agentStore, agentFactory) {
91
+ this.userPaths = userPaths;
92
+ this.agentStore = agentStore;
93
+ this.agentFactory = agentFactory;
94
+ }
95
+ /**
96
+ * Whether a picture is being drawn for this target right now.
97
+ * @param key The target key
98
+ */
99
+ isBusy(key) {
100
+ return this.inFlight.has(key);
101
+ }
102
+ /**
103
+ * Describes a plain room to the pipeline.
104
+ *
105
+ * Images go in an `images/` subdirectory rather than the room directory
106
+ * itself: `ArtifactService` keeps its index in `metadata.json`, and so does
107
+ * the room, so pointing one at the other would overwrite the room's config.
108
+ * Being inside the room directory does mean the existing recursive delete
109
+ * takes the images with the room, which is what we want.
110
+ *
111
+ * The three agent ids go in a sidecar beside those images, never in
112
+ * `RoomConfig`. `cloneRoomAsPublished` copies every setting verbatim into each
113
+ * published instance, so an id held as a setting would have a template and all
114
+ * its campaigns sharing one illustrator's rolling history and its costs.
115
+ */
116
+ targetFor(room) {
117
+ const imagesDir = path.join(room.getStorageDir(), room.getId(), 'images');
118
+ const artifacts = new artifact_service_1.ArtifactService(this.userPaths, imagesDir);
119
+ const sidecar = path.join(imagesDir, 'illustrator.json');
120
+ return {
121
+ key: room.getId(),
122
+ label: room.getName(),
123
+ // The agent store's own directory, NOT the room's. `room.getStorageDir()`
124
+ // is the *rooms* directory, so saving there writes agent files somewhere
125
+ // `AgentStoreService.getAgent` never looks — they resolve for as long as
126
+ // they are in memory and vanish on the next restart.
127
+ agentsDir: this.agentStore.getDefaultStorageDir(),
128
+ artifacts,
129
+ imageUrl: (artifactId) => `/api/rooms/${room.getId()}/images/${artifactId}`,
130
+ imageName: (sequence) => `Image - ${sequence}`,
131
+ scenario: () => room.getGoal() || '',
132
+ // A room has messages, not narration. StoryService's target says true.
133
+ narrated: false,
134
+ imageModelName: () => (0, room_config_1.resolveRoomImageModel)(room.getImageModel()),
135
+ // Borrow a text model from the room itself rather than adding another
136
+ // setting. The leader is the agent whose voice the pictures follow;
137
+ // its small model is the right tier for a mechanical prompt.
138
+ textModel: () => {
139
+ const leader = room
140
+ .getAgents()
141
+ .find((a) => a.agentNickname === room.getRoomLeader() && !a.isControlledByHuman);
142
+ const source = leader ?? room.getAgents().find((a) => !a.isControlledByHuman);
143
+ if (!source)
144
+ return null;
145
+ return {
146
+ service: source.serviceName,
147
+ model: source.smallModelName || source.modelName,
148
+ };
149
+ },
150
+ agentIds: () => this.readSidecar(sidecar),
151
+ saveAgentIds: (ids) => this.writeSidecar(sidecar, ids),
152
+ };
153
+ }
154
+ /**
155
+ * Builds the trio the first time a target actually needs one.
156
+ *
157
+ * Only for targets that supply a `textModel` — a story creates its agents up
158
+ * front, interleaved with its creation progress events, and must not have a
159
+ * second set conjured underneath it.
160
+ *
161
+ * @returns The new ids, or the target's existing ones when nothing was created
162
+ */
163
+ createAgentsFor(target) {
164
+ const existing = target.agentIds();
165
+ if (!target.textModel)
166
+ return existing;
167
+ const imageModelName = target.imageModelName();
168
+ if (!imageModelName)
169
+ return existing;
170
+ const text = target.textModel();
171
+ if (!text) {
172
+ logger_1.logger.warn(`No text model available to write image prompts for ${target.key}`);
173
+ return existing;
174
+ }
175
+ const artist = this.createArtistAgent({
176
+ label: target.label,
177
+ agentsDir: target.agentsDir,
178
+ artifacts: target.artifacts,
179
+ imageModelName,
180
+ nickname: 'Artist',
181
+ variant: 'generation',
182
+ ownerRoomId: target.key,
183
+ });
184
+ if (!artist)
185
+ return existing;
186
+ const artistEdit = this.createArtistAgent({
187
+ label: target.label,
188
+ agentsDir: target.agentsDir,
189
+ artifacts: target.artifacts,
190
+ imageModelName,
191
+ nickname: 'Artist (Edit)',
192
+ variant: 'editing',
193
+ ownerRoomId: target.key,
194
+ });
195
+ const illustrator = this.createIllustratorAgent({
196
+ label: target.label,
197
+ agentsDir: target.agentsDir,
198
+ artifacts: target.artifacts,
199
+ service: text.service,
200
+ model: text.model,
201
+ ownerRoomId: target.key,
202
+ });
203
+ const ids = {
204
+ illustratorAgentId: illustrator.id,
205
+ artistAgentId: artist.id,
206
+ artistEditAgentId: artistEdit?.id,
207
+ };
208
+ target.saveAgentIds(ids);
209
+ logger_1.logger.log(`Created illustration agents for ${target.key}`);
210
+ return ids;
211
+ }
212
+ readSidecar(file) {
213
+ try {
214
+ if (!fs.existsSync(file))
215
+ return {};
216
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
217
+ }
218
+ catch (error) {
219
+ logger_1.logger.warn(`Could not read illustration agents from ${file}: ${error}`);
220
+ return {};
221
+ }
222
+ }
223
+ writeSidecar(file, ids) {
224
+ try {
225
+ fs.mkdirSync(path.dirname(file), { recursive: true });
226
+ fs.writeFileSync(file, JSON.stringify(ids, null, 2), 'utf8');
227
+ }
228
+ catch (error) {
229
+ logger_1.logger.error(`Could not save illustration agents to ${file}:`, error);
230
+ }
231
+ }
232
+ /**
233
+ * Looks up image model configuration by name for one variant. Each consolidated
234
+ * entry in image_models.json carries a `generation` block (text-to-image) and an
235
+ * `editing` block (image-to-image); this returns the service/model for the
236
+ * requested variant.
237
+ * @param modelName The name from image_models.json
238
+ * @param variant Which model to resolve
239
+ * @returns {service, model}, or null when disabled or not found
240
+ */
241
+ getImageModelConfig(modelName, variant = 'generation') {
242
+ try {
243
+ // No model name → images disabled
244
+ if (!modelName) {
245
+ return null;
246
+ }
247
+ const imageModels = this.readImageModels();
248
+ const entry = imageModels.find((m) => m.name === modelName);
249
+ if (!entry) {
250
+ logger_1.logger.warn(`Image model not found: ${modelName}`);
251
+ return null;
252
+ }
253
+ // Resolve the requested variant. "No images" (and any entry missing the
254
+ // variant) yields null, which disables that artist agent.
255
+ const variantConfig = entry[variant];
256
+ if (!variantConfig || !variantConfig.service || !variantConfig.model) {
257
+ logger_1.logger.log(`No ${variant} model for "${modelName}" (images disabled)`);
258
+ return null;
259
+ }
260
+ return {
261
+ service: variantConfig.service,
262
+ model: variantConfig.model,
263
+ };
264
+ }
265
+ catch (error) {
266
+ logger_1.logger.error('Error loading image model config:', error);
267
+ return null;
268
+ }
269
+ }
270
+ /**
271
+ * Looks up the image generation properties (API params plus centsPerImage) for
272
+ * an agent's model. Read fresh at call time rather than stored on the Agent —
273
+ * only the modelName is persisted.
274
+ *
275
+ * The variant is passed explicitly rather than inferred from the agent's
276
+ * nickname. The same model id can appear under both variants (GPT Image edits
277
+ * with itself), so the caller's intent is the only reliable discriminator.
278
+ *
279
+ * @param agent The artist agent whose model to look up
280
+ * @param variant Which block of the entry the caller is about to use
281
+ * @returns The merged imageProperties, or {} when the model is not listed
282
+ */
283
+ getImageProperties(agent, variant) {
284
+ try {
285
+ const imageModels = this.readImageModels();
286
+ const other = variant === 'editing' ? 'generation' : 'editing';
287
+ const findVariant = (v) => {
288
+ const entry = imageModels.find((m) => m[v]?.model === agent.modelName);
289
+ return entry ? entry[v] : null;
290
+ };
291
+ const variantConfig = findVariant(variant) ?? findVariant(other);
292
+ if (!variantConfig) {
293
+ logger_1.logger.warn(`No image_models.json entry for "${agent.modelName}"; image generation may fail`);
294
+ return {};
295
+ }
296
+ return {
297
+ ...(variantConfig.imageProperties ?? {}),
298
+ ...(variantConfig.centsPerImage != null
299
+ ? { centsPerImage: variantConfig.centsPerImage }
300
+ : {}),
301
+ };
302
+ }
303
+ catch (error) {
304
+ logger_1.logger.error('Error loading image properties for agent:', error);
305
+ return {};
306
+ }
307
+ }
308
+ /**
309
+ * Creates an artist agent. Persistent and saved to disk, because its
310
+ * accumulated `totalCost` is how image spend is reported.
311
+ * @returns The agent, or null when this model has no such variant
312
+ */
313
+ createArtistAgent(opts) {
314
+ const nickname = opts.nickname ?? 'Artist';
315
+ const variant = opts.variant ?? 'generation';
316
+ const imageConfig = this.getImageModelConfig(opts.imageModelName, variant);
317
+ if (!imageConfig) {
318
+ logger_1.logger.log(`Artist agent creation skipped (${nickname}): images disabled`);
319
+ return null;
320
+ }
321
+ const artistAgent = this.agentFactory.createAgent(imageConfig.service, `${opts.label} - ${nickname}`, nickname, 'AI artist for generating character portraits and scene illustrations', 'default', imageConfig.model, opts.agentsDir, opts.artifacts);
322
+ artistAgent.maxHistoryMessages = 10;
323
+ artistAgent.promptCacheTTL = 0;
324
+ if (opts.ownerRoomId)
325
+ artistAgent.ownerRoomId = opts.ownerRoomId;
326
+ artistAgent.save();
327
+ logger_1.logger.log(`Created artist agent: ${artistAgent.agentName} (${imageConfig.service}/${imageConfig.model})`);
328
+ return artistAgent;
329
+ }
330
+ /**
331
+ * Creates the illustrator — the agent that writes the image prompt. A text
332
+ * agent, always: it never calls generateImage, and a ComfyUI-backed agent
333
+ * would throw on a text prompt.
334
+ */
335
+ createIllustratorAgent(opts) {
336
+ const illustrator = this.agentFactory.createAgent(opts.service, `${opts.label} - Illustrator`, 'Illustrator', 'Visual artist for generating scene illustrations', 'illustrator', opts.model, opts.agentsDir, opts.artifacts);
337
+ illustrator.reasoningEffort = 'low';
338
+ illustrator.maxHistoryMessages = 10;
339
+ illustrator.promptCacheTTL = 60;
340
+ if (opts.ownerRoomId)
341
+ illustrator.ownerRoomId = opts.ownerRoomId;
342
+ illustrator.save();
343
+ return illustrator;
344
+ }
345
+ /**
346
+ * Resolves the target's three agents.
347
+ *
348
+ * Re-points every one of them at the target's artifact service on every call.
349
+ * The alternative — setting it once at creation — is how images end up in the
350
+ * wrong directory the moment one agent serves two targets.
351
+ *
352
+ * @returns The trio, or null when the target has no illustrator or artist
353
+ */
354
+ async ensureAgents(target) {
355
+ let ids = target.agentIds();
356
+ if (!ids.illustratorAgentId || !ids.artistAgentId) {
357
+ ids = this.createAgentsFor(target);
358
+ }
359
+ if (!ids.illustratorAgentId || !ids.artistAgentId) {
360
+ logger_1.logger.log(`No illustrator configured for ${target.key}`);
361
+ return null;
362
+ }
363
+ const illustrator = await this.agentStore.getAgent(ids.illustratorAgentId);
364
+ const artist = await this.agentStore.getAgent(ids.artistAgentId);
365
+ if (!illustrator || !artist) {
366
+ logger_1.logger.warn(`Illustration agents missing for ${target.key}`);
367
+ return null;
368
+ }
369
+ const artistEdit = ids.artistEditAgentId
370
+ ? await this.agentStore.getAgent(ids.artistEditAgentId)
371
+ : null;
372
+ illustrator.artifactService = target.artifacts;
373
+ artist.artifactService = target.artifacts;
374
+ if (artistEdit)
375
+ artistEdit.artifactService = target.artifacts;
376
+ return { illustrator, artist, artistEdit };
377
+ }
378
+ /**
379
+ * The whole chain: decide, draw, post.
380
+ *
381
+ * @param room The room the picture belongs in
382
+ * @param target Where the images live and what they are called
383
+ * @param req What to draw
384
+ */
385
+ async illustrate(room, target, req) {
386
+ if (this.inFlight.has(target.key)) {
387
+ logger_1.logger.log(`Illustration already in flight for ${target.key}; skipping`);
388
+ return;
389
+ }
390
+ this.inFlight.add(target.key);
391
+ try {
392
+ await this.runIllustration(room, target, req);
393
+ }
394
+ catch (error) {
395
+ logger_1.logger.error('Scene illustration error:', error);
396
+ // Non-blocking — an image is never worth failing a turn over.
397
+ }
398
+ finally {
399
+ this.inFlight.delete(target.key);
400
+ }
401
+ }
402
+ /**
403
+ * One pass of the pipeline. Recurses into itself once, directly rather than
404
+ * back through {@link illustrate}, so the lock the caller holds stays held.
405
+ * @returns True when a picture reached the room
406
+ */
407
+ async runIllustration(room, target, req) {
408
+ const agents = await this.ensureAgents(target);
409
+ if (!agents)
410
+ return false;
411
+ const { illustrator } = agents;
412
+ // Count their spend against the room without letting them take turns in it.
413
+ room.attachAgent(illustrator);
414
+ room.attachAgent(agents.artist);
415
+ if (agents.artistEdit)
416
+ room.attachAgent(agents.artistEdit);
417
+ // The narration to illustrate. When the caller has it in hand (the
418
+ // triggering message has not been logged yet) it is passed in; otherwise
419
+ // illustrate whatever was said last.
420
+ let narrationText = req.narration;
421
+ if (!narrationText) {
422
+ const allMessages = room.getLatestRoomMessages(0, true);
423
+ const latestMessage = allMessages[allMessages.length - 1];
424
+ if (!latestMessage) {
425
+ logger_1.logger.warn('No messages in room');
426
+ return false;
427
+ }
428
+ narrationText = latestMessage.content;
429
+ }
430
+ // Into the rolling window (maxHistoryMessages=10) before prompting, so the
431
+ // cached prefix stays warm across turns.
432
+ illustrator.addToConversationHistory(narrationText, false);
433
+ const allArtifacts = target.artifacts.listArtifacts();
434
+ const existingScenes = allArtifacts
435
+ .filter((a) => a.name.startsWith(SCENE_PREFIX))
436
+ .map((a) => ({
437
+ name: a.name.replace(SCENE_PREFIX, ''),
438
+ description: a.description || '',
439
+ }));
440
+ // The candidate cast comes from Portrait artifacts rather than the room
441
+ // roster, so minor characters the illustrator named on an earlier turn are
442
+ // reused consistently instead of being reinvented.
443
+ const portraitCharacters = allArtifacts
444
+ .filter((a) => a.name.startsWith(PORTRAIT_PREFIX))
445
+ .map((a) => ({
446
+ name: a.name.replace(PORTRAIT_PREFIX, ''),
447
+ description: a.description || '',
448
+ }));
449
+ let existingScenesString = existingScenes
450
+ .map((s) => `- ${s.name}: ${s.description}`)
451
+ .join('\n');
452
+ if (!existingScenesString)
453
+ existingScenesString =
454
+ 'No scene reference images have been created yet. (set isReference: true)';
455
+ const situationForScene = `${req.situationTime ? `${req.situationTime} - ` : ''}${req.situation}`;
456
+ let prompt = `**Current Situation**:\n ${situationForScene}\n\n**Existing Scenes**:\n ${existingScenesString}`;
457
+ // What the agent that called `illustrate` asked to see. Appended rather than
458
+ // woven in, so the automatic path — which never sets it — renders exactly the
459
+ // prompt it always did and keeps the illustrator's cached prefix warm.
460
+ if (req.brief) {
461
+ prompt += `\n\n**Requested by ${req.requestedBy || 'an agent in the room'}**:\n ${req.brief}`;
462
+ if (req.subjects?.length) {
463
+ prompt += `\n\n**Who or what should appear**:\n ${req.subjects.join(', ')}`;
464
+ }
465
+ prompt +=
466
+ '\n\nThis was asked for deliberately, so prefer creating an image unless one ' +
467
+ 'just like it already exists.';
468
+ }
469
+ const sceneAnalysis = await illustrator.instructedPrompt(prompt, 'describe_scene', { characters: portraitCharacters, narrator: target.narrated }, true, // don't save this prompt to history
470
+ true);
471
+ illustrator.save();
472
+ if (!sceneAnalysis || !sceneAnalysis.createImage) {
473
+ logger_1.logger.log('Illustrator decided not to create an image for this situation');
474
+ return false;
475
+ }
476
+ if (sceneAnalysis.isReference) {
477
+ if (req.allowReference === false) {
478
+ // A reference was just created on this chain; another would loop.
479
+ logger_1.logger.warn(`Illustrator requested another reference (${sceneAnalysis.sceneName}) after one was just created; skipping to avoid loop`);
480
+ return false;
481
+ }
482
+ const referenceId = await this.generateSceneReference(target, sceneAnalysis.sceneName, sceneAnalysis.sceneDescription);
483
+ if (!referenceId)
484
+ return false;
485
+ const posted = await this.runIllustration(room, target, {
486
+ ...req,
487
+ allowReference: false,
488
+ });
489
+ if (posted)
490
+ return true;
491
+ // Nothing was drawn on top of the reference — with nobody in the scene
492
+ // there was nothing to add, so the illustrator declined. In a story that
493
+ // is right: the reference is an establishing asset and the story image
494
+ // is what the reader sees. In a room it is the whole picture, and
495
+ // leaving it on disk means an agent asked for one, the balance was
496
+ // charged, and the transcript showed nothing.
497
+ if (!target.narrated) {
498
+ this.postImageToRoom(room, target, referenceId, sceneAnalysis.imageCaption || sceneAnalysis.sceneName);
499
+ return true;
500
+ }
501
+ return false;
502
+ }
503
+ // Every named character needs a portrait BEFORE the scene is drawn, so the
504
+ // lookup below always finds a reference to hand the image model.
505
+ await this.ensureMinorCharacterPortraits(room, target, sceneAnalysis.characterNames || [], sceneAnalysis.newCharacters || [], portraitCharacters.map((c) => c.name), illustrator);
506
+ return this.generateSceneImage(room, target, {
507
+ sequence: req.sequence ?? 0,
508
+ imageCaption: sceneAnalysis.imageCaption,
509
+ sceneName: sceneAnalysis.sceneName,
510
+ sceneDescription: sceneAnalysis.sceneDescription,
511
+ characterNames: sceneAnalysis.characterNames,
512
+ });
513
+ }
514
+ /**
515
+ * Draws the setting with nobody in it, so later pictures of the same place can
516
+ * be built on top of it.
517
+ * @returns The stored artifact's id, or null when nothing was drawn
518
+ */
519
+ async generateSceneReference(target, sceneName, sceneDescription) {
520
+ try {
521
+ logger_1.logger.log(`Generating scene reference: ${sceneName}`);
522
+ const agents = await this.ensureAgents(target);
523
+ if (!agents)
524
+ return null;
525
+ const { artist } = agents;
526
+ const imageResult = await artist.generateImage(sceneDescription, this.getImageProperties(artist, 'generation'));
527
+ if (imageResult.error) {
528
+ return null;
529
+ }
530
+ artist.save();
531
+ const artifactId = imageResult.artifactId;
532
+ target.artifacts.renameArtifact(artifactId, `${SCENE_PREFIX}${sceneName}`);
533
+ target.artifacts.updateArtifactDescription(artifactId, sceneDescription);
534
+ logger_1.logger.log(`Generated scene reference: ${sceneName} (${artifactId})`);
535
+ return artifactId;
536
+ }
537
+ catch (error) {
538
+ logger_1.logger.error('Scene reference generation error:', error);
539
+ return null;
540
+ }
541
+ }
542
+ /**
543
+ * Draws the scene — the reference plus the characters in it — and posts it.
544
+ *
545
+ * The reference images are positional: the prompt tells the model that Image 1
546
+ * is the setting, Image 2 the first character, and so on, so the order here is
547
+ * part of the contract with `describe_scene.prompt`.
548
+ */
549
+ async generateSceneImage(room, target, scene) {
550
+ try {
551
+ logger_1.logger.log(`Generating image for ${target.key} (${scene.sequence})`);
552
+ const agents = await this.ensureAgents(target);
553
+ if (!agents)
554
+ return false;
555
+ const { artist, artistEdit } = agents;
556
+ const sceneArtifact = target.artifacts
557
+ .listArtifacts()
558
+ .find((a) => a.name === `${SCENE_PREFIX}${scene.sceneName}`);
559
+ if (!sceneArtifact) {
560
+ logger_1.logger.warn(`Scene not found: ${scene.sceneName}`);
561
+ return false;
562
+ }
563
+ const characterPortraitIds = this.collectPortraitIds(target, scene.characterNames || []);
564
+ const referenceImageIds = [sceneArtifact.artifactId, ...characterPortraitIds];
565
+ const imageResult = referenceImageIds.length && artistEdit
566
+ ? await artistEdit.editImage(scene.sceneDescription, this.getImageProperties(artistEdit, 'editing'), referenceImageIds)
567
+ : await artist.generateImage(scene.sceneDescription, this.getImageProperties(artist, 'generation'));
568
+ if (imageResult.error) {
569
+ return false;
570
+ }
571
+ artist.save();
572
+ artistEdit?.save();
573
+ const artifactId = imageResult.artifactId;
574
+ target.artifacts.renameArtifact(artifactId, target.imageName(scene.sequence));
575
+ target.artifacts.updateArtifactDescription(artifactId, scene.imageCaption);
576
+ logger_1.logger.log(`Generated image: ${scene.imageCaption} (${artifactId})`);
577
+ this.postImageToRoom(room, target, artifactId, scene.imageCaption);
578
+ return true;
579
+ }
580
+ catch (error) {
581
+ logger_1.logger.error('Image generation error:', error);
582
+ return false;
583
+ }
584
+ }
585
+ /**
586
+ * Puts the finished picture in the transcript.
587
+ *
588
+ * The caption goes in the sender slot, so it renders as the message's heading
589
+ * with the image as the body. `addRoomMessage` notifies over SSE, which is how
590
+ * this reaches clients despite arriving with no turn in progress.
591
+ */
592
+ postImageToRoom(room, target, artifactId, caption) {
593
+ try {
594
+ const markdown = `![${caption}](${target.imageUrl(artifactId)})`;
595
+ room.addRoomMessage(new message_1.RoomMessage(caption, app_types_1.MessageAction.SYSTEM, markdown));
596
+ logger_1.logger.log('Added image message to room');
597
+ }
598
+ catch (error) {
599
+ logger_1.logger.error('Error adding image message to room:', error);
600
+ // Don't throw — the image was generated successfully.
601
+ }
602
+ }
603
+ /**
604
+ * Tells the room that a face could not be drawn.
605
+ *
606
+ * SYSTEM rather than the free TOOL notice, which `getLatestRoomMessages` filters
607
+ * out unless the reader has thoughts turned on. A picture that silently never
608
+ * arrives is the thing being fixed here, so the line has to be one a person sees
609
+ * by default — the same way the finished picture is posted.
610
+ *
611
+ * @param portraitKept Whether an existing likeness survived the failure, which
612
+ * is the half of the news that decides what the reader should do next
613
+ */
614
+ postPortraitFailure(room, characterName, error, portraitKept) {
615
+ const cause = error instanceof blank_image_1.BlankImageError
616
+ ? 'the image model returned a blank image, which usually means it refused the description'
617
+ : `the image model failed (${this.describeError(error)})`;
618
+ const outcome = portraitKept
619
+ ? 'The existing portrait has been kept.'
620
+ : 'They have no portrait yet.';
621
+ try {
622
+ room.addRoomMessage(new message_1.RoomMessage('Illustrator', app_types_1.MessageAction.SYSTEM, `Could not draw a portrait for ${characterName}: ${cause}. ${outcome}`));
623
+ }
624
+ catch (postError) {
625
+ logger_1.logger.error('Error adding portrait failure message to room:', postError);
626
+ }
627
+ }
628
+ /** One clipped line of an error, for a notice a person reads. */
629
+ describeError(error) {
630
+ const text = error instanceof Error ? error.message : String(error);
631
+ const line = text.split('\n')[0].trim();
632
+ return line.length > 200 ? `${line.slice(0, 200)}...` : line || 'no reason given';
633
+ }
634
+ /** Resolves each named character to a Portrait artifact id, warning on misses. */
635
+ collectPortraitIds(target, characterNames) {
636
+ const ids = [];
637
+ for (const charName of characterNames) {
638
+ const portrait = target.artifacts
639
+ .listArtifacts()
640
+ .find((a) => a.name === `${PORTRAIT_PREFIX}${charName}`);
641
+ if (portrait) {
642
+ ids.push(portrait.artifactId);
643
+ }
644
+ else {
645
+ logger_1.logger.warn(`Portrait not found for ${charName}, skipping`);
646
+ }
647
+ }
648
+ return ids;
649
+ }
650
+ /**
651
+ * Draws a portrait from a name and a written profile, with no agent needed
652
+ * behind the character. Used both for real cast members and for the incidental
653
+ * people the illustrator names as it goes.
654
+ *
655
+ * @param room Where the notice goes when nothing could be drawn
656
+ * @param promptAgent Runs `describe_character`. Defaults to the artist, but the
657
+ * illustrator is the better choice — the prompt ships in its folder for this.
658
+ * @returns The artifact id, or null on any failure
659
+ */
660
+ async portrait(target, characterName, characterProfile, room, promptAgent) {
661
+ try {
662
+ if (!characterProfile) {
663
+ logger_1.logger.warn(`No profile for ${characterName}, skipping portrait`);
664
+ return null;
665
+ }
666
+ const agents = await this.ensureAgents(target);
667
+ if (!agents)
668
+ return null;
669
+ const { artist, illustrator } = agents;
670
+ // The illustrator by default: `describe_character` ships in its folder,
671
+ // and the artist is a ComfyUI-backed agent in most rooms, which throws
672
+ // on a text prompt. Every caller that has a better-informed agent — a
673
+ // story hands its own character — passes one.
674
+ const describeAgent = promptAgent || illustrator;
675
+ const visualDescription = await describeAgent.preparedPrompt('describe_character', {
676
+ characterName,
677
+ characterProfile,
678
+ scenario: target.scenario(),
679
+ }, false);
680
+ if (!visualDescription || typeof visualDescription !== 'string') {
681
+ logger_1.logger.warn(`Failed to generate visual description for ${characterName}`);
682
+ return null;
683
+ }
684
+ const imageResult = await artist.generateImage(visualDescription, this.getImageProperties(artist, 'generation'));
685
+ if (imageResult.error) {
686
+ this.postPortraitFailure(room, characterName, imageResult.error, false);
687
+ return null;
688
+ }
689
+ artist.save();
690
+ const artifactId = imageResult.artifactId;
691
+ target.artifacts.renameArtifact(artifactId, `${PORTRAIT_PREFIX}${characterName}`);
692
+ target.artifacts.updateArtifactDescription(artifactId, visualDescription);
693
+ logger_1.logger.log(`Generated portrait for ${characterName}: ${artifactId}`);
694
+ return artifactId;
695
+ }
696
+ catch (error) {
697
+ logger_1.logger.error(`Error generating portrait for ${characterName}:`, error);
698
+ return null;
699
+ }
700
+ }
701
+ /**
702
+ * Redraws an existing portrait from a fresh visual prompt, replacing the old
703
+ * artifact. Falls back to drawing from scratch when there is nothing to edit.
704
+ */
705
+ async updatePortrait(target, characterName, visualDescription, room) {
706
+ try {
707
+ const agents = await this.ensureAgents(target);
708
+ if (!agents?.artistEdit)
709
+ return null;
710
+ const { artistEdit } = agents;
711
+ const portraitName = `${PORTRAIT_PREFIX}${characterName}`;
712
+ const existing = target.artifacts
713
+ .listArtifacts()
714
+ .find((a) => a.name === portraitName);
715
+ if (!existing)
716
+ return null;
717
+ const imageResult = await artistEdit.editImage(visualDescription, this.getImageProperties(artistEdit, 'editing'), [existing.artifactId]);
718
+ if (imageResult.error) {
719
+ this.postPortraitFailure(room, characterName, imageResult.error, true);
720
+ return null;
721
+ }
722
+ target.artifacts.deleteArtifact(existing.artifactId);
723
+ artistEdit.save();
724
+ const artifactId = imageResult.artifactId;
725
+ target.artifacts.renameArtifact(artifactId, portraitName);
726
+ target.artifacts.updateArtifactDescription(artifactId, visualDescription);
727
+ logger_1.logger.log(`Updated portrait for ${characterName}: ${artifactId}`);
728
+ return artifactId;
729
+ }
730
+ catch (error) {
731
+ logger_1.logger.error(`Error updating portrait for ${characterName}:`, error);
732
+ return null;
733
+ }
734
+ }
735
+ /** True when this character already has a portrait. */
736
+ hasPortrait(target, characterName) {
737
+ return target.artifacts
738
+ .listArtifacts()
739
+ .some((a) => a.name === `${PORTRAIT_PREFIX}${characterName}`);
740
+ }
741
+ /**
742
+ * Gives every character the illustrator named a portrait before the scene is
743
+ * drawn. A name the illustrator invented without a matching `newCharacters`
744
+ * entry cannot be drawn, so it is warned about and left out.
745
+ */
746
+ async ensureMinorCharacterPortraits(room, target, characterNames, newCharacters, existingPortraitNames, promptAgent) {
747
+ const existing = new Set(existingPortraitNames);
748
+ const descriptionsByName = new Map(newCharacters.map((c) => [c.name, c.briefDescription]));
749
+ for (const name of characterNames) {
750
+ if (existing.has(name))
751
+ continue;
752
+ const briefDescription = descriptionsByName.get(name);
753
+ if (!briefDescription) {
754
+ logger_1.logger.warn(`Illustrator named "${name}" but provided no newCharacters entry; portrait will be skipped`);
755
+ continue;
756
+ }
757
+ await this.portrait(target, name, briefDescription, room, promptAgent);
758
+ }
759
+ }
760
+ readImageModels() {
761
+ const imageModelsPath = path.join(this.userPaths.getCommonConfigDir(), 'image_models.json');
762
+ return JSON.parse(fs.readFileSync(imageModelsPath, 'utf8'));
763
+ }
764
+ };
765
+ exports.IllustrationService = IllustrationService;
766
+ exports.IllustrationService = IllustrationService = __decorate([
767
+ (0, common_1.Injectable)(),
768
+ __metadata("design:paramtypes", [user_paths_service_1.UserPathsService,
769
+ agent_store_service_1.AgentStoreService,
770
+ agent_factory_1.AgentFactory])
771
+ ], IllustrationService);