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
@@ -23,7 +23,8 @@
23
23
  "stat_block",
24
24
  "magic_item",
25
25
  "spell",
26
- "rules_lookup"
26
+ "rules_lookup",
27
+ "illustrate"
27
28
  ],
28
29
  "documentIds": [
29
30
  "pack:dnd5e.dungeon_master-procedure"
@@ -138,7 +138,7 @@ Everyone hears what you say, but only the character you name responds.
138
138
  {{#each availableTools}}
139
139
  - **{{this.name}}**: {{this.description}}
140
140
  {{#each this.parameters}}
141
- - {{this.name}} ({{this.type}}{{#if this.required}}, required{{/if}}): {{this.description}}
141
+ - {{this.name}} ({{this.type}}{{#if this.required}}, required{{/if}}): {{this.description}}{{#if this.enumText}} Must be exactly one of: {{this.enumText}}.{{/if}}
142
142
  {{/each}}
143
143
  {{/each}}
144
144
  {{else}}
@@ -1,15 +1,18 @@
1
- {
2
- "key": "campaign",
3
- "name": "Campaign",
4
- "goal": "Play a fifth-edition campaign: the Dungeon Master runs the world, the Battle Master runs fights, and the players play their characters.",
5
- "turnMode": "directed",
6
- "agents": [
7
- "table_moderator",
8
- "dungeon_master",
9
- "battle_master",
10
- "character_creator",
11
- "campaign_designer"
12
- ],
13
- "roomLeader": "dungeon_master",
14
- "moderator": "table_moderator"
15
- }
1
+ {
2
+ "key": "campaign",
3
+ "name": "Campaign",
4
+ "goal": "Play a fifth-edition campaign: the Dungeon Master runs the world, the Battle Master runs fights, and the players play their characters.",
5
+ "turnMode": "directed",
6
+ "imageModel": "FLUX.1 Kontext",
7
+ "illustrationMode": "on-request",
8
+ "agents": [
9
+ "table_moderator",
10
+ "dungeon_master",
11
+ "battle_master",
12
+ "character_creator",
13
+ "campaign_designer"
14
+ ],
15
+ "roomLeader": "dungeon_master",
16
+ "moderator": "table_moderator",
17
+ "beginInstruction": "Session zero begins. The whole table is seated and waiting on you, and the roster is final. Follow your Before the first session procedure now."
18
+ }
@@ -1,16 +1,17 @@
1
- {
2
- "key": "table",
3
- "name": "D&D Table",
4
- "goal": "Play a fifth-edition campaign: the Dungeon Master runs the world, the Battle Master runs fights, and the players play their characters.",
5
- "turnMode": "directed",
6
- "agents": [
7
- "table_moderator",
8
- "dungeon_master",
9
- "battle_master",
10
- "character_creator",
11
- "campaign_designer",
12
- "player"
13
- ],
14
- "roomLeader": "dungeon_master",
15
- "moderator": "table_moderator"
16
- }
1
+ {
2
+ "key": "table",
3
+ "name": "D&D Table",
4
+ "goal": "Play a fifth-edition campaign: the Dungeon Master runs the world, the Battle Master runs fights, and the players play their characters.",
5
+ "turnMode": "directed",
6
+ "agents": [
7
+ "table_moderator",
8
+ "dungeon_master",
9
+ "battle_master",
10
+ "character_creator",
11
+ "campaign_designer",
12
+ "player"
13
+ ],
14
+ "roomLeader": "dungeon_master",
15
+ "moderator": "table_moderator",
16
+ "beginInstruction": "Session zero begins. The whole table is seated and waiting on you, and the roster is final. Follow your Before the first session procedure now."
17
+ }
@@ -228,7 +228,7 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
228
228
  // Instead, append the schema to the trailing prompt message (after the cached document) so
229
229
  // the system + document prefix stays byte-identical across calls. Without caching, keep the
230
230
  // schema in the system block (unchanged behavior).
231
- let instructionText = promptInstructions || agent.systemInstruction;
231
+ let instructionText = promptInstructions || this.getSystemInstruction(agent);
232
232
  if (jsonSchema && !cacheConfig) {
233
233
  instructionText += schemaInstruction;
234
234
  }
@@ -64,6 +64,22 @@ export declare class BaseAiService {
64
64
  */
65
65
  hasPromptFile(agent: Agent, fileName: string, extension?: string): boolean;
66
66
  getPreparedPrompt(agent: Agent, promptFileName: string, variables: any): string;
67
+ /**
68
+ * The agent's system instruction, resolved from its prompt folder per call.
69
+ *
70
+ * Read on every call for the same reason {@link getPreparedPrompt} re-reads its
71
+ * template: the folder's files are the source, so an edit reaches the next turn.
72
+ * A copy taken at creation could not — nothing in the API sets this field, so a
73
+ * stale copy stayed stale for the life of the agent.
74
+ *
75
+ * Reached only when the caller passes no instructions of its own. A room turn
76
+ * renders `perceive.prompt` and passes that, which *replaces* this rather than
77
+ * adding to it, so the read never happens on the hot path.
78
+ *
79
+ * @param agent The agent whose prompt folder is searched
80
+ * @returns The file's contents, or '' when the folder has no such file
81
+ */
82
+ protected getSystemInstruction(agent: Agent): string;
67
83
  protected getPreparedSchema(agent: Agent, promptFileName: string): any;
68
84
  /**
69
85
  * Lists available models from the AI service
@@ -138,6 +154,12 @@ export declare class BaseAiService {
138
154
  protected loadReferenceImages(agent: Agent, artifactIds: string[]): Promise<File[]>;
139
155
  /**
140
156
  * Helper: Save image from base64 data as artifact
157
+ *
158
+ * The one place every image from every provider passes through, which is why the
159
+ * blank-frame check lives here. A refusal comes back as a successful response
160
+ * holding no picture; throwing rather than storing it turns into `{ error }` in
161
+ * each provider's catch, and every caller already bails on that before it deletes
162
+ * the portrait the new image was meant to replace.
141
163
  */
142
164
  protected saveImageAsArtifact(agent: Agent, base64Data: string, prompt: string): Promise<string>;
143
165
  /**
@@ -55,6 +55,7 @@ const logger_1 = require("../../common/logger");
55
55
  const jsonrepair_1 = require("jsonrepair");
56
56
  const model_prices_1 = require("../model_prices");
57
57
  const ai_debug_logger_1 = require("../ai-debug-logger");
58
+ const blank_image_1 = require("./blank-image");
58
59
  let BaseAiService = class BaseAiService {
59
60
  // Cache for models to avoid repeated API calls
60
61
  modelsCache = null;
@@ -160,6 +161,34 @@ let BaseAiService = class BaseAiService {
160
161
  const template = (0, handlebars_1.compile)(preparedPrompt, { noEscape: true });
161
162
  return template(variables);
162
163
  }
164
+ /**
165
+ * The agent's system instruction, resolved from its prompt folder per call.
166
+ *
167
+ * Read on every call for the same reason {@link getPreparedPrompt} re-reads its
168
+ * template: the folder's files are the source, so an edit reaches the next turn.
169
+ * A copy taken at creation could not — nothing in the API sets this field, so a
170
+ * stale copy stayed stale for the life of the agent.
171
+ *
172
+ * Reached only when the caller passes no instructions of its own. A room turn
173
+ * renders `perceive.prompt` and passes that, which *replaces* this rather than
174
+ * adding to it, so the read never happens on the hot path.
175
+ *
176
+ * @param agent The agent whose prompt folder is searched
177
+ * @returns The file's contents, or '' when the folder has no such file
178
+ */
179
+ getSystemInstruction(agent) {
180
+ const systemInstructionFile = this.findPromptFile(agent, 'system_instruction', '.prompt');
181
+ if (!systemInstructionFile) {
182
+ return '';
183
+ }
184
+ try {
185
+ return (0, fs_1.readFileSync)(systemInstructionFile).toString('utf8');
186
+ }
187
+ catch (error) {
188
+ logger_1.logger.error(`Error reading system instruction from ${systemInstructionFile}:`, error);
189
+ return '';
190
+ }
191
+ }
163
192
  getPreparedSchema(agent, promptFileName) {
164
193
  // Use 4-level fallback to find the schema file
165
194
  const jsonSchemaFile = this.findPromptFile(agent, promptFileName, '.json');
@@ -248,20 +277,7 @@ let BaseAiService = class BaseAiService {
248
277
  throw new Error(`Model '${modelName}' is not listed in model_prices.json for ${this.getServiceName()}. ` +
249
278
  `Add a pricing entry before using this model.`);
250
279
  }
251
- // Create a temporary agent object to use the findPromptFile helper
252
- const tempAgent = { promptFolder, userPaths };
253
- const systemInstructionFile = this.findPromptFile(tempAgent, 'system_instruction', '.prompt');
254
- let systemInstructionPrompt = null;
255
- if (systemInstructionFile) {
256
- try {
257
- systemInstructionPrompt = (0, fs_1.readFileSync)(systemInstructionFile).toString('utf8');
258
- }
259
- catch (error) {
260
- logger_1.logger.error(`Error reading system instruction from ${systemInstructionFile}:`, error);
261
- systemInstructionPrompt = null;
262
- }
263
- }
264
- const agent = new agent_1.Agent(null, userPaths, configService, agentStoreService, balanceService, artifactService, agentName, agentNickname, description, promptFolder, systemInstructionPrompt, [], modelName, this.getServiceName(), this, // Pass the service instance itself
280
+ const agent = new agent_1.Agent(null, userPaths, configService, agentStoreService, balanceService, artifactService, agentName, agentNickname, description, promptFolder, [], modelName, this.getServiceName(), this, // Pass the service instance itself
265
281
  null, // no reasoning
266
282
  false, // do not allow search
267
283
  0, // Default to maximum output tokens
@@ -343,10 +359,19 @@ let BaseAiService = class BaseAiService {
343
359
  }
344
360
  /**
345
361
  * Helper: Save image from base64 data as artifact
362
+ *
363
+ * The one place every image from every provider passes through, which is why the
364
+ * blank-frame check lives here. A refusal comes back as a successful response
365
+ * holding no picture; throwing rather than storing it turns into `{ error }` in
366
+ * each provider's catch, and every caller already bails on that before it deletes
367
+ * the portrait the new image was meant to replace.
346
368
  */
347
369
  async saveImageAsArtifact(agent, base64Data, prompt) {
348
370
  // Decode base64 to buffer
349
371
  const buffer = Buffer.from(base64Data, 'base64');
372
+ if ((0, blank_image_1.isBlankImage)(buffer)) {
373
+ throw new blank_image_1.BlankImageError(`${this.getServiceName()} returned a blank ${buffer.length}-byte image`);
374
+ }
350
375
  // Default to PNG for generated images
351
376
  const mimeType = 'image/png';
352
377
  // Generate name from prompt (truncate if too long)
@@ -377,8 +402,27 @@ let BaseAiService = class BaseAiService {
377
402
  if (!this.isAvailable) {
378
403
  return Promise.reject(new Error(`${this.getServiceName()} service is not available. Check API key configuration.`));
379
404
  }
380
- let promptInstructions = this.getPreparedPrompt(agent, instructionFileName, variables);
381
- let jsonSchema = this.getPreparedSchema(agent, instructionFileName);
405
+ // The folder's standing instruction prefixes the rendered one, so a folder
406
+ // works the same whether its agent is talked to alone or is in a room.
407
+ //
408
+ // Without this a folder had to pick: `system_instruction.prompt` carries the
409
+ // role for a one-to-one chat on the Agents page (where nothing renders an
410
+ // instruction file, so the provider falls back to it), and a room renders
411
+ // `perceive.prompt` and passes it here — which *replaces* the fallback rather
412
+ // than adding to it. A folder written for one context lost its role in the
413
+ // other.
414
+ //
415
+ // The standing instruction goes first for two reasons: a role reads before
416
+ // the protocol that carries it out, and the system block is the cached
417
+ // prefix — a file changes far less often than a rendered `perceive.prompt`,
418
+ // which carries the artifact roster and every other agent's description, so
419
+ // the stable half belongs in front.
420
+ const renderedInstructions = this.getPreparedPrompt(agent, instructionFileName, variables);
421
+ const standingInstruction = this.getSystemInstruction(agent).trim();
422
+ const promptInstructions = standingInstruction
423
+ ? `${standingInstruction}\n\n${renderedInstructions}`
424
+ : renderedInstructions;
425
+ const jsonSchema = this.getPreparedSchema(agent, instructionFileName);
382
426
  return this.textPrompt(agent, prompt, jsonSchema, saveResponse, promptInstructions, cacheConfig, maxOutputChars);
383
427
  }
384
428
  /**
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Recognizing the frame an image model returns when it has refused.
3
+ *
4
+ * A refusal usually arrives as a perfectly successful response carrying a uniformly
5
+ * black picture rather than as an error, so nothing upstream of the pixels can tell
6
+ * it apart from a drawing. Stored, it replaces the likeness it was meant to redraw —
7
+ * `IllustrationService.updatePortrait` deletes the old portrait once the new one is
8
+ * in hand — and the original is gone for good.
9
+ *
10
+ * The test is the compressed size rather than the pixels, because both PNG's deflate
11
+ * and JPEG's DCT crush a flat frame to almost nothing. Measured at 1024x1024, in
12
+ * bytes per pixel:
13
+ *
14
+ * solid colour 0.003
15
+ * smooth gradient 0.11 the flattest thing a model actually draws
16
+ * photographic detail 1.0 - 3.0
17
+ *
18
+ * So the two cases are more than an order of magnitude apart on either side of the
19
+ * threshold below, and deciding between them needs no decoder and no dependency.
20
+ *
21
+ * The limits are worth knowing. A refusal that is not flat — a placeholder graphic,
22
+ * a frame of noise — reads as a picture; those are not what the models in use here
23
+ * return, and guessing at them would cost real drawings. In the other direction a
24
+ * genuinely flat synthetic image, two blocks of colour or a shape on a plain ground,
25
+ * reads as blank, which is why this is applied to generated illustration output and
26
+ * not to anything a person uploads.
27
+ */
28
+ /** Thrown instead of storing a frame that carries no picture. */
29
+ export declare class BlankImageError extends Error {
30
+ constructor(message: string);
31
+ }
32
+ /**
33
+ * Whether these bytes are a blank frame rather than a picture.
34
+ * @param image The decoded image bytes
35
+ */
36
+ export declare function isBlankImage(image: Buffer): boolean;
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ /**
3
+ * Recognizing the frame an image model returns when it has refused.
4
+ *
5
+ * A refusal usually arrives as a perfectly successful response carrying a uniformly
6
+ * black picture rather than as an error, so nothing upstream of the pixels can tell
7
+ * it apart from a drawing. Stored, it replaces the likeness it was meant to redraw —
8
+ * `IllustrationService.updatePortrait` deletes the old portrait once the new one is
9
+ * in hand — and the original is gone for good.
10
+ *
11
+ * The test is the compressed size rather than the pixels, because both PNG's deflate
12
+ * and JPEG's DCT crush a flat frame to almost nothing. Measured at 1024x1024, in
13
+ * bytes per pixel:
14
+ *
15
+ * solid colour 0.003
16
+ * smooth gradient 0.11 the flattest thing a model actually draws
17
+ * photographic detail 1.0 - 3.0
18
+ *
19
+ * So the two cases are more than an order of magnitude apart on either side of the
20
+ * threshold below, and deciding between them needs no decoder and no dependency.
21
+ *
22
+ * The limits are worth knowing. A refusal that is not flat — a placeholder graphic,
23
+ * a frame of noise — reads as a picture; those are not what the models in use here
24
+ * return, and guessing at them would cost real drawings. In the other direction a
25
+ * genuinely flat synthetic image, two blocks of colour or a shape on a plain ground,
26
+ * reads as blank, which is why this is applied to generated illustration output and
27
+ * not to anything a person uploads.
28
+ */
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.BlankImageError = void 0;
31
+ exports.isBlankImage = isBlankImage;
32
+ /** PNG's 8-byte file signature. */
33
+ const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
34
+ /** Compressed bytes per pixel below which a frame holds no picture. */
35
+ const MIN_BYTES_PER_PIXEL = 0.02;
36
+ /**
37
+ * The floor applied when the dimensions cannot be read, which today means anything
38
+ * that is not a PNG. Every entry in image_models.json generates at 1024x1024 or
39
+ * larger, and the most aggressive JPEG of a face at that size is still several times
40
+ * this. It is deliberately not applied to PNGs, whose dimensions are there to be
41
+ * read: a small PNG that really is a picture is under the floor honestly.
42
+ */
43
+ const MIN_IMAGE_BYTES = 20_000;
44
+ /** Thrown instead of storing a frame that carries no picture. */
45
+ class BlankImageError extends Error {
46
+ constructor(message) {
47
+ super(message);
48
+ this.name = 'BlankImageError';
49
+ if (Error.captureStackTrace) {
50
+ Error.captureStackTrace(this, BlankImageError);
51
+ }
52
+ }
53
+ }
54
+ exports.BlankImageError = BlankImageError;
55
+ /** Width and height out of a PNG's IHDR chunk, or null for anything else. */
56
+ function readPngDimensions(image) {
57
+ // The 8-byte signature, a 4-byte chunk length, 'IHDR', then width and height.
58
+ if (image.length < 24)
59
+ return null;
60
+ if (!image.subarray(0, 8).equals(PNG_SIGNATURE))
61
+ return null;
62
+ if (image.subarray(12, 16).toString('ascii') !== 'IHDR')
63
+ return null;
64
+ return { width: image.readUInt32BE(16), height: image.readUInt32BE(20) };
65
+ }
66
+ /**
67
+ * Whether these bytes are a blank frame rather than a picture.
68
+ * @param image The decoded image bytes
69
+ */
70
+ function isBlankImage(image) {
71
+ if (!image || image.length === 0)
72
+ return true;
73
+ const dimensions = readPngDimensions(image);
74
+ if (!dimensions)
75
+ return image.length < MIN_IMAGE_BYTES;
76
+ const pixels = dimensions.width * dimensions.height;
77
+ if (pixels <= 0)
78
+ return true;
79
+ return image.length / pixels < MIN_BYTES_PER_PIXEL;
80
+ }
@@ -170,7 +170,7 @@ let DeepSeekAiService = DeepSeekAiService_1 = class DeepSeekAiService extends ba
170
170
  }
171
171
  // Build messages array locally without modifying agent.history yet
172
172
  const identity = `Your agent identity is ${agent.agentName}: ${agent.description}`;
173
- const instructions = promptInstructions || agent.systemInstruction;
173
+ const instructions = promptInstructions || this.getSystemInstruction(agent);
174
174
  // The instructions go in the `system` option rather than as a leading
175
175
  // system message. The SDK warns about the latter because a system turn
176
176
  // sitting in `messages` is indistinguishable from one a model was talked
@@ -114,7 +114,7 @@ let FalAiService = class FalAiService extends base_ai_service_1.BaseAiService {
114
114
  // Build messages array locally without modifying agent.history yet
115
115
  // Prepend identity and system instruction at the beginning
116
116
  const identity = `Your agent identity is ${agent.agentName}: ${agent.description}`;
117
- const instructions = promptInstructions || agent.systemInstruction;
117
+ const instructions = promptInstructions || this.getSystemInstruction(agent);
118
118
  // Build full prompt for fal.ai any-llm
119
119
  let fullPrompt = '';
120
120
  if (instructions) {
@@ -127,7 +127,7 @@ let GoogleAiService = class GoogleAiService extends base_ai_service_1.BaseAiServ
127
127
  const { name: _name, description: _description, ...schemaOnly } = jsonSchema;
128
128
  generationConfig.responseSchema = schemaOnly;
129
129
  }
130
- const instructions = promptInstructions || agent.systemInstruction;
130
+ const instructions = promptInstructions || this.getSystemInstruction(agent);
131
131
  const requestParams = {
132
132
  model: agent.modelName,
133
133
  contents: messages,
@@ -132,7 +132,7 @@ let GrokAiService = class GrokAiService extends base_ai_service_1.BaseAiService
132
132
  // Build messages array locally without modifying agent.history yet
133
133
  // Prepend identity and system instruction at the beginning
134
134
  const identity = `Your agent identity is ${agent.agentName}: ${agent.description}`;
135
- const instructions = promptInstructions || agent.systemInstruction;
135
+ const instructions = promptInstructions || this.getSystemInstruction(agent);
136
136
  const messages = [];
137
137
  if (instructions)
138
138
  messages.push({
@@ -228,7 +228,7 @@ let OpenAiService = class OpenAiService extends base_ai_service_1.BaseAiService
228
228
  : {
229
229
  type: 'text',
230
230
  };
231
- let instructions = promptInstructions || agent.systemInstruction;
231
+ let instructions = promptInstructions || this.getSystemInstruction(agent);
232
232
  const effort = this.resolveReasoningEffort(agent.modelName, agent.reasoningEffort);
233
233
  const requestParams = {
234
234
  model: agent.modelName,
@@ -83,7 +83,7 @@ let SelfHostedAiService = class SelfHostedAiService extends base_ai_service_1.Ba
83
83
  }
84
84
  // Build messages array locally without modifying agent.history yet
85
85
  const identity = `Your agent identity is ${agent.agentName}: ${agent.description}`;
86
- const instructions = promptInstructions || agent.systemInstruction;
86
+ const instructions = promptInstructions || this.getSystemInstruction(agent);
87
87
  const messages = [];
88
88
  if (instructions)
89
89
  messages.push({
@@ -98,7 +98,7 @@ let TogetherAiService = class TogetherAiService extends base_ai_service_1.BaseAi
98
98
  // Build messages array locally without modifying agent.history yet
99
99
  // Prepend identity and system instruction at the beginning
100
100
  const identity = `Your agent identity is ${agent.agentName}: ${agent.description}`;
101
- const instructions = promptInstructions || agent.systemInstruction;
101
+ const instructions = promptInstructions || this.getSystemInstruction(agent);
102
102
  const messages = [];
103
103
  if (instructions)
104
104
  messages.push({ role: 'system', content: instructions });
@@ -9,7 +9,6 @@ export interface AgentConfig {
9
9
  description: string;
10
10
  privateContext?: string;
11
11
  promptFolder: string;
12
- systemInstruction: string;
13
12
  modelName: string;
14
13
  smallModelName?: string;
15
14
  serviceName: string;
@@ -193,7 +193,7 @@ let AgentStoreService = class AgentStoreService {
193
193
  const aiService = this.aiFactoryService.createAiService(template.serviceName);
194
194
  // Create new agent with copied properties
195
195
  const instance = new agent_1.Agent(instanceId, this.userPaths, this.configService, this, this.balanceService, this.artifactService, publishedName, // New name for the instance
196
- template.agentNickname || template.agentName, template.description, template.promptFolder, template.systemInstruction, [], // Empty history for new instance
196
+ template.agentNickname || template.agentName, template.description, template.promptFolder, [], // Empty history for new instance
197
197
  template.modelName, template.serviceName, aiService, template.reasoningEffort, template.allowSearch, template.maxOutputTokens, template.beginInstruction, this.defaultStorageDir);
198
198
  // Set instance-specific properties
199
199
  instance.templateAgentId = templateId;
@@ -267,7 +267,6 @@ let AgentStoreService = class AgentStoreService {
267
267
  instance.privateContext = template.privateContext;
268
268
  instance.agentNickname = template.agentNickname;
269
269
  instance.promptFolder = template.promptFolder;
270
- instance.systemInstruction = template.systemInstruction;
271
270
  instance.modelName = template.modelName;
272
271
  instance.smallModelName = template.smallModelName;
273
272
  instance.serviceName = template.serviceName;
@@ -356,7 +355,7 @@ let AgentStoreService = class AgentStoreService {
356
355
  // Use provided artifact service or fall back to default
357
356
  const finalArtifactService = artifactService || this.artifactService;
358
357
  // Create a new agent with the saved configuration, including history
359
- const agent = new agent_1.Agent(config.id, this.userPaths, this.configService, this, this.balanceService, finalArtifactService, config.agentName, config.agentNickname || config.agentName, config.description, config.promptFolder, config.systemInstruction, config.history || [], // Restore history or use empty array
358
+ const agent = new agent_1.Agent(config.id, this.userPaths, this.configService, this, this.balanceService, finalArtifactService, config.agentName, config.agentNickname || config.agentName, config.description, config.promptFolder, config.history || [], // Restore history or use empty array
360
359
  config.modelName, config.serviceName, aiService, config.reasoningEffort, config.allowSearch, config.maxOutputTokens, config.beginInstruction || '', storageDir);
361
360
  // Restore agent-private context (e.g. story inventory)
362
361
  agent.privateContext = config.privateContext || '';
@@ -476,7 +475,6 @@ let AgentStoreService = class AgentStoreService {
476
475
  description: agent.description,
477
476
  privateContext: agent.privateContext,
478
477
  promptFolder: agent.promptFolder,
479
- systemInstruction: agent.systemInstruction,
480
478
  modelName: agent.modelName,
481
479
  smallModelName: agent.smallModelName,
482
480
  serviceName: agent.serviceName,
@@ -74,7 +74,6 @@ export declare class Agent {
74
74
  * not the agent, and persisting it would freeze a copy of the enabled set.
75
75
  */
76
76
  enabledPacks?: () => readonly string[];
77
- systemInstruction: string;
78
77
  maxHistoryMessages?: number;
79
78
  /**
80
79
  * Index into {@link history} below which the rolling window may trim, and at or
@@ -127,7 +126,7 @@ export declare class Agent {
127
126
  * BaseAiService.createAgent); SDK consumers should obtain them via
128
127
  * {@link Briyah} rather than calling this directly.
129
128
  */
130
- constructor(id: string | null, userPaths: UserPathsService, configService: IConfigService, agentStoreService: AgentStoreService, balanceService: BalanceService, artifactService: ArtifactService, agentName: string, agentNickname: string, description: string, promptFolder: string, systemInstruction: string, history: any[], modelName: string, serviceName: string, aiService: BaseAiService, reasoningEffort: 'low' | 'medium' | 'high' | null, allowSearch: boolean, maxOutputTokens: number, beginInstruction: string, storageDir: string);
129
+ constructor(id: string | null, userPaths: UserPathsService, configService: IConfigService, agentStoreService: AgentStoreService, balanceService: BalanceService, artifactService: ArtifactService, agentName: string, agentNickname: string, description: string, promptFolder: string, history: any[], modelName: string, serviceName: string, aiService: BaseAiService, reasoningEffort: 'low' | 'medium' | 'high' | null, allowSearch: boolean, maxOutputTokens: number, beginInstruction: string, storageDir: string);
131
130
  attachDocument(fileName: string, fileData: Uint8Array): Promise<string>;
132
131
  /**
133
132
  * Attaches an artifact to the agent
@@ -76,7 +76,6 @@ class Agent {
76
76
  * not the agent, and persisting it would freeze a copy of the enabled set.
77
77
  */
78
78
  enabledPacks;
79
- systemInstruction;
80
79
  maxHistoryMessages; // If set, keep only last N messages (rolling window)
81
80
  /**
82
81
  * Index into {@link history} below which the rolling window may trim, and at or
@@ -132,13 +131,12 @@ class Agent {
132
131
  * BaseAiService.createAgent); SDK consumers should obtain them via
133
132
  * {@link Briyah} rather than calling this directly.
134
133
  */
135
- constructor(id, userPaths, configService, agentStoreService, balanceService, artifactService, agentName = '', agentNickname = '', description = '', promptFolder = '', systemInstruction = '', history = [], modelName = '', serviceName = '', aiService, reasoningEffort = null, allowSearch = false, maxOutputTokens = 0, beginInstruction = '', storageDir) {
134
+ constructor(id, userPaths, configService, agentStoreService, balanceService, artifactService, agentName = '', agentNickname = '', description = '', promptFolder = '', history = [], modelName = '', serviceName = '', aiService, reasoningEffort = null, allowSearch = false, maxOutputTokens = 0, beginInstruction = '', storageDir) {
136
135
  this.agentName = agentName;
137
136
  // Auto-generate nickname if not provided
138
137
  this.agentNickname = agentNickname || Agent.generateNickname(agentName);
139
138
  this.description = description;
140
139
  this.promptFolder = promptFolder;
141
- this.systemInstruction = systemInstruction;
142
140
  this.history = history;
143
141
  this.openai = null;
144
142
  this.assistant = null;
@@ -40,6 +40,7 @@ const user_config_service_1 = require("../config/user-config.service");
40
40
  const pack_service_1 = require("../packs/pack.service");
41
41
  const pack_instantiation_service_1 = require("../packs/pack-instantiation.service");
42
42
  const rpg_service_1 = require("../rpg/rpg.service");
43
+ const illustration_service_1 = require("../room/illustration/illustration.service");
43
44
  /**
44
45
  * Factory for creating user-specific AppService instances with their dependencies
45
46
  */
@@ -114,10 +115,15 @@ let UserServiceFactory = class UserServiceFactory {
114
115
  const roomFactory = new room_factory_1.RoomFactory(roomStore, toolStore, toolExecution);
115
116
  // 8. Create StoryStoreService (depends on UserPathsService)
116
117
  const storyStore = new story_store_service_1.StoryStoreService(userPaths, roomStore);
118
+ // 8b. The illustration pipeline. Shared by stories and rooms, so it is built
119
+ // here rather than inside either of them.
120
+ const illustration = new illustration_service_1.IllustrationService(userPaths, agentStore, agentFactory);
121
+ roomStore.setIllustrationService(illustration);
122
+ roomFactory.setIllustrationService(illustration);
117
123
  // 9. Create StoryService (depends on all user-specific services)
118
- const storyService = new story_service_1.StoryService(storyStore, agentStore, roomStore, this.storyProgressService, this.storyMessageService, userPaths, agentFactory, roomFactory);
124
+ const storyService = new story_service_1.StoryService(storyStore, agentStore, roomStore, this.storyProgressService, this.storyMessageService, userPaths, agentFactory, roomFactory, illustration);
119
125
  // 10. Create AppService with all dependencies
120
- const appService = new app_service_1.AppService(this.aiFactoryService, agentStore, this.agentMessageService, roomStore, this.roomMessageService, userPaths, attachedFileService, artifactService, storyStore, storyService, this.publishedAgentsService, this.publishedRoomsService, balanceService, this.balanceMessageService, transactionService, agentFactory, roomFactory, toolStore, toolExecution, packService);
126
+ const appService = new app_service_1.AppService(this.aiFactoryService, agentStore, this.agentMessageService, roomStore, this.roomMessageService, userPaths, attachedFileService, artifactService, storyStore, storyService, this.publishedAgentsService, this.publishedRoomsService, balanceService, this.balanceMessageService, transactionService, agentFactory, roomFactory, toolStore, toolExecution, packService, illustration);
121
127
  // Built after the AppService it drives, and handed back through it, because
122
128
  // instantiating a pack's room goes through the same createRoom and
123
129
  // createRoomAgent paths the API uses rather than around them.
@@ -87,6 +87,7 @@ export declare class AppController {
87
87
  */
88
88
  private static parseInstantiateModels;
89
89
  private static parseTurnMode;
90
+ private static parseIllustrationMode;
90
91
  createRoom(req: ExpressRequest, body: {
91
92
  roomName: string;
92
93
  roomGoal: string;
@@ -94,6 +95,12 @@ export declare class AppController {
94
95
  roomLeader?: string;
95
96
  turnMode?: string;
96
97
  moderator?: string;
98
+ /** What Begin sends to the room leader. */
99
+ beginInstruction?: string;
100
+ /** Entry in image_models.json. "No images" disables illustration. */
101
+ imageModel?: string;
102
+ /** When the room illustrates itself. Absent means 'on-request'. */
103
+ illustrationMode?: string;
97
104
  }): Promise<CreateRoomResponse>;
98
105
  editRoom(req: ExpressRequest, roomId: string, body: {
99
106
  roomName: string;
@@ -105,6 +112,12 @@ export declare class AppController {
105
112
  moderator?: string;
106
113
  /** Files the room under a pack. Empty string clears it. */
107
114
  pack?: string;
115
+ /** What Begin sends to the room leader. Empty string clears it. */
116
+ beginInstruction?: string;
117
+ /** Entry in image_models.json. Empty string falls back to the env default. */
118
+ imageModel?: string;
119
+ /** When the room illustrates itself. */
120
+ illustrationMode?: string;
108
121
  }): Promise<void>;
109
122
  /**
110
123
  * Creates an agent that belongs to this room and adds it to it.
@@ -141,6 +154,16 @@ export declare class AppController {
141
154
  targets?: string[];
142
155
  clearQueue?: boolean;
143
156
  }): Promise<SendMessageResult>;
157
+ /**
158
+ * Opens a room with its configured begin instruction.
159
+ *
160
+ * `RoomAccess` rather than `OwnerOnly`, and deliberately: the people who most
161
+ * need to start a published room are the party holding its link, who have a
162
+ * room-scoped token and nothing more. It is also a strictly narrower power than
163
+ * the message endpoint beside it — the caller chooses nothing, since the
164
+ * content, sender, action and target all come from the room's own settings.
165
+ */
166
+ beginRoom(req: ExpressRequest, roomId: string): Promise<SendMessageResult>;
144
167
  pauseRoom(req: ExpressRequest, roomId: string): Promise<{
145
168
  success: boolean;
146
169
  }>;
@@ -178,6 +201,16 @@ export declare class AppController {
178
201
  resetPublishedRoomInstance(req: ExpressRequest, instanceId: string): Promise<void>;
179
202
  resetStory(req: ExpressRequest, storyId: string): Promise<void>;
180
203
  revertStoryChapter(req: ExpressRequest, storyId: string): Promise<void>;
204
+ /**
205
+ * Serves a picture the room's illustrator drew.
206
+ *
207
+ * Read access rather than owner-only, because the whole point is that a
208
+ * published campaign shows its images to the people playing it. The browser
209
+ * fetches this as a subresource of a message, carrying neither the room header
210
+ * nor a cookie, so `JwtAuthGuard` has a branch that resolves a published room
211
+ * id straight from this URL — the same accommodation the SSE routes need.
212
+ */
213
+ getRoomImage(req: ExpressRequest, roomId: string, artifactId: string, res: Response): Promise<void>;
181
214
  getRoomArtifacts(req: ExpressRequest, roomId: string): Promise<{
182
215
  artifacts: any[];
183
216
  }>;