briyah 2.0.12 → 2.0.14

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.
package/README.md CHANGED
@@ -1343,6 +1343,11 @@ await app.attachDocument(assistant.id, 'working-with-documents.md', Buffer.from(
1343
1343
  `list` returned for this call's context. Your `search`, `read` and `fullText` never see an id the
1344
1344
  context cannot.
1345
1345
 
1346
+ **Listing a large library.** `list_documents` gives up detail before documents: every document
1347
+ with a one-line summary if that fits, then every document without summaries, then pages with a
1348
+ `nextOffset`. The agent can narrow by `kind` (the result's `kinds` counts them) or by part of the
1349
+ `name`. Return `kind` from your `list` for that filter to be useful.
1350
+
1346
1351
  **Looking up versus holding.** `find_in_documents` and `read_document` put only what the agent
1347
1352
  read into its history. `load_document` holds a whole document in the agent's context, where it
1348
1353
  rides every request until `unload_document` — the right tool for "review this contract" or
@@ -1364,6 +1369,32 @@ still deletes them. Every artifact now carries `createdAt` and `updatedAt`.
1364
1369
  for a host keeping its own accounting. The vector length has to match your column, so declare
1365
1370
  the column from `EMBEDDING_DIMENSIONS` and change the model and the column together.
1366
1371
 
1372
+ ### Example 14: Letting an agent make pictures
1373
+
1374
+ Give the room an image model (an entry in `image_models.json`) and grant the agent the core tool
1375
+ `create_image`. The agent writes the description and a title; the room's artist draws it exactly
1376
+ as written, once.
1377
+
1378
+ ```typescript
1379
+ const { roomId } = await app.createRoom(
1380
+ 'Assistant', goal, agentIds, 'Lisa', 'directed',
1381
+ undefined, undefined,
1382
+ 'GPT Image 2.5', // imageModel
1383
+ );
1384
+ assistant.toolNames = [...assistant.toolNames, 'create_image'];
1385
+ ```
1386
+
1387
+ The call returns at once, because drawing can outlast a tool call. The finished picture arrives
1388
+ as a `system` room message whose sender is the title and whose content is
1389
+ `![<title>](/api/rooms/<roomId>/images/<imageId>)`; a picture that could not be made arrives
1390
+ instead as a `system` notice from `Artist` saying why. Fetch the bytes with
1391
+ `app.getRoomImage(roomId, imageId)`. One picture per agent per turn.
1392
+
1393
+ `create_image` is not `illustrate`. `illustrate` asks the room's illustrator for a picture of the
1394
+ current scene, and it is built for stories: it decides whether a picture is warranted, draws the
1395
+ setting before the moment, and gives each named character a portrait. Use it for a story-like
1396
+ room, and `create_image` for an agent asked to make a picture of something.
1397
+
1367
1398
  ## Data Storage
1368
1399
 
1369
1400
  Briyah stores data in the following structure:
@@ -2086,11 +2086,15 @@ export declare class AppService {
2086
2086
  *
2087
2087
  * @param roomId - The room's ID
2088
2088
  * @param artifactId - The image's ID, as it appears in the message markdown
2089
- * @returns The bytes and MIME type, or `null` when there is no such image
2089
+ * @returns The bytes and MIME type, with the image's name and the prompt it was
2090
+ * drawn from — what a host keeping a copy needs to make it findable — or
2091
+ * `null` when there is no such image
2090
2092
  */
2091
2093
  getRoomImage(roomId: string, artifactId: string): Promise<{
2092
2094
  content: string | Buffer;
2093
2095
  mimeType: string;
2096
+ name: string;
2097
+ description: string;
2094
2098
  } | null>;
2095
2099
  /**
2096
2100
  * Returns metadata for all artifacts currently attached to an agent.
@@ -3860,7 +3860,9 @@ class AppService {
3860
3860
  *
3861
3861
  * @param roomId - The room's ID
3862
3862
  * @param artifactId - The image's ID, as it appears in the message markdown
3863
- * @returns The bytes and MIME type, or `null` when there is no such image
3863
+ * @returns The bytes and MIME type, with the image's name and the prompt it was
3864
+ * drawn from — what a host keeping a copy needs to make it findable — or
3865
+ * `null` when there is no such image
3864
3866
  */
3865
3867
  async getRoomImage(roomId, artifactId) {
3866
3868
  const room = await this.roomStore.getRoom(roomId);
@@ -3871,7 +3873,12 @@ class AppService {
3871
3873
  const content = artifacts.getArtifact(artifactId);
3872
3874
  if (!metadata || !content)
3873
3875
  return null;
3874
- return { content, mimeType: metadata.mimeType || 'application/octet-stream' };
3876
+ return {
3877
+ content,
3878
+ mimeType: metadata.mimeType || 'application/octet-stream',
3879
+ name: metadata.name || '',
3880
+ description: metadata.description || '',
3881
+ };
3875
3882
  }
3876
3883
  /**
3877
3884
  * Returns metadata for all artifacts currently attached to an agent.
@@ -43,6 +43,10 @@ function buildDocumentGuideMarkdown() {
43
43
  '',
44
44
  '- **Start with `list_documents`** unless you listed them in this same piece of work.',
45
45
  ' Documents are added while you work.',
46
+ '- **Know when you have seen only part of the library.** A large library is listed in',
47
+ ' pages: a result with a `nextOffset` is not everything. Call again with that offset, or',
48
+ ' narrow with `kind` or `name`, before saying what is there. A search finds passages,',
49
+ ' not documents, so "my search found three policies" never means there are only three.',
46
50
  '- **Search in the document\'s own words.** A contract says "hold harmless" and',
47
51
  ' "indemnify"; a loss run says "incurred" and "reserve". Try a second phrasing before',
48
52
  ' concluding something is not there.',
@@ -174,6 +174,26 @@ export declare class IllustrationService {
174
174
  * part of the contract with `describe_scene.prompt`.
175
175
  */
176
176
  private generateSceneImage;
177
+ /**
178
+ * Draws a picture exactly as described and posts it — no illustrator, no
179
+ * reference scene, no portraits. What {@link ToolIllustration.create} queues.
180
+ *
181
+ * Never throws, like the rest of this class. A failure is posted as a notice
182
+ * rather than only logged: the caller told someone a picture was coming, and
183
+ * one that silently never arrives leaves them waiting for it.
184
+ *
185
+ * @returns The stored image's artifact id, or null when nothing was drawn
186
+ */
187
+ createImage(room: Room, target: IllustrationTarget, req: {
188
+ description: string;
189
+ title: string;
190
+ aspect?: ImageAspect;
191
+ requestedBy?: string;
192
+ }): Promise<string | null>;
193
+ /** Tells the room that a picture asked for by name could not be made. */
194
+ private postImageFailure;
195
+ /** Why the image model drew nothing, in words a person can act on. */
196
+ private describeCause;
177
197
  /**
178
198
  * Puts the finished picture in the transcript.
179
199
  *
@@ -608,6 +608,59 @@ let IllustrationService = class IllustrationService {
608
608
  return false;
609
609
  }
610
610
  }
611
+ /**
612
+ * Draws a picture exactly as described and posts it — no illustrator, no
613
+ * reference scene, no portraits. What {@link ToolIllustration.create} queues.
614
+ *
615
+ * Never throws, like the rest of this class. A failure is posted as a notice
616
+ * rather than only logged: the caller told someone a picture was coming, and
617
+ * one that silently never arrives leaves them waiting for it.
618
+ *
619
+ * @returns The stored image's artifact id, or null when nothing was drawn
620
+ */
621
+ async createImage(room, target, req) {
622
+ try {
623
+ const agents = await this.ensureAgents(target);
624
+ if (!agents) {
625
+ this.postImageFailure(room, req.title, 'no image model is configured for this room');
626
+ return null;
627
+ }
628
+ const { artist } = agents;
629
+ room.attachAgent(artist);
630
+ logger_1.logger.log(`Creating image "${req.title}" for ${req.requestedBy || target.key}`);
631
+ const imageResult = await artist.generateImage(req.description, this.getImageProperties(artist, 'generation', req.aspect));
632
+ if (imageResult.error) {
633
+ this.postImageFailure(room, req.title, this.describeCause(imageResult.error));
634
+ return null;
635
+ }
636
+ artist.save();
637
+ const artifactId = imageResult.artifactId;
638
+ target.artifacts.renameArtifact(artifactId, req.title);
639
+ target.artifacts.updateArtifactDescription(artifactId, req.description);
640
+ this.postImageToRoom(room, target, artifactId, req.title);
641
+ return artifactId;
642
+ }
643
+ catch (error) {
644
+ logger_1.logger.error(`Error creating image "${req.title}":`, error);
645
+ this.postImageFailure(room, req.title, this.describeCause(error));
646
+ return null;
647
+ }
648
+ }
649
+ /** Tells the room that a picture asked for by name could not be made. */
650
+ postImageFailure(room, title, cause) {
651
+ try {
652
+ room.addRoomMessage(new message_1.RoomMessage('Artist', app_types_1.MessageAction.SYSTEM, `Could not make the picture "${title}": ${cause}.`));
653
+ }
654
+ catch (postError) {
655
+ logger_1.logger.error('Error adding image failure message to room:', postError);
656
+ }
657
+ }
658
+ /** Why the image model drew nothing, in words a person can act on. */
659
+ describeCause(error) {
660
+ return error instanceof blank_image_1.BlankImageError
661
+ ? 'the image model returned a blank image, which usually means it refused the description'
662
+ : `the image model failed (${this.describeError(error)})`;
663
+ }
611
664
  /**
612
665
  * Puts the finished picture in the transcript.
613
666
  *
@@ -638,9 +691,7 @@ let IllustrationService = class IllustrationService {
638
691
  * is the half of the news that decides what the reader should do next
639
692
  */
640
693
  postPortraitFailure(room, characterName, error, portraitKept) {
641
- const cause = error instanceof blank_image_1.BlankImageError
642
- ? 'the image model returned a blank image, which usually means it refused the description'
643
- : `the image model failed (${this.describeError(error)})`;
694
+ const cause = this.describeCause(error);
644
695
  const outcome = portraitKept
645
696
  ? 'The existing portrait has been kept.'
646
697
  : 'They have no portrait yet.';
@@ -2145,6 +2145,25 @@ Recent Message: ${message.getContent()}
2145
2145
  });
2146
2146
  return { accepted: true, ready };
2147
2147
  },
2148
+ create: (description, title, aspect) => {
2149
+ if (!available)
2150
+ return { accepted: false, reason: 'images_disabled' };
2151
+ const used = this.imagesThisTurn.get(nickname) ?? 0;
2152
+ if (used >= Room.IMAGES_PER_TURN) {
2153
+ return { accepted: false, reason: 'turn_limit' };
2154
+ }
2155
+ // Not gated on `isBusy` either, for the portrait's reason: the lock
2156
+ // guards a room's one situation, and a picture made to order is not
2157
+ // a picture of it.
2158
+ this.imagesThisTurn.set(nickname, used + 1);
2159
+ void illustration.createImage(this, target, {
2160
+ description,
2161
+ title,
2162
+ aspect: aspect ?? this.getImageAspect(),
2163
+ requestedBy: nickname,
2164
+ });
2165
+ return { accepted: true };
2166
+ },
2148
2167
  };
2149
2168
  }
2150
2169
  /**
@@ -3198,7 +3217,13 @@ Recent Message: ${message.getContent()}
3198
3217
  };
3199
3218
  for (const agent of responders) {
3200
3219
  this.pinHistoryOnHandoff(agent, nextMessage);
3201
- const continuing = agent.agentNickname === nextMessage.getSender();
3220
+ // Only a directed room selects the sender on purpose, through the bounded
3221
+ // allowance in selectResponders. A broadcast room selects everyone, the
3222
+ // sender included, and there the sender's own message must fall through to
3223
+ // perceive's hearing check, which drops it, rather than be handed back with
3224
+ // a note telling it to carry on: that has an agent answering itself after
3225
+ // every message it sends, with no bound on how many times.
3226
+ const continuing = this.turnMode === 'directed' && agent.agentNickname === nextMessage.getSender();
3202
3227
  this.perceive(agent, nextMessage, (message) => {
3203
3228
  agentsInProgress--;
3204
3229
  // Process the response immediately
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Fitting an oversized tool result into its budget without breaking it.
3
+ *
4
+ * Every tool result is appended verbatim to the calling agent's history and sent
5
+ * with each of its later requests, so a tool has a character budget. A result
6
+ * over it has to shrink, and how it shrinks decides whether the agent can still
7
+ * use it:
8
+ *
9
+ * - Slicing the serialized JSON (what Briyah once did) hands the agent
10
+ * unparseable half-JSON with the explanation stranded past the cut.
11
+ * - Clipping only the top-level strings (what it did next) cannot shrink the
12
+ * commonest large result there is — a list of records — and threw the whole
13
+ * thing away instead. A document listing of 33 entries came back as an error
14
+ * telling the agent to "ask for less", from a tool with nothing to ask with.
15
+ *
16
+ * So a result keeps its shape and loses detail before it loses records:
17
+ *
18
+ * 1. The longest strings, wherever they are, are cut to the longest length at
19
+ * which everything fits — but never below {@link MIN_CLIPPED_CHARS}, which is
20
+ * the point where a summary stops saying anything.
21
+ * 2. Still over: the largest list loses items from its end until it fits, and
22
+ * the result says how many went (`_omitted` on an object; a closing line in a
23
+ * bare list).
24
+ * 3. Only what neither can shrink — an object of thousands of numbers, say —
25
+ * is replaced by a small object saying so.
26
+ */
27
+ /**
28
+ * Fits a result into its budget, keeping it valid JSON of the same shape.
29
+ *
30
+ * @param result The raw tool result
31
+ * @param maxChars The serialized-JSON budget
32
+ * @returns The result itself when it fits, a shrunken copy, or a small object
33
+ * saying it could not be shrunk
34
+ */
35
+ export declare function clipToolResult(result: any, maxChars: number): any;
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ /**
3
+ * Fitting an oversized tool result into its budget without breaking it.
4
+ *
5
+ * Every tool result is appended verbatim to the calling agent's history and sent
6
+ * with each of its later requests, so a tool has a character budget. A result
7
+ * over it has to shrink, and how it shrinks decides whether the agent can still
8
+ * use it:
9
+ *
10
+ * - Slicing the serialized JSON (what Briyah once did) hands the agent
11
+ * unparseable half-JSON with the explanation stranded past the cut.
12
+ * - Clipping only the top-level strings (what it did next) cannot shrink the
13
+ * commonest large result there is — a list of records — and threw the whole
14
+ * thing away instead. A document listing of 33 entries came back as an error
15
+ * telling the agent to "ask for less", from a tool with nothing to ask with.
16
+ *
17
+ * So a result keeps its shape and loses detail before it loses records:
18
+ *
19
+ * 1. The longest strings, wherever they are, are cut to the longest length at
20
+ * which everything fits — but never below {@link MIN_CLIPPED_CHARS}, which is
21
+ * the point where a summary stops saying anything.
22
+ * 2. Still over: the largest list loses items from its end until it fits, and
23
+ * the result says how many went (`_omitted` on an object; a closing line in a
24
+ * bare list).
25
+ * 3. Only what neither can shrink — an object of thousands of numbers, say —
26
+ * is replaced by a small object saying so.
27
+ */
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.clipToolResult = clipToolResult;
30
+ /** Strings are never cut shorter than this to make room; lists lose items instead. */
31
+ const MIN_CLIPPED_CHARS = 120;
32
+ /** What a cut string ends with: enough for the agent to know it is not the whole value. */
33
+ function clipString(value, cap) {
34
+ const marker = `…(clipped from ${value.length} characters)`;
35
+ return `${value.slice(0, Math.max(0, cap - marker.length))}${marker}`;
36
+ }
37
+ /** A copy with every string longer than `cap` cut to it. */
38
+ function capStrings(value, cap) {
39
+ if (typeof value === 'string')
40
+ return value.length > cap ? clipString(value, cap) : value;
41
+ if (Array.isArray(value))
42
+ return value.map((item) => capStrings(item, cap));
43
+ if (value && typeof value === 'object') {
44
+ const out = {};
45
+ for (const [key, item] of Object.entries(value))
46
+ out[key] = capStrings(item, cap);
47
+ return out;
48
+ }
49
+ return value;
50
+ }
51
+ function longestString(value) {
52
+ if (typeof value === 'string')
53
+ return value.length;
54
+ if (value && typeof value === 'object') {
55
+ let longest = 0;
56
+ for (const item of Object.values(value))
57
+ longest = Math.max(longest, longestString(item));
58
+ return longest;
59
+ }
60
+ return 0;
61
+ }
62
+ /** Every non-empty list in the value, the largest first. */
63
+ function listSites(holder, key, path, out = []) {
64
+ const value = holder[key];
65
+ if (Array.isArray(value)) {
66
+ if (value.length > 0)
67
+ out.push({ holder, key, path, size: JSON.stringify(value).length });
68
+ value.forEach((_, index) => listSites(value, index, `${path}[${index}]`, out));
69
+ }
70
+ else if (value && typeof value === 'object') {
71
+ for (const child of Object.keys(value))
72
+ listSites(value, child, path ? `${path}.${child}` : child, out);
73
+ }
74
+ return out.sort((a, b) => b.size - a.size);
75
+ }
76
+ /**
77
+ * Fits a result into its budget, keeping it valid JSON of the same shape.
78
+ *
79
+ * @param result The raw tool result
80
+ * @param maxChars The serialized-JSON budget
81
+ * @returns The result itself when it fits, a shrunken copy, or a small object
82
+ * saying it could not be shrunk
83
+ */
84
+ function clipToolResult(result, maxChars) {
85
+ const serialized = JSON.stringify(result);
86
+ if (serialized === undefined || serialized.length <= maxChars) {
87
+ return result;
88
+ }
89
+ const originalChars = serialized.length;
90
+ if (typeof result === 'string') {
91
+ const marker = `…(clipped from ${originalChars} characters)`;
92
+ const keep = Math.max(0, maxChars - marker.length - 2);
93
+ return `${result.slice(0, keep)}${marker}`;
94
+ }
95
+ if (result && typeof result === 'object') {
96
+ const fitted = fitStructure(JSON.parse(serialized), maxChars, originalChars);
97
+ if (fitted !== undefined)
98
+ return fitted;
99
+ }
100
+ return {
101
+ _truncated: true,
102
+ _originalChars: originalChars,
103
+ error: `The result was ${originalChars} characters, over this tool's ${maxChars}-character ` +
104
+ 'budget, and could not be clipped to fit. Call the tool again for less at a time.',
105
+ };
106
+ }
107
+ /**
108
+ * Steps 1 and 2. Works on plain JSON — the caller round-trips the result first,
109
+ * so a Date is already its string and a class instance its fields.
110
+ * @returns The fitted result, or undefined when nothing left to shrink would do it
111
+ */
112
+ function fitStructure(plain, maxChars, originalChars) {
113
+ const isList = Array.isArray(plain);
114
+ const omitted = {};
115
+ const annotate = (value) => isList
116
+ ? value
117
+ : {
118
+ ...value,
119
+ _truncated: true,
120
+ _originalChars: originalChars,
121
+ ...(Object.keys(omitted).length ? { _omitted: { ...omitted } } : {}),
122
+ };
123
+ const fits = (value) => JSON.stringify(annotate(value)).length <= maxChars;
124
+ // 1. Cut the longest strings to the longest length at which everything fits.
125
+ const longest = longestString(plain);
126
+ if (longest > MIN_CLIPPED_CHARS) {
127
+ let low = MIN_CLIPPED_CHARS;
128
+ let high = longest - 1;
129
+ let best;
130
+ while (low <= high) {
131
+ const cap = Math.floor((low + high) / 2);
132
+ const candidate = capStrings(plain, cap);
133
+ if (fits(candidate)) {
134
+ best = candidate;
135
+ low = cap + 1;
136
+ }
137
+ else {
138
+ high = cap - 1;
139
+ }
140
+ }
141
+ if (best !== undefined)
142
+ return annotate(best);
143
+ }
144
+ // 2. Strings as short as they go; the largest lists give up items from the end.
145
+ const box = { root: longest > MIN_CLIPPED_CHARS ? capStrings(plain, MIN_CLIPPED_CHARS) : plain };
146
+ const trimmed = new Set();
147
+ while (!fits(box.root)) {
148
+ const site = listSites(box, 'root', '').find(({ holder, key }) => !trimmed.has(holder[key]));
149
+ if (!site)
150
+ return undefined;
151
+ const list = site.holder[site.key];
152
+ const keepFirst = (count) => {
153
+ const kept = list.slice(0, count);
154
+ const left = list.length - count;
155
+ // A bare list has nowhere else to say what was dropped.
156
+ if (isList && left > 0)
157
+ kept.push(`…and ${left} more item(s), left out to fit`);
158
+ return kept;
159
+ };
160
+ // The most items that fit, if any number does.
161
+ let low = 0;
162
+ let high = list.length - 1;
163
+ let keep = 0;
164
+ while (low <= high) {
165
+ const count = Math.floor((low + high) / 2);
166
+ site.holder[site.key] = keepFirst(count);
167
+ if (!isList)
168
+ omitted[site.path || '(result)'] = list.length - count;
169
+ if (fits(box.root)) {
170
+ keep = count;
171
+ low = count + 1;
172
+ }
173
+ else {
174
+ high = count - 1;
175
+ }
176
+ }
177
+ site.holder[site.key] = keepFirst(keep);
178
+ if (!isList)
179
+ omitted[site.path || '(result)'] = list.length - keep;
180
+ trimmed.add(site.holder[site.key]);
181
+ }
182
+ return annotate(box.root);
183
+ }
@@ -0,0 +1,18 @@
1
+ import { NativeToolDefinition } from '../native-tool.types';
2
+ /**
3
+ * Makes a picture to order: the calling agent describes it, the room's artist
4
+ * draws it once.
5
+ *
6
+ * Not `illustrate`, which asks the room's illustrator for a picture of the scene.
7
+ * That pipeline belongs to stories — it decides for itself whether a picture is
8
+ * warranted, draws a setting before it draws the moment, and gives everyone named
9
+ * a portrait first. An assistant asked for "a flatbed hauling steel coils, for a
10
+ * proposal cover" wants none of that, and an agent able to hold a conversation can
11
+ * write the image prompt itself, so here the description goes to the image model
12
+ * as written.
13
+ *
14
+ * Returns as soon as the request is accepted, for the same reason `illustrate`
15
+ * does: drawing can outlast a tool call. The picture arrives in the room on its
16
+ * own, as a message captioned with the title.
17
+ */
18
+ export declare const createImageTool: NativeToolDefinition;
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createImageTool = void 0;
4
+ const coerce_1 = require("../shared/coerce");
5
+ /** Longest title kept: it is a caption and an artifact name, not a description. */
6
+ const MAX_TITLE_CHARS = 120;
7
+ /**
8
+ * Makes a picture to order: the calling agent describes it, the room's artist
9
+ * draws it once.
10
+ *
11
+ * Not `illustrate`, which asks the room's illustrator for a picture of the scene.
12
+ * That pipeline belongs to stories — it decides for itself whether a picture is
13
+ * warranted, draws a setting before it draws the moment, and gives everyone named
14
+ * a portrait first. An assistant asked for "a flatbed hauling steel coils, for a
15
+ * proposal cover" wants none of that, and an agent able to hold a conversation can
16
+ * write the image prompt itself, so here the description goes to the image model
17
+ * as written.
18
+ *
19
+ * Returns as soon as the request is accepted, for the same reason `illustrate`
20
+ * does: drawing can outlast a tool call. The picture arrives in the room on its
21
+ * own, as a message captioned with the title.
22
+ */
23
+ exports.createImageTool = {
24
+ name: 'create_image',
25
+ description: 'Make a picture: a photograph, illustration, icon, diagram-style graphic or anything else that can be drawn. ' +
26
+ 'Write the description the image model will draw from — the subject, the setting, the composition, the style ' +
27
+ '("a clean flat vector illustration", "a photograph in soft morning light") and any colours that matter. ' +
28
+ 'It is drawn exactly as written, so be concrete; the model knows nothing of this conversation. ' +
29
+ 'Image models render words unreliably: ask for text in the picture only when it is short, and quote it exactly. ' +
30
+ 'The picture does NOT come back in the result: it appears in the room a minute or so later, on its own. ' +
31
+ 'One picture per turn.',
32
+ parameters: [
33
+ {
34
+ name: 'description',
35
+ type: 'string',
36
+ description: 'What to draw, in full, e.g. "A photograph of a red semi-truck with a flatbed trailer hauling steel coils on a desert interstate at sunrise, three-quarter view from the roadside, warm light, sharp focus"',
37
+ required: true,
38
+ },
39
+ {
40
+ name: 'title',
41
+ type: 'string',
42
+ description: 'A short name for the picture, e.g. "Flatbed at sunrise" — it becomes the caption.',
43
+ required: true,
44
+ },
45
+ {
46
+ name: 'aspect',
47
+ type: 'string',
48
+ description: 'The shape of the picture: "landscape" (wider than tall), "portrait" (taller than wide) or "square". Optional — leave it out for the room\'s usual shape.',
49
+ required: false,
50
+ enum: ['square', 'landscape', 'portrait'],
51
+ },
52
+ ],
53
+ async handler(args, helpers) {
54
+ if (!helpers?.illustration) {
55
+ throw new Error('Making a picture works on a room and there is no room here. Run it from a room rather than the tool tester.');
56
+ }
57
+ const description = (0, coerce_1.str)(args.description, 'description').trim();
58
+ const title = (0, coerce_1.str)(args.title, 'title').trim().slice(0, MAX_TITLE_CHARS);
59
+ if (!description) {
60
+ throw new Error('description is empty. Say what the picture should show.');
61
+ }
62
+ if (!title) {
63
+ throw new Error('title is empty. Give the picture a short name.');
64
+ }
65
+ // Already checked against the enum before the handler runs.
66
+ const aspect = args.aspect ? (0, coerce_1.str)(args.aspect, 'aspect') : undefined;
67
+ const ticket = helpers.illustration.create(description, title, aspect);
68
+ if (ticket.accepted === true) {
69
+ return {
70
+ requested: true,
71
+ summary: `Picture requested: ${title}`,
72
+ note: 'It is being drawn and will appear in the room in a minute or so. Do not wait for it.',
73
+ };
74
+ }
75
+ // Refusals come back successfully rather than thrown, as `illustrate`'s do:
76
+ // they are rulings the caller acts on, not broken calls.
77
+ if (ticket.reason === 'turn_limit') {
78
+ return {
79
+ requested: false,
80
+ violation: 'turn_limit',
81
+ message: 'You have already asked for a picture this turn.',
82
+ rule: 'One picture per turn — each one costs real money.',
83
+ options: ['Make the next one on a later turn.'],
84
+ summary: 'Picture refused: one per turn',
85
+ };
86
+ }
87
+ return {
88
+ requested: false,
89
+ violation: 'images_disabled',
90
+ message: 'This room has no image model configured, so no picture can be made.',
91
+ options: ['Carry on without one, and do not offer to make pictures.'],
92
+ summary: 'Picture refused: images are off',
93
+ };
94
+ },
95
+ };
@@ -16,6 +16,14 @@ const READ_PART_CHARS = 20_000;
16
16
  const SEARCH_BUDGET = 14_000;
17
17
  /** One excerpt's ceiling, so a single long passage cannot crowd out the rest. */
18
18
  const EXCERPT_CHARS = 1_500;
19
+ /**
20
+ * Serialized characters of a listing, under the tool's own budget. A listing is
21
+ * kept whole in the caller's history, so this is the most a library can cost to
22
+ * look at; past it the listing pages.
23
+ */
24
+ const LIST_BUDGET = 14_000;
25
+ /** A summary in a listing: enough to tell documents apart. Searching and reading say more. */
26
+ const LIST_SUMMARY_CHARS = 150;
19
27
  const DEFAULT_HITS = 8;
20
28
  const MAX_HITS = 20;
21
29
  /** Rough characters per token, for telling an agent what holding a document costs. */
@@ -75,34 +83,146 @@ function optionalString(value, param) {
75
83
  function clip(text, max) {
76
84
  return text.length <= max ? text : `${text.slice(0, max).trimEnd()} …`;
77
85
  }
86
+ /** One document as a listing shows it. */
87
+ function listedEntry(document, held, withSummary) {
88
+ return {
89
+ documentId: document.documentId,
90
+ name: document.name,
91
+ ...(document.kind ? { kind: document.kind } : {}),
92
+ pages: document.pages,
93
+ chars: document.chars,
94
+ ...(document.addedAt ? { addedAt: document.addedAt } : {}),
95
+ ...(document.state && document.state !== 'ready' ? { state: document.state } : {}),
96
+ ...(held.has(document.documentId) ? { heldInFull: true } : {}),
97
+ ...(withSummary && document.summary ? { summary: clip(document.summary, LIST_SUMMARY_CHARS) } : {}),
98
+ };
99
+ }
100
+ /** How many documents in scope have each kind, spelled as the host spells it. */
101
+ function kindCounts(documents) {
102
+ const counts = {};
103
+ for (const document of documents) {
104
+ if (document.kind)
105
+ counts[document.kind] = (counts[document.kind] ?? 0) + 1;
106
+ }
107
+ return counts;
108
+ }
109
+ /**
110
+ * As much of a listing as fits the budget, giving up detail before documents.
111
+ *
112
+ * An agent asked what a library holds needs every document's name more than any
113
+ * one document's summary: a listing that ran out of room once had an agent tell
114
+ * a person that only the three policies its search had happened to find existed.
115
+ * So, in order: every document with its summary; every document without; then a
116
+ * page without, which the caller marks as one.
117
+ *
118
+ * @param documents The documents from the requested offset on
119
+ * @param budget Serialized characters the documents may take
120
+ */
121
+ function fitListing(documents, held, budget) {
122
+ const withSummaries = documents.map((document) => listedEntry(document, held, true));
123
+ if (JSON.stringify(withSummaries).length <= budget) {
124
+ return { documents: withSummaries, summaries: true };
125
+ }
126
+ const page = [];
127
+ let size = 2; // the brackets
128
+ for (const document of documents) {
129
+ const entry = listedEntry(document, held, false);
130
+ const entrySize = JSON.stringify(entry).length + 1;
131
+ // Always at least one, so a caller paging through can never stall.
132
+ if (page.length > 0 && size + entrySize > budget)
133
+ break;
134
+ page.push(entry);
135
+ size += entrySize;
136
+ }
137
+ return { documents: page, summaries: false };
138
+ }
78
139
  exports.listDocumentsTool = {
79
140
  name: 'list_documents',
80
141
  description: 'Lists the documents available to you: each one\'s documentId, name, kind, page count, ' +
81
142
  'size and a short summary, and which of them you are holding in full. Documents can ' +
82
- 'be added while you work, so list again rather than relying on an earlier answer.',
83
- parameters: [],
84
- handler: async (_args, helpers, context) => {
143
+ 'be added while you work, so list again rather than relying on an earlier answer. ' +
144
+ 'A large library comes back without summaries, or in pages: when the result has a ' +
145
+ 'nextOffset you have NOT seen every document — call again with that offset, or narrow ' +
146
+ 'with kind or name, before saying what the library holds.',
147
+ parameters: [
148
+ {
149
+ name: 'kind',
150
+ type: 'string',
151
+ description: 'Only documents of this kind. The result\'s `kinds` lists the kinds there are.',
152
+ required: false,
153
+ },
154
+ {
155
+ name: 'name',
156
+ type: 'string',
157
+ description: 'Only documents whose name contains this text, e.g. "declarations".',
158
+ required: false,
159
+ },
160
+ {
161
+ name: 'offset',
162
+ type: 'number',
163
+ description: 'Skip this many documents — pass the nextOffset a previous listing gave you.',
164
+ required: false,
165
+ },
166
+ ],
167
+ handler: async (args, helpers, context) => {
85
168
  if (!(0, document_registry_1.hasDocumentSources)())
86
169
  return unavailable;
87
- const scope = await inScope(context);
170
+ const kind = optionalString(args.kind, 'kind').toLowerCase();
171
+ const name = optionalString(args.name, 'name').toLowerCase();
172
+ const offset = Math.max(0, (0, coerce_1.int)(args.offset, 'offset', 0));
173
+ const everything = (await inScope(context)).map(({ document }) => document);
174
+ const kinds = kindCounts(everything);
175
+ if (kind && !everything.some((document) => (document.kind || '').toLowerCase() === kind)) {
176
+ return {
177
+ ok: false,
178
+ summary: `No documents of kind "${kind}"`,
179
+ error: Object.keys(kinds).length
180
+ ? `There are no documents of kind "${kind}". Use one of these kinds, or leave kind out:`
181
+ : 'No document here has a kind. Leave kind out.',
182
+ kinds,
183
+ };
184
+ }
185
+ const matching = everything.filter((document) => (!kind || (document.kind || '').toLowerCase() === kind) &&
186
+ (!name || (document.name || '').toLowerCase().includes(name)));
187
+ const total = matching.length;
188
+ const narrowed = kind || name ? ` matching${kind ? ` kind "${kind}"` : ''}${name ? ` name "${name}"` : ''}` : '';
189
+ if (offset > 0 && offset >= total) {
190
+ return {
191
+ ok: true,
192
+ summary: `No documents past ${total}`,
193
+ total,
194
+ kinds,
195
+ note: `There are ${total} document(s)${narrowed}, so offset ${offset} is past the end. Use an offset below ${total}.`,
196
+ documents: [],
197
+ };
198
+ }
88
199
  const held = await heldLibraryIds(helpers);
200
+ const page = fitListing(matching.slice(offset), held, LIST_BUDGET - JSON.stringify(kinds).length);
201
+ const shownTo = offset + page.documents.length;
202
+ const partial = offset > 0 || shownTo < total;
203
+ const notes = [];
204
+ if (!page.summaries) {
205
+ notes.push('Summaries are left out so that the list fits. List with kind or name to see them for fewer documents.');
206
+ }
207
+ if (shownTo < total) {
208
+ notes.push(`This is documents ${offset + 1} to ${shownTo} of ${total}, not all of them. Call list_documents ` +
209
+ `with offset ${shownTo} for the rest, or narrow with kind or name. Do not say what the ` +
210
+ 'library holds until you have seen all of it.');
211
+ }
89
212
  return {
90
213
  ok: true,
91
- summary: `Listed ${scope.length} document(s)`,
92
- documents: scope.map(({ document }) => ({
93
- documentId: document.documentId,
94
- name: document.name,
95
- ...(document.kind ? { kind: document.kind } : {}),
96
- pages: document.pages,
97
- chars: document.chars,
98
- ...(document.addedAt ? { addedAt: document.addedAt } : {}),
99
- ...(document.state && document.state !== 'ready' ? { state: document.state } : {}),
100
- ...(held.has(document.documentId) ? { heldInFull: true } : {}),
101
- ...(document.summary ? { summary: clip(document.summary, 600) } : {}),
102
- })),
214
+ summary: partial
215
+ ? `Listed ${offset + 1}-${shownTo} of ${total} document(s)${narrowed}`
216
+ : `Listed ${total} document(s)${narrowed}`,
217
+ total,
218
+ ...(offset > 0 ? { offset } : {}),
219
+ ...(shownTo < total ? { nextOffset: shownTo } : {}),
220
+ kinds,
221
+ ...(notes.length ? { note: notes.join(' ') } : {}),
222
+ documents: page.documents,
103
223
  };
104
224
  },
105
- maxResultChars: 12_000,
225
+ maxResultChars: 16_000,
106
226
  timeoutMs: 15_000,
107
227
  };
108
228
  exports.findInDocumentsTool = {
@@ -16,6 +16,7 @@
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.CORE_TOOL_GROUP = void 0;
18
18
  exports.coreTools = coreTools;
19
+ const create_image_tool_1 = require("./create-image.tool");
19
20
  const data_tools_1 = require("./data.tools");
20
21
  const document_tools_1 = require("./document.tools");
21
22
  const illustrate_tool_1 = require("./illustrate.tool");
@@ -30,5 +31,12 @@ exports.CORE_TOOL_GROUP = 'core';
30
31
  * @returns The tool definitions
31
32
  */
32
33
  function coreTools() {
33
- return [rename_tool_1.renameAgentTool, illustrate_tool_1.illustrateTool, data_tools_1.describeDataTool, data_tools_1.queryDataTool, ...document_tools_1.documentTools];
34
+ return [
35
+ rename_tool_1.renameAgentTool,
36
+ illustrate_tool_1.illustrateTool,
37
+ create_image_tool_1.createImageTool,
38
+ data_tools_1.describeDataTool,
39
+ data_tools_1.queryDataTool,
40
+ ...document_tools_1.documentTools,
41
+ ];
34
42
  }
@@ -221,6 +221,19 @@ export type PortraitTicket = {
221
221
  accepted: false;
222
222
  reason: 'images_disabled' | 'turn_limit';
223
223
  };
224
+ /**
225
+ * What {@link ToolIllustration.create} did, or why it did nothing.
226
+ *
227
+ * No `in_flight` refusal: the scene lock exists because a room has one situation
228
+ * and two scenes drawn at once would show a stale one, while a picture made to
229
+ * order has nothing to go stale.
230
+ */
231
+ export type CreateImageTicket = {
232
+ accepted: true;
233
+ } | {
234
+ accepted: false;
235
+ reason: 'images_disabled' | 'turn_limit';
236
+ };
224
237
  /**
225
238
  * Asking the room's illustrator for a picture.
226
239
  *
@@ -254,6 +267,23 @@ export interface ToolIllustration {
254
267
  * else identifies them. An empty profile draws nothing.
255
268
  */
256
269
  portrait(characterName: string, profile: string): PortraitTicket;
270
+ /**
271
+ * Draws exactly what the caller describes, once.
272
+ *
273
+ * The other half of {@link request}. That one hands a scene to the illustrator,
274
+ * which decides whether a picture is warranted and builds it from references and
275
+ * portraits — right for a story, and wrong for an assistant asked for a picture
276
+ * of a thing: it can decline, draw twice, or invent a cast. Here the caller's
277
+ * description is the image prompt, and the artist draws it as written.
278
+ *
279
+ * Returns when the work is queued; the picture arrives in the room as its own
280
+ * message, captioned with `title`, or a notice saying why it could not be made.
281
+ *
282
+ * @param description The image prompt, written by the caller
283
+ * @param title A short name for the picture: its caption and its artifact name
284
+ * @param aspect The shape to draw it in. Absent takes the room's default.
285
+ */
286
+ create(description: string, title: string, aspect?: ImageAspect): CreateImageTicket;
257
287
  }
258
288
  /** A document held in an agent's context. */
259
289
  export interface ToolHeldDocument {
@@ -122,19 +122,12 @@ export declare class ToolExecutionService {
122
122
  /**
123
123
  * Caps an oversized result while keeping it valid JSON of the same shape.
124
124
  *
125
- * This used to serialize, slice at the budget, and return the resulting
126
- * string. That handed the agent unparseable half-JSON with the explanation
127
- * stranded at the end, past the cut — and because the object had become a
128
- * string it also defeated Room.describeToolResult's `detail`/`summary`
129
- * lookup, so the room log lost its readable line for exactly the results a
130
- * person most wanted to read. Instead:
131
- *
132
- * - An object keeps its keys. Its longest string properties are clipped, in
133
- * order, until the whole thing fits, and `_truncated`/`_originalChars`
134
- * record what happened so the agent can say so or ask for less.
135
- * - A bare string is clipped in place with the same marker appended.
136
- * - Anything that cannot be clipped that way — a long array, say — is
137
- * replaced by a small object saying so, which is at least parseable.
125
+ * Never a slice of the serialized JSON: that handed the agent unparseable
126
+ * half-JSON, and because the object had become a string it also defeated
127
+ * Room.describeToolResult's `detail`/`summary` lookup, so the room log lost
128
+ * its readable line for exactly the results a person most wanted to read.
129
+ * How a result shrinks instead — strings first, then list items — is
130
+ * {@link clipToolResult}.
138
131
  *
139
132
  * @param result The raw tool result
140
133
  * @param maxChars The serialized-JSON budget for this tool
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ToolExecutionService = void 0;
4
4
  const logger_1 = require("../common/logger");
5
+ const clip_result_1 = require("./clip-result");
5
6
  const AsyncFunction = Object.getPrototypeOf(async function () { }).constructor;
6
7
  const DEFAULT_TIMEOUT_MS = 30_000;
7
8
  const MAX_TIMEOUT_MS = 120_000;
@@ -232,58 +233,19 @@ class ToolExecutionService {
232
233
  /**
233
234
  * Caps an oversized result while keeping it valid JSON of the same shape.
234
235
  *
235
- * This used to serialize, slice at the budget, and return the resulting
236
- * string. That handed the agent unparseable half-JSON with the explanation
237
- * stranded at the end, past the cut — and because the object had become a
238
- * string it also defeated Room.describeToolResult's `detail`/`summary`
239
- * lookup, so the room log lost its readable line for exactly the results a
240
- * person most wanted to read. Instead:
241
- *
242
- * - An object keeps its keys. Its longest string properties are clipped, in
243
- * order, until the whole thing fits, and `_truncated`/`_originalChars`
244
- * record what happened so the agent can say so or ask for less.
245
- * - A bare string is clipped in place with the same marker appended.
246
- * - Anything that cannot be clipped that way — a long array, say — is
247
- * replaced by a small object saying so, which is at least parseable.
236
+ * Never a slice of the serialized JSON: that handed the agent unparseable
237
+ * half-JSON, and because the object had become a string it also defeated
238
+ * Room.describeToolResult's `detail`/`summary` lookup, so the room log lost
239
+ * its readable line for exactly the results a person most wanted to read.
240
+ * How a result shrinks instead — strings first, then list items — is
241
+ * {@link clipToolResult}.
248
242
  *
249
243
  * @param result The raw tool result
250
244
  * @param maxChars The serialized-JSON budget for this tool
251
245
  * @returns A result that serializes within budget
252
246
  */
253
247
  static truncateResult(result, maxChars) {
254
- const serialized = JSON.stringify(result);
255
- if (serialized === undefined || serialized.length <= maxChars) {
256
- return result;
257
- }
258
- const originalChars = serialized.length;
259
- const marker = `…(clipped from ${originalChars} characters)`;
260
- if (typeof result === 'string') {
261
- const keep = Math.max(0, maxChars - marker.length - 2);
262
- return `${result.slice(0, keep)}${marker}`;
263
- }
264
- if (result && typeof result === 'object' && !Array.isArray(result)) {
265
- const clipped = { ...result, _truncated: true, _originalChars: originalChars };
266
- const stringKeys = Object.keys(clipped)
267
- .filter((key) => typeof clipped[key] === 'string')
268
- .sort((a, b) => clipped[b].length - clipped[a].length);
269
- for (const key of stringKeys) {
270
- const over = JSON.stringify(clipped).length - maxChars;
271
- if (over <= 0)
272
- break;
273
- const value = clipped[key];
274
- const keep = Math.max(0, value.length - over - marker.length);
275
- clipped[key] = `${value.slice(0, keep)}${marker}`;
276
- }
277
- if (JSON.stringify(clipped).length <= maxChars) {
278
- return clipped;
279
- }
280
- }
281
- return {
282
- _truncated: true,
283
- _originalChars: originalChars,
284
- error: `The result was ${originalChars} characters, over this tool's ${maxChars}-character ` +
285
- 'budget, and could not be clipped to fit. Call the tool again for less at a time.',
286
- };
248
+ return (0, clip_result_1.clipToolResult)(result, maxChars);
287
249
  }
288
250
  /** @returns The native tool definitions registered in this process. */
289
251
  listNativeTools() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "briyah",
3
- "version": "2.0.12",
3
+ "version": "2.0.14",
4
4
  "description": "SDK for AI agents, multi-agent rooms, interactive stories, and role-playing games with per-user data isolation and cost tracking",
5
5
  "private": false,
6
6
  "license": "Apache-2.0",