briyah 2.0.4 → 2.0.6

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 (80) 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/moderate.json +34 -0
  6. package/data/common/prompts/moderate.prompt +136 -0
  7. package/data/common/prompts/perceive.prompt +1 -1
  8. package/data/packs/dnd5e/prompts/battle_master/perceive.prompt +1 -1
  9. package/data/packs/dnd5e/prompts/campaign_designer/perceive.prompt +1 -1
  10. package/data/packs/dnd5e/prompts/character_creator/perceive.prompt +795 -787
  11. package/data/packs/dnd5e/prompts/dungeon_master/defaults_config.json +2 -1
  12. package/data/packs/dnd5e/prompts/dungeon_master/perceive.prompt +1 -1
  13. package/data/packs/dnd5e/rooms/campaign.json +18 -15
  14. package/data/packs/dnd5e/rooms/table.json +17 -16
  15. package/dist-sdk/server/src/ai/LLM/anthropic.service.js +1 -1
  16. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +38 -0
  17. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +83 -16
  18. package/dist-sdk/server/src/ai/LLM/blank-image.d.ts +36 -0
  19. package/dist-sdk/server/src/ai/LLM/blank-image.js +80 -0
  20. package/dist-sdk/server/src/ai/LLM/deepseek.service.js +1 -1
  21. package/dist-sdk/server/src/ai/LLM/fal.service.js +1 -1
  22. package/dist-sdk/server/src/ai/LLM/googleai.service.js +1 -1
  23. package/dist-sdk/server/src/ai/LLM/grok.service.js +1 -1
  24. package/dist-sdk/server/src/ai/LLM/openai.service.js +1 -1
  25. package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +1 -1
  26. package/dist-sdk/server/src/ai/LLM/together.service.js +1 -1
  27. package/dist-sdk/server/src/ai/agent-config.d.ts +0 -1
  28. package/dist-sdk/server/src/ai/agent-store.service.js +2 -4
  29. package/dist-sdk/server/src/ai/agent.d.ts +7 -2
  30. package/dist-sdk/server/src/ai/agent.js +11 -3
  31. package/dist-sdk/server/src/app/user-service-factory.js +8 -2
  32. package/dist-sdk/server/src/app.controller.d.ts +33 -0
  33. package/dist-sdk/server/src/app.controller.js +93 -2
  34. package/dist-sdk/server/src/app.service.d.ts +49 -4
  35. package/dist-sdk/server/src/app.service.js +101 -16
  36. package/dist-sdk/server/src/auth/jwt-auth.guard.js +26 -0
  37. package/dist-sdk/server/src/data/data-guide.builder.d.ts +2 -0
  38. package/dist-sdk/server/src/data/data-guide.builder.js +90 -0
  39. package/dist-sdk/server/src/data/data-registry.d.ts +32 -0
  40. package/dist-sdk/server/src/data/data-registry.js +61 -0
  41. package/dist-sdk/server/src/data/data.types.d.ts +158 -0
  42. package/dist-sdk/server/src/data/data.types.js +24 -0
  43. package/dist-sdk/server/src/data/query-validation.d.ts +45 -0
  44. package/dist-sdk/server/src/data/query-validation.js +245 -0
  45. package/dist-sdk/server/src/packs/pack-instantiation.service.js +5 -0
  46. package/dist-sdk/server/src/packs/pack-manifest.d.ts +14 -0
  47. package/dist-sdk/server/src/packs/pack-manifest.js +11 -0
  48. package/dist-sdk/server/src/room/illustration/illustration.service.d.ts +211 -0
  49. package/dist-sdk/server/src/room/illustration/illustration.service.js +771 -0
  50. package/dist-sdk/server/src/room/illustration/illustration.types.d.ts +101 -0
  51. package/dist-sdk/server/src/room/illustration/illustration.types.js +2 -0
  52. package/dist-sdk/server/src/room/room-config.d.ts +58 -1
  53. package/dist-sdk/server/src/room/room-config.js +19 -0
  54. package/dist-sdk/server/src/room/room-factory.d.ts +8 -0
  55. package/dist-sdk/server/src/room/room-factory.js +11 -0
  56. package/dist-sdk/server/src/room/room-store.service.d.ts +8 -0
  57. package/dist-sdk/server/src/room/room-store.service.js +43 -2
  58. package/dist-sdk/server/src/room/room.d.ts +110 -6
  59. package/dist-sdk/server/src/room/room.js +277 -10
  60. package/dist-sdk/server/src/rpg/rpg.service.js +5 -1
  61. package/dist-sdk/server/src/sdk/index.d.ts +4 -0
  62. package/dist-sdk/server/src/sdk/index.js +11 -1
  63. package/dist-sdk/server/src/story/story.service.d.ts +24 -65
  64. package/dist-sdk/server/src/story/story.service.js +105 -458
  65. package/dist-sdk/server/src/tools/core/data.tools.d.ts +17 -0
  66. package/dist-sdk/server/src/tools/core/data.tools.js +165 -0
  67. package/dist-sdk/server/src/tools/core/illustrate.tool.d.ts +14 -0
  68. package/dist-sdk/server/src/tools/core/illustrate.tool.js +80 -0
  69. package/dist-sdk/server/src/tools/core/index.js +3 -1
  70. package/dist-sdk/server/src/tools/native-tool.types.d.ts +90 -0
  71. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +9 -0
  72. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +5 -0
  73. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +30 -0
  74. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +75 -0
  75. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +11 -2
  76. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +36 -5
  77. package/dist-sdk/server/src/tools/tool-execution.service.js +91 -21
  78. package/dist-sdk/shared/types/app.types.d.ts +43 -0
  79. package/dist-sdk/shared/types/app.types.js +15 -1
  80. package/package.json +1 -1
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Reading a host's data, without the model ever writing a query language.
3
+ *
4
+ * `query_data` takes a JSON description of a question — dataset, filters,
5
+ * groupings, metrics — validates every name in it against what the host
6
+ * declared, and hands the result to the host's executor. A field the host did
7
+ * not declare cannot reach the executor, so the host builds its statement from
8
+ * names it chose rather than from anything a model produced. That is the whole
9
+ * safety argument, and it holds without a read-only database role behind it.
10
+ *
11
+ * The DSL arrives as one string parameter because {@link ToolParameter} cannot
12
+ * express nesting. Models reproduce a shown example far more reliably than they
13
+ * invent a shape, so the description carries two worked ones.
14
+ */
15
+ import { NativeToolDefinition } from '../native-tool.types';
16
+ export declare const describeDataTool: NativeToolDefinition;
17
+ export declare const queryDataTool: NativeToolDefinition;
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.queryDataTool = exports.describeDataTool = void 0;
4
+ const coerce_1 = require("../shared/coerce");
5
+ const data_registry_1 = require("../../data/data-registry");
6
+ const query_validation_1 = require("../../data/query-validation");
7
+ /** Serialized characters a query result may occupy. Under the tool's own budget. */
8
+ const RESULT_BUDGET = 20_000;
9
+ const QUERY_EXAMPLE = '{"dataset": "claims", "filters": [{"field": "year", "op": "gte", "value": 2022}], ' +
10
+ '"groupBy": ["customer"], "metrics": [{"fn": "sum", "field": "incurred"}], ' +
11
+ '"orderBy": [{"by": "sum_incurred", "dir": "desc"}], "limit": 10}';
12
+ const LIST_EXAMPLE = '{"dataset": "drivers", "filters": [{"field": "age", "op": "lt", "value": 30}, ' +
13
+ '{"field": "active", "op": "eq", "value": true}], "select": ["firstName", "lastName", "age"]}';
14
+ /** Names every dataset, for an error that teaches rather than just refuses. */
15
+ function datasetNames() {
16
+ return (0, data_registry_1.listDatasets)().map((set) => set.name);
17
+ }
18
+ exports.describeDataTool = {
19
+ name: 'describe_data',
20
+ description: 'Lists the datasets you can query, or the fields of one dataset. Your attached ' +
21
+ 'data guide already describes these — use this when you need to confirm a field ' +
22
+ 'exists, or when the guide and a query result disagree.',
23
+ parameters: [
24
+ {
25
+ name: 'dataset',
26
+ type: 'string',
27
+ description: 'The dataset to describe. Omit to list every dataset.',
28
+ required: false,
29
+ },
30
+ ],
31
+ handler: async (args) => {
32
+ if (!(0, data_registry_1.hasDataSources)()) {
33
+ return {
34
+ ok: false,
35
+ summary: 'No data is available to query',
36
+ error: 'This application has not made any data available to query.',
37
+ };
38
+ }
39
+ const wanted = args.dataset === undefined || args.dataset === null || args.dataset === ''
40
+ ? ''
41
+ : (0, coerce_1.str)(args.dataset, 'dataset');
42
+ if (!wanted) {
43
+ const sets = (0, data_registry_1.listDatasets)();
44
+ return {
45
+ ok: true,
46
+ summary: `Listed ${sets.length} dataset(s)`,
47
+ datasets: sets.map((set) => ({
48
+ name: set.name,
49
+ label: set.label || set.name,
50
+ description: set.description,
51
+ })),
52
+ };
53
+ }
54
+ const set = (0, data_registry_1.listDatasets)().find((candidate) => candidate.name === wanted);
55
+ if (!set) {
56
+ return {
57
+ ok: false,
58
+ summary: `No dataset called "${wanted}"`,
59
+ error: `Unknown dataset "${wanted}". Available datasets:`,
60
+ available: datasetNames(),
61
+ };
62
+ }
63
+ return {
64
+ ok: true,
65
+ summary: `Described the "${set.name}" dataset`,
66
+ dataset: set.name,
67
+ label: set.label || set.name,
68
+ description: set.description,
69
+ notes: set.notes || [],
70
+ fields: set.fields,
71
+ };
72
+ },
73
+ timeoutMs: 5_000,
74
+ };
75
+ exports.queryDataTool = {
76
+ name: 'query_data',
77
+ description: 'Answers a question about the application\'s data. Pass a JSON query naming a ' +
78
+ 'dataset from your data guide, with optional filters, groupBy, metrics, orderBy ' +
79
+ 'and limit. Aggregate example: ' +
80
+ QUERY_EXAMPLE +
81
+ ' — listing example: ' +
82
+ LIST_EXAMPLE +
83
+ ' Only the datasets and fields in your data guide exist; if a question needs ' +
84
+ 'something that is not there, say so rather than substituting a field that looks close.',
85
+ parameters: [
86
+ {
87
+ name: 'query',
88
+ type: 'string',
89
+ description: 'The query as a JSON object. Example: ' + QUERY_EXAMPLE,
90
+ required: true,
91
+ },
92
+ ],
93
+ handler: async (args, _helpers, context) => {
94
+ if (!(0, data_registry_1.hasDataSources)()) {
95
+ return {
96
+ ok: false,
97
+ summary: 'No data is available to query',
98
+ error: 'This application has not made any data available to query.',
99
+ };
100
+ }
101
+ const raw = (0, coerce_1.jsonObject)(args.query, 'query', QUERY_EXAMPLE);
102
+ const checked = (0, query_validation_1.validateQuery)(raw, (0, data_registry_1.listDatasets)());
103
+ if (!checked.ok) {
104
+ // A refusal, not a malfunction: it names what was allowed instead so
105
+ // the next turn can be right rather than another guess.
106
+ return {
107
+ ok: false,
108
+ summary: 'Query refused',
109
+ error: checked.error,
110
+ ...(checked.available ? { available: checked.available } : {}),
111
+ };
112
+ }
113
+ const source = (0, data_registry_1.sourceForDataset)(checked.query.dataset);
114
+ if (!source) {
115
+ return {
116
+ ok: false,
117
+ summary: `No source offers "${checked.query.dataset}"`,
118
+ error: `Unknown dataset "${checked.query.dataset}". Available datasets:`,
119
+ available: datasetNames(),
120
+ };
121
+ }
122
+ const result = await source.execute(checked.query, context);
123
+ const rows = Array.isArray(result?.rows) ? result.rows : [];
124
+ const fitted = fitRows(rows);
125
+ return {
126
+ ok: true,
127
+ summary: summarize(checked.query.dataset, fitted.rows.length, result?.totalRows),
128
+ dataset: checked.query.dataset,
129
+ // Echoed so an answer can state the question it actually asked, and
130
+ // so a wrong answer can be traced to a wrong query.
131
+ query: checked.query,
132
+ rowCount: fitted.rows.length,
133
+ ...(typeof result?.totalRows === 'number' ? { totalRows: result.totalRows } : {}),
134
+ ...(fitted.dropped > 0
135
+ ? {
136
+ truncated: true,
137
+ note: `${fitted.dropped} more row(s) were dropped to fit the result size. ` +
138
+ 'Add filters, group the data, or lower the limit.',
139
+ }
140
+ : {}),
141
+ rows: fitted.rows,
142
+ };
143
+ },
144
+ // Rows are the payload, and a grouped answer is worth reading whole. Still
145
+ // modest: every result is appended to the calling agent's history.
146
+ maxResultChars: 24_000,
147
+ timeoutMs: 30_000,
148
+ };
149
+ /** Drops trailing rows until the payload fits, reporting how many went. */
150
+ function fitRows(rows) {
151
+ let kept = rows;
152
+ while (kept.length > 0 && JSON.stringify(kept).length > RESULT_BUDGET) {
153
+ kept = kept.slice(0, Math.max(1, Math.floor(kept.length / 2)));
154
+ if (kept.length === 1 && JSON.stringify(kept).length > RESULT_BUDGET) {
155
+ return { rows: [], dropped: rows.length };
156
+ }
157
+ }
158
+ return { rows: kept, dropped: rows.length - kept.length };
159
+ }
160
+ function summarize(dataset, returned, total) {
161
+ if (typeof total === 'number' && total > returned) {
162
+ return `Queried ${dataset}: ${returned} of ${total} rows`;
163
+ }
164
+ return `Queried ${dataset}: ${returned} row(s)`;
165
+ }
@@ -0,0 +1,14 @@
1
+ import { NativeToolDefinition } from '../native-tool.types';
2
+ /**
3
+ * Asks the room's illustrator for a picture of what is happening.
4
+ *
5
+ * The split matters: the calling agent says *what* to depict, in plain language,
6
+ * and the illustrator turns that into a prompt an image model can use. Writing for
7
+ * an image model is a craft, and it is not one every agent in a room should have
8
+ * to carry in its prompt.
9
+ *
10
+ * Returns as soon as the request is accepted, never with the picture. Drawing one
11
+ * takes minutes and a tool call is capped at two, so waiting would guarantee a
12
+ * timeout; the finished image arrives in the room on its own.
13
+ */
14
+ export declare const illustrateTool: NativeToolDefinition;
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.illustrateTool = void 0;
4
+ const coerce_1 = require("../shared/coerce");
5
+ /**
6
+ * Asks the room's illustrator for a picture of what is happening.
7
+ *
8
+ * The split matters: the calling agent says *what* to depict, in plain language,
9
+ * and the illustrator turns that into a prompt an image model can use. Writing for
10
+ * an image model is a craft, and it is not one every agent in a room should have
11
+ * to carry in its prompt.
12
+ *
13
+ * Returns as soon as the request is accepted, never with the picture. Drawing one
14
+ * takes minutes and a tool call is capped at two, so waiting would guarantee a
15
+ * timeout; the finished image arrives in the room on its own.
16
+ */
17
+ exports.illustrateTool = {
18
+ name: 'illustrate',
19
+ description: 'Ask the room artist for a picture of the current scene. Say what should be shown — the moment, who is in it, where it is happening — in a sentence or two; the artist works out how to draw it, so you do not need to describe style, lighting or composition. ' +
20
+ 'The picture does NOT come back in the result: it appears in the room a minute or two later, on its own. Carry on with your turn and do not wait for it or mention that it is coming. ' +
21
+ 'One picture per turn. The artist may also decide a picture is not warranted — if the scene has not changed much since the last one, none is drawn, and that is normal.',
22
+ parameters: [
23
+ {
24
+ name: 'brief',
25
+ type: 'string',
26
+ description: 'What the picture should show, in a sentence or two, e.g. "The party edges along a ledge above the flooded hall, lit only by Mira\'s lantern"',
27
+ required: true,
28
+ },
29
+ {
30
+ name: 'subjects',
31
+ type: 'array',
32
+ description: 'Who or what appears, by the names the room uses. Optional — the artist reads the scene either way.',
33
+ required: false,
34
+ },
35
+ ],
36
+ async handler(args, helpers) {
37
+ if (!helpers?.illustration) {
38
+ throw new Error('Illustrating works on a room and there is no room here. Run it from a room rather than the tool tester.');
39
+ }
40
+ const brief = (0, coerce_1.str)(args.brief, 'brief');
41
+ const subjects = args.subjects ? (0, coerce_1.list)(args.subjects) : undefined;
42
+ const ticket = helpers.illustration.request(brief, subjects);
43
+ if (ticket.accepted === true) {
44
+ return {
45
+ requested: true,
46
+ summary: `Illustration requested: ${brief}`,
47
+ note: 'It will appear in the room shortly. Carry on — do not wait for it.',
48
+ };
49
+ }
50
+ // Refusals come back successfully rather than thrown, the same way a rules
51
+ // refusal does: "you already asked this turn" is something the caller acts
52
+ // on by getting on with its turn, and reads as nothing like a broken tool.
53
+ if (ticket.reason === 'turn_limit') {
54
+ return {
55
+ requested: false,
56
+ violation: 'turn_limit',
57
+ message: 'You have already asked for a picture this turn.',
58
+ rule: `One picture per turn — each one costs real money and takes minutes to draw.`,
59
+ options: ['Carry on with this turn and ask again on a later one.'],
60
+ summary: 'Illustration refused: one per turn',
61
+ };
62
+ }
63
+ if (ticket.reason === 'in_flight') {
64
+ return {
65
+ requested: false,
66
+ violation: 'in_flight',
67
+ message: 'A picture for this room is already being drawn.',
68
+ options: ['Wait for it to arrive before asking for another.'],
69
+ summary: 'Illustration refused: one already being drawn',
70
+ };
71
+ }
72
+ return {
73
+ requested: false,
74
+ violation: 'images_disabled',
75
+ message: 'This room has no artist configured, so no picture can be made.',
76
+ options: ['Carry on without one, and do not offer to draw again.'],
77
+ summary: 'Illustration refused: images are off',
78
+ };
79
+ },
80
+ };
@@ -16,6 +16,8 @@
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.CORE_TOOL_GROUP = void 0;
18
18
  exports.coreTools = coreTools;
19
+ const data_tools_1 = require("./data.tools");
20
+ const illustrate_tool_1 = require("./illustrate.tool");
19
21
  const rename_tool_1 = require("./rename.tool");
20
22
  /** The name the UI groups these under, in place of a pack name. */
21
23
  exports.CORE_TOOL_GROUP = 'core';
@@ -27,5 +29,5 @@ exports.CORE_TOOL_GROUP = 'core';
27
29
  * @returns The tool definitions
28
30
  */
29
31
  function coreTools() {
30
- return [rename_tool_1.renameAgentTool];
32
+ return [rename_tool_1.renameAgentTool, illustrate_tool_1.illustrateTool, data_tools_1.describeDataTool, data_tools_1.queryDataTool];
31
33
  }
@@ -183,6 +183,77 @@ export interface ToolPackDocuments {
183
183
  * opaque {@link ToolContext}: helpers are Briyah-owned (e.g. an abort-wired
184
184
  * fetch), context is host-owned.
185
185
  */
186
+ /**
187
+ * What {@link ToolIllustration.request} did, or why it did nothing.
188
+ *
189
+ * A refusal comes back as a value rather than a throw, for the same reason
190
+ * {@link RenameOutcome} does: "you already asked for one this turn" is a ruling
191
+ * the model can act on by getting on with its turn, and is nothing like a broken
192
+ * call.
193
+ */
194
+ export type IllustrationTicket = {
195
+ accepted: true;
196
+ } | {
197
+ accepted: false;
198
+ reason: 'images_disabled' | 'turn_limit' | 'in_flight';
199
+ };
200
+ /**
201
+ * What {@link ToolIllustration.portrait} did, and where the answer will arrive.
202
+ *
203
+ * `ready` is the one place the illustration contract hands back a promise. A
204
+ * portrait is drawn for something that is being *written down* — a character sheet
205
+ * that wants to show its face — so unlike a scene, the caller has somewhere to put
206
+ * the result and needs the url to put there. Resolves to a markdown-ready url, or
207
+ * null when the drawing failed; it never rejects, so a caller can `void` it without
208
+ * an unhandled rejection.
209
+ *
210
+ * The turn still ends long before it settles. A caller reports what it started, and
211
+ * writes the url wherever it belongs whenever it turns up.
212
+ *
213
+ * No `in_flight` refusal, unlike a scene: the scene lock exists because a room has
214
+ * one situation and overlapping scenes would draw stale ones, while portraits are
215
+ * per-character and a table seats its party one at a time.
216
+ */
217
+ export type PortraitTicket = {
218
+ accepted: true;
219
+ ready: Promise<string | null>;
220
+ } | {
221
+ accepted: false;
222
+ reason: 'images_disabled' | 'turn_limit';
223
+ };
224
+ /**
225
+ * Asking the room's illustrator for a picture.
226
+ *
227
+ * Synchronous for the same reason {@link ToolRoomAccess} is: the per-turn counter
228
+ * must not be interleaved, and concurrent tool calls are real — commissioned
229
+ * agents run their turns under Promise.allSettled.
230
+ *
231
+ * `request` returns as soon as the request is *accepted*, never when the image is
232
+ * ready. Drawing one takes minutes and a tool call has at most 120 seconds; the
233
+ * picture arrives later as its own message in the room.
234
+ */
235
+ export interface ToolIllustration {
236
+ /** False when the room has no image model, so a tool can say so rather than try. */
237
+ readonly available: boolean;
238
+ readonly usedThisTurn: number;
239
+ readonly perTurnLimit: number;
240
+ /**
241
+ * @param brief What the picture should show
242
+ * @param subjects Who or what appears, by the names the room uses
243
+ */
244
+ request(brief: string, subjects?: string[]): IllustrationTicket;
245
+ /**
246
+ * Draws one character's portrait and reports where it ended up.
247
+ *
248
+ * Stored under the room's `Portrait - <name>` image, which is also what a later
249
+ * scene reuses to keep the character looking like themselves.
250
+ *
251
+ * @param characterName The name the room knows them by
252
+ * @param profile Prose the likeness is drawn from — appearance, and whatever
253
+ * else identifies them. An empty profile draws nothing.
254
+ */
255
+ portrait(characterName: string, profile: string): PortraitTicket;
256
+ }
186
257
  export interface ToolHelpers {
187
258
  fetch: typeof fetch;
188
259
  /**
@@ -196,6 +267,12 @@ export interface ToolHelpers {
196
267
  * store into the tool execution service, which today means a unit test.
197
268
  */
198
269
  packDocuments?: ToolPackDocuments;
270
+ /**
271
+ * Asking the room to illustrate itself. Absent when there is no room, and when
272
+ * the host wired no illustration service — a tool that needs it should say so
273
+ * rather than dereferencing it.
274
+ */
275
+ illustration?: ToolIllustration;
199
276
  }
200
277
  /**
201
278
  * An opaque, per-invocation value supplied by the host when it starts an
@@ -225,6 +302,19 @@ export interface NativeToolDefinition {
225
302
  handler: (args: Record<string, any>, helpers: ToolHelpers, context: ToolContext) => Promise<any>;
226
303
  /** Per-call timeout in ms (default 30_000, capped at 120_000). */
227
304
  timeoutMs?: number;
305
+ /**
306
+ * Per-call result budget in characters of serialized JSON (default 16_384).
307
+ *
308
+ * Raise it for a tool whose whole job is to hand the agent a document — a
309
+ * reference lookup that comes back in six numbered parts is worse than one
310
+ * that comes back whole. Leave it alone for tools that return rows or
311
+ * records: every result is appended verbatim to the calling agent's history,
312
+ * so a generous budget on a chatty tool is what pushes an agent into
313
+ * compaction. Whatever the budget, an oversized result is clipped
314
+ * structurally rather than truncated into unparseable JSON — see
315
+ * ToolExecutionService.truncateResult.
316
+ */
317
+ maxResultChars?: number;
228
318
  /**
229
319
  * The name of the tool pack this tool belongs to. Set by
230
320
  * {@link registerToolPacks} rather than by the pack's own definitions, and
@@ -144,6 +144,15 @@ export interface SheetState {
144
144
  languages?: string[];
145
145
  bg?: string;
146
146
  align?: string;
147
+ /**
148
+ * Url of the character's portrait, rendered into the summary as an image.
149
+ *
150
+ * Written well after the sheet is: `create_sheet` asks for the picture and the
151
+ * drawing takes minutes, so it lands in a later write. Stored rather than
152
+ * resolved on read — which is how a story finds a character's portrait — because
153
+ * nothing reads a room artifact on the way out. A sheet is what it says it is.
154
+ */
155
+ img?: string;
147
156
  class: ClassEntry[];
148
157
  abil: Record<AbilityKey, number>;
149
158
  saveProf: AbilityKey[];
@@ -222,6 +222,7 @@ function normalizeState(raw) {
222
222
  languages: raw.languages ? toStringArray(raw.languages) : undefined,
223
223
  bg: raw.bg ? String(raw.bg) : undefined,
224
224
  align: raw.align ? String(raw.align) : undefined,
225
+ img: raw.img ? String(raw.img).trim() || undefined : undefined,
225
226
  class: Array.isArray(raw.class) && raw.class.length > 0 ? raw.class : [],
226
227
  abil: abil,
227
228
  saveProf: toStringArray(raw.saveProf),
@@ -560,6 +561,10 @@ function renderSummary(state) {
560
561
  ].filter(Boolean);
561
562
  lines.push(`*${descriptors.join(' — ')}*`);
562
563
  lines.push('');
564
+ if (state.img) {
565
+ lines.push(`![${state.name}](${state.img})`);
566
+ lines.push('');
567
+ }
563
568
  const tempNote = state.hp.temp > 0 ? ` (temp ${state.hp.temp})` : '';
564
569
  // Exhaustion and heavy armour change the effective maximum and speed without
565
570
  // touching the stored values, so the line shows what is actually in play.
@@ -157,6 +157,36 @@ export declare function mutateSheet(room: ToolRoomAccess, name: string, mutate:
157
157
  * @throws If a sheet already exists and `replace` is false
158
158
  */
159
159
  export declare function writeNewSheet(room: ToolRoomAccess, state: SheetState, notes: string, replace: boolean): string;
160
+ /**
161
+ * Asks for a character's portrait, and writes the url onto their sheet when it
162
+ * arrives.
163
+ *
164
+ * Two things make this awkward enough to keep in one place. The drawing takes
165
+ * minutes, so the write lands long after the tool call that started it has
166
+ * returned — and the sheet will have moved on by then, because a portrait is drawn
167
+ * while the game is being played. So the state is re-parsed *inside* the update
168
+ * from whatever the body holds at that moment, never from a copy read beforehand:
169
+ * writing back a state captured before the first fight would undo it.
170
+ *
171
+ * Nothing here throws. A portrait is decoration on a character who already exists,
172
+ * and by the time it fails there is no turn left to report it to.
173
+ *
174
+ * @param profile Prose the likeness is drawn from
175
+ * @returns What to tell the model about the request it just made
176
+ */
177
+ export declare function requestPortrait(helpers: ToolHelpers, room: ToolRoomAccess, characterName: string, profile: string): {
178
+ requested: boolean;
179
+ reason?: string;
180
+ };
181
+ /**
182
+ * Writes a portrait url onto an existing sheet, leaving everything else alone.
183
+ *
184
+ * Refuses a corrupt or missing sheet the way every other writer in the pack does,
185
+ * rather than rebuilding one around a picture.
186
+ *
187
+ * @returns True when a sheet was found and changed
188
+ */
189
+ export declare function attachPortrait(room: ToolRoomAccess, characterName: string, url: string): boolean;
160
190
  /**
161
191
  * Rewrites the shared party summary from every sheet in the room. Always a full
162
192
  * re-render rather than an incremental patch, so it is idempotent and the last
@@ -26,6 +26,8 @@ exports.clearFoes = clearFoes;
26
26
  exports.loadSheet = loadSheet;
27
27
  exports.mutateSheet = mutateSheet;
28
28
  exports.writeNewSheet = writeNewSheet;
29
+ exports.requestPortrait = requestPortrait;
30
+ exports.attachPortrait = attachPortrait;
29
31
  exports.refreshPartyStatus = refreshPartyStatus;
30
32
  exports.shareGuide = shareGuide;
31
33
  exports.partyLine = partyLine;
@@ -298,6 +300,79 @@ function writeNewSheet(room, state, notes, replace) {
298
300
  });
299
301
  return artifactName;
300
302
  }
303
+ /**
304
+ * Asks for a character's portrait, and writes the url onto their sheet when it
305
+ * arrives.
306
+ *
307
+ * Two things make this awkward enough to keep in one place. The drawing takes
308
+ * minutes, so the write lands long after the tool call that started it has
309
+ * returned — and the sheet will have moved on by then, because a portrait is drawn
310
+ * while the game is being played. So the state is re-parsed *inside* the update
311
+ * from whatever the body holds at that moment, never from a copy read beforehand:
312
+ * writing back a state captured before the first fight would undo it.
313
+ *
314
+ * Nothing here throws. A portrait is decoration on a character who already exists,
315
+ * and by the time it fails there is no turn left to report it to.
316
+ *
317
+ * @param profile Prose the likeness is drawn from
318
+ * @returns What to tell the model about the request it just made
319
+ */
320
+ function requestPortrait(helpers, room, characterName, profile) {
321
+ const illustration = helpers.illustration;
322
+ if (!illustration)
323
+ return { requested: false, reason: 'no_illustrator' };
324
+ if (!profile.trim())
325
+ return { requested: false, reason: 'no_description' };
326
+ const ticket = illustration.portrait(characterName, profile);
327
+ // `=== true` rather than a truthiness check: the project compiles with
328
+ // strictNullChecks off, which stops `!ticket.accepted` narrowing the union.
329
+ // `illustrate.tool.ts` reads its own ticket the same way.
330
+ if (ticket.accepted === true) {
331
+ void ticket.ready.then((url) => {
332
+ if (!url)
333
+ return;
334
+ try {
335
+ attachPortrait(room, characterName, url);
336
+ }
337
+ catch {
338
+ // Deliberately swallowed: see above.
339
+ }
340
+ });
341
+ return { requested: true };
342
+ }
343
+ return { requested: false, reason: ticket.reason };
344
+ }
345
+ /**
346
+ * Writes a portrait url onto an existing sheet, leaving everything else alone.
347
+ *
348
+ * Refuses a corrupt or missing sheet the way every other writer in the pack does,
349
+ * rather than rebuilding one around a picture.
350
+ *
351
+ * @returns True when a sheet was found and changed
352
+ */
353
+ function attachPortrait(room, characterName, url) {
354
+ let written = false;
355
+ room.update((0, sheet_1.sheetArtifactName)(characterName), (current) => {
356
+ if (!current)
357
+ return null;
358
+ let state;
359
+ let notes;
360
+ try {
361
+ state = (0, sheet_1.parseSheet)(current.body);
362
+ notes = (0, sheet_1.extractNotes)(current.body);
363
+ }
364
+ catch {
365
+ return null;
366
+ }
367
+ if (state.img === url)
368
+ return null;
369
+ state.img = url;
370
+ state.rev = (state.rev || 0) + 1;
371
+ written = true;
372
+ return (0, sheet_1.renderSheet)(state, notes);
373
+ });
374
+ return written;
375
+ }
301
376
  /**
302
377
  * Rewrites the shared party summary from every sheet in the room. Always a full
303
378
  * re-render rather than an incremental patch, so it is idempotent and the last
@@ -46,11 +46,11 @@ const spells_1 = require("../engine/spells");
46
46
  const srd_1 = require("../data/srd");
47
47
  const sheet_1 = require("../engine/sheet");
48
48
  const shared_1 = require("./shared");
49
- const SPEC_EXAMPLE = '{"class":"Ranger","subclass":"Hunter","level":3,"race":"Wood Elf","background":"Outlander","alignment":"NG","abilities":{"str":10,"dex":16,"con":14,"int":11,"wis":15,"cha":9},"skills":["perception","stealth","survival"],"languages":["Giant"],"equipment":["studded leather","longbow","arrows x40"],"attacks":[{"n":"Longbow","atk":5,"dmg":"1d8+3","type":"piercing"}],"spells":["hunter\'s mark"],"backstory":"Raised by the Emberwood circle."}';
49
+ const SPEC_EXAMPLE = '{"class":"Ranger","subclass":"Hunter","level":3,"race":"Wood Elf","background":"Outlander","alignment":"NG","abilities":{"str":10,"dex":16,"con":14,"int":11,"wis":15,"cha":9},"skills":["perception","stealth","survival"],"languages":["Giant"],"equipment":["studded leather","longbow","arrows x40"],"attacks":[{"n":"Longbow","atk":5,"dmg":"1d8+3","type":"piercing"}],"spells":["hunter\'s mark"],"appearance":"Lean and weather-beaten, copper hair in a long braid, green studded leather, a longbow across her back.","backstory":"Raised by the Emberwood circle."}';
50
50
  const SET_EXAMPLE = '{"ac":18,"hp.max":32,"speed":25,"resist":["fire"],"uses.channel_divinity.cur":0}';
51
51
  exports.createSheetTool = {
52
52
  name: 'create_sheet',
53
- description: 'Create a character sheet. "character" is the character\'s name. "spec" is a JSON object describing them; only the class is genuinely required and everything else is derived or defaulted. Hit points, armour class, proficiency bonus, saving throws, skill modifiers, spell slots and hit dice are all computed from the 5e rules, so do not work them out yourself. Put tool proficiencies the player *chose* in "tools", e.g. "tools":["Lute","Drum","Flute"] for a bard — the ones their class, race and background grant outright are added for you, and the result says which choices are still owed. Put languages the player *chose* in "languages" — a background\'s and the extra one a race lets them pick — since no tool here knows what a background grants; what the race speaks natively is added for you. Include a "backstory" string to seed the sheet\'s notes section, which later tool calls never overwrite. "owner" is the nickname of the agent who plays this character — set it, because the sheet is made readable to that agent alone, and because it is how the rest of the table is told who they are: the owning agent\'s public description becomes the character\'s name, race and class, replacing whatever placeholder they were created with. The class\'s own rules are shared with that agent at the same time, as a "Class: ..." document they read from then on, so a player always knows their own features. Set "replace" to true to overwrite an existing sheet. Example spec: ' +
53
+ description: 'Create a character sheet. "character" is the character\'s name. "spec" is a JSON object describing them; only the class is genuinely required and everything else is derived or defaulted. Hit points, armour class, proficiency bonus, saving throws, skill modifiers, spell slots and hit dice are all computed from the 5e rules, so do not work them out yourself. Put tool proficiencies the player *chose* in "tools", e.g. "tools":["Lute","Drum","Flute"] for a bard — the ones their class, race and background grant outright are added for you, and the result says which choices are still owed. Put languages the player *chose* in "languages" — a background\'s and the extra one a race lets them pick — since no tool here knows what a background grants; what the race speaks natively is added for you. Include a "backstory" string to seed the sheet\'s notes section, which later tool calls never overwrite. A portrait is drawn automatically and added to the sheet a few minutes later; include an "appearance" string describing what the character looks like — their build, colouring, clothing and what they carry — so the likeness is theirs rather than a guess from their race and class. "owner" is the nickname of the agent who plays this character — set it, because the sheet is made readable to that agent alone, and because it is how the rest of the table is told who they are: the owning agent\'s public description becomes the character\'s name, race and class, replacing whatever placeholder they were created with. The class\'s own rules are shared with that agent at the same time, as a "Class: ..." document they read from then on, so a player always knows their own features. Set "replace" to true to overwrite an existing sheet. Example spec: ' +
54
54
  SPEC_EXAMPLE,
55
55
  parameters: [
56
56
  { name: 'character', type: 'string', description: "The character's name", required: true },
@@ -112,8 +112,17 @@ exports.createSheetTool = {
112
112
  // failing here would throw away a finished character.
113
113
  const renamed = state.owner ? room.renameAgent(state.owner, state.name) : undefined;
114
114
  const guides = shareGuidesForCharacter(room, helpers.packDocuments, state);
115
+ // Asked for after the sheet exists, because the url is written onto that
116
+ // sheet when the drawing finishes — minutes from now, and long after this
117
+ // turn has ended. The identity line goes with the appearance so the
118
+ // illustrator knows it is drawing a wood elf ranger and not a bare list of
119
+ // features.
120
+ const portrait = (0, shared_1.requestPortrait)(helpers, room, state.name, [identity, spec.appearance, spec.backstory].filter(Boolean).join('\n\n'));
115
121
  return {
116
122
  created: artifactName,
123
+ portrait: portrait.requested
124
+ ? 'A portrait is being drawn and will appear on the sheet in a few minutes.'
125
+ : undefined,
117
126
  headline: (0, shared_1.sheetHeadline)(state),
118
127
  owner: renamed?.renamed ? renamed.to : state.owner,
119
128
  publicIdentity: described ? identity : undefined,