briyah 2.0.13 → 2.0.15

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
@@ -1390,6 +1395,26 @@ current scene, and it is built for stories: it decides whether a picture is warr
1390
1395
  setting before the moment, and gives each named character a portrait. Use it for a story-like
1391
1396
  room, and `create_image` for an agent asked to make a picture of something.
1392
1397
 
1398
+ ### Example 15: Telling a room's agents today's date
1399
+
1400
+ A model does not know the date. Asked about "this year" it guesses from the newest thing it has
1401
+ seen. A room that works in the present names a time zone, and every turn its agents take opens
1402
+ with the date and time there — `Today is Monday, November 2, 2026; the time is 9:58 PM
1403
+ (America/Chicago).` — in the uncached per-turn prompt, so it costs no cache.
1404
+
1405
+ ```typescript
1406
+ const { roomId } = await app.createRoom(
1407
+ 'Assistant', goal, agentIds, 'Lisa', 'directed',
1408
+ undefined, undefined, undefined, undefined, undefined,
1409
+ 'America/Chicago', // timeZone: any IANA name
1410
+ );
1411
+ ```
1412
+
1413
+ Leave it out for a story or campaign, which keeps its own clock (the room's situation time).
1414
+ `editRoom` takes it in the same place; an empty string stops it, and a name the runtime does not
1415
+ know is refused with a `ValidationError`. Room Settings has it as "Tell the agents today's date",
1416
+ and a pack room template as `timeZone`.
1417
+
1393
1418
  ## Data Storage
1394
1419
 
1395
1420
  Briyah stores data in the following structure:
@@ -105,6 +105,8 @@ export declare class AppController {
105
105
  illustrationMode?: string;
106
106
  /** The default shape of the room's pictures. Absent means 'square'. */
107
107
  imageAspect?: string;
108
+ /** IANA time zone the agents are told the date in. Absent: not told. */
109
+ timeZone?: string;
108
110
  }): Promise<CreateRoomResponse>;
109
111
  editRoom(req: ExpressRequest, roomId: string, body: {
110
112
  roomName: string;
@@ -124,6 +126,8 @@ export declare class AppController {
124
126
  illustrationMode?: string;
125
127
  /** The default shape of the room's pictures. */
126
128
  imageAspect?: string;
129
+ /** IANA time zone the agents are told the date in. Empty string stops it. */
130
+ timeZone?: string;
127
131
  }): Promise<void>;
128
132
  /**
129
133
  * Creates an agent that belongs to this room and adds it to it.
@@ -902,7 +902,9 @@ let AppController = AppController_1 = class AppController {
902
902
  const imageAspect = AppController_1.parseImageAspect(body.imageAspect);
903
903
  try {
904
904
  const appService = this.getAppService(req);
905
- return await appService.createRoom(body.roomName, body.roomGoal, body.agentIds ?? [], body.roomLeader, turnMode, body.moderator, body.beginInstruction, body.imageModel, illustrationMode, imageAspect);
905
+ return await appService.createRoom(body.roomName, body.roomGoal, body.agentIds ?? [], body.roomLeader, turnMode, body.moderator, body.beginInstruction, body.imageModel, illustrationMode, imageAspect,
906
+ // A name the runtime does not know comes back as a ValidationError: a 400.
907
+ body.timeZone);
906
908
  }
907
909
  catch (error) {
908
910
  logger_1.logger.error(`[${req.user?.sub}] Error creating room ${body.roomName}:`, error);
@@ -921,7 +923,7 @@ let AppController = AppController_1 = class AppController {
921
923
  const imageAspect = AppController_1.parseImageAspect(body.imageAspect);
922
924
  try {
923
925
  const appService = this.getAppService(req);
924
- await appService.editRoom(roomId, body.roomName, body.roomGoal, body.baseRoomDir, body.agentIds, body.roomLeader, turnMode, body.moderator, body.pack, body.beginInstruction, body.imageModel, illustrationMode, imageAspect);
926
+ await appService.editRoom(roomId, body.roomName, body.roomGoal, body.baseRoomDir, body.agentIds, body.roomLeader, turnMode, body.moderator, body.pack, body.beginInstruction, body.imageModel, illustrationMode, imageAspect, body.timeZone);
925
927
  }
926
928
  catch (error) {
927
929
  logger_1.logger.error(`[${req.user?.sub}] Error editing room ${roomId}:`, error);
@@ -474,8 +474,12 @@ export declare class AppService {
474
474
  * `'directed'` prompts only the message's targets. See {@link RoomTurnMode}.
475
475
  * @param moderator - Nickname of the agent that places messages the room cannot
476
476
  * route mechanically. Only consulted in `'moderated'` mode.
477
+ * @param timeZone - An IANA time zone (`America/Chicago`) in which every agent's
478
+ * turn is told today's date and time. Omit for a room that keeps its own clock,
479
+ * as a story does. See `RoomConfig.timeZone`.
477
480
  * @returns Object containing the new `roomId`
478
481
  * @throws {NotFoundError} If any agent ID does not exist
482
+ * @throws {ValidationError} If `timeZone` is not a time zone
479
483
  *
480
484
  * @example
481
485
  * ```typescript
@@ -527,7 +531,13 @@ export declare class AppService {
527
531
  * @param arriving An agent not yet in the room, checked as though it were.
528
532
  */
529
533
  private assertModeratorAvailable;
530
- createRoom(roomName: string, goal: string, agentIds: string[], roomLeader?: string, turnMode?: RoomTurnMode, moderator?: string, beginInstruction?: string, imageModel?: string, illustrationMode?: RoomIllustrationMode, imageAspect?: ImageAspect): Promise<CreateRoomResponse>;
534
+ /**
535
+ * Refuses a time zone the runtime does not know, where the caller can hear it.
536
+ * `Room.setTimeZone` would only warn, and the room's agents would silently go
537
+ * on without a date. Empty is allowed: it means "stop telling them".
538
+ */
539
+ private static assertTimeZone;
540
+ createRoom(roomName: string, goal: string, agentIds: string[], roomLeader?: string, turnMode?: RoomTurnMode, moderator?: string, beginInstruction?: string, imageModel?: string, illustrationMode?: RoomIllustrationMode, imageAspect?: ImageAspect, timeZone?: string): Promise<CreateRoomResponse>;
531
541
  /**
532
542
  * Updates the name, goal, and/or agent membership of an existing room.
533
543
  *
@@ -554,10 +564,13 @@ export declare class AppService {
554
564
  * @param illustrationMode - When the room illustrates itself. Omit to leave unchanged.
555
565
  * @param imageAspect - The shape the room draws in when an `illustrate` call names
556
566
  * none. Omit to leave unchanged. See {@link ImageAspect}.
567
+ * @param timeZone - The IANA time zone the agents are told the date in. Empty
568
+ * string stops telling them. Omit to leave unchanged. See `RoomConfig.timeZone`.
557
569
  * @throws {NotFoundError} If the room does not exist
558
570
  * @throws {OperationFailedError} If attempting to edit a published room instance
571
+ * @throws {ValidationError} If `timeZone` is not a time zone
559
572
  */
560
- editRoom(roomId: string, roomName: string, goal: string, baseRoomDir?: string, agentIds?: string[], roomLeader?: string, turnMode?: RoomTurnMode, moderator?: string, pack?: string, beginInstruction?: string, imageModel?: string, illustrationMode?: RoomIllustrationMode, imageAspect?: ImageAspect): Promise<void>;
573
+ editRoom(roomId: string, roomName: string, goal: string, baseRoomDir?: string, agentIds?: string[], roomLeader?: string, turnMode?: RoomTurnMode, moderator?: string, pack?: string, beginInstruction?: string, imageModel?: string, illustrationMode?: RoomIllustrationMode, imageAspect?: ImageAspect, timeZone?: string): Promise<void>;
561
574
  /**
562
575
  * Separates a room's name from the bare name of an agent that belongs to it.
563
576
  */
@@ -38,6 +38,7 @@ const errors_1 = require("./common/errors");
38
38
  const fs = __importStar(require("fs"));
39
39
  const path = __importStar(require("path"));
40
40
  const room_store_service_1 = require("./room/room-store.service");
41
+ const room_clock_1 = require("./room/room-clock");
41
42
  const prompt_resolver_1 = require("./config/prompt-resolver");
42
43
  const core_1 = require("./tools/core");
43
44
  const app_types_1 = require("../../shared/types/app.types");
@@ -800,8 +801,12 @@ class AppService {
800
801
  * `'directed'` prompts only the message's targets. See {@link RoomTurnMode}.
801
802
  * @param moderator - Nickname of the agent that places messages the room cannot
802
803
  * route mechanically. Only consulted in `'moderated'` mode.
804
+ * @param timeZone - An IANA time zone (`America/Chicago`) in which every agent's
805
+ * turn is told today's date and time. Omit for a room that keeps its own clock,
806
+ * as a story does. See `RoomConfig.timeZone`.
803
807
  * @returns Object containing the new `roomId`
804
808
  * @throws {NotFoundError} If any agent ID does not exist
809
+ * @throws {ValidationError} If `timeZone` is not a time zone
805
810
  *
806
811
  * @example
807
812
  * ```typescript
@@ -884,7 +889,19 @@ class AppService {
884
889
  throw new errors_1.ValidationError(`${names} ${needsModerator.length === 1 ? 'uses' : 'use'} a moderator, ` +
885
890
  `so room "${room.getName()}" needs one. ${reason}`);
886
891
  }
887
- async createRoom(roomName, goal, agentIds, roomLeader, turnMode, moderator, beginInstruction, imageModel, illustrationMode, imageAspect) {
892
+ /**
893
+ * Refuses a time zone the runtime does not know, where the caller can hear it.
894
+ * `Room.setTimeZone` would only warn, and the room's agents would silently go
895
+ * on without a date. Empty is allowed: it means "stop telling them".
896
+ */
897
+ static assertTimeZone(timeZone) {
898
+ const name = timeZone?.trim();
899
+ if (name && !(0, room_clock_1.isTimeZone)(name)) {
900
+ throw new errors_1.ValidationError(`"${name}" is not a time zone. Use an IANA name such as "America/Chicago" or "UTC".`);
901
+ }
902
+ }
903
+ async createRoom(roomName, goal, agentIds, roomLeader, turnMode, moderator, beginInstruction, imageModel, illustrationMode, imageAspect, timeZone) {
904
+ AppService.assertTimeZone(timeZone);
888
905
  // Validate that all agents exist before creating the room
889
906
  for (const agentId of agentIds) {
890
907
  const agent = await this.agentStore.getAgent(agentId);
@@ -922,6 +939,9 @@ class AppService {
922
939
  if (imageAspect !== undefined) {
923
940
  room.setImageAspect(imageAspect);
924
941
  }
942
+ if (timeZone !== undefined) {
943
+ room.setTimeZone(timeZone);
944
+ }
925
945
  // Before saveMetadata, so a room that cannot route its members' messages is
926
946
  // never written to disk.
927
947
  this.assertModeratorAvailable(room);
@@ -958,10 +978,14 @@ class AppService {
958
978
  * @param illustrationMode - When the room illustrates itself. Omit to leave unchanged.
959
979
  * @param imageAspect - The shape the room draws in when an `illustrate` call names
960
980
  * none. Omit to leave unchanged. See {@link ImageAspect}.
981
+ * @param timeZone - The IANA time zone the agents are told the date in. Empty
982
+ * string stops telling them. Omit to leave unchanged. See `RoomConfig.timeZone`.
961
983
  * @throws {NotFoundError} If the room does not exist
962
984
  * @throws {OperationFailedError} If attempting to edit a published room instance
985
+ * @throws {ValidationError} If `timeZone` is not a time zone
963
986
  */
964
- async editRoom(roomId, roomName, goal, baseRoomDir, agentIds, roomLeader, turnMode, moderator, pack, beginInstruction, imageModel, illustrationMode, imageAspect) {
987
+ async editRoom(roomId, roomName, goal, baseRoomDir, agentIds, roomLeader, turnMode, moderator, pack, beginInstruction, imageModel, illustrationMode, imageAspect, timeZone) {
988
+ AppService.assertTimeZone(timeZone);
965
989
  // Get the existing room
966
990
  const room = await this.roomStore.getRoom(roomId);
967
991
  if (!room) {
@@ -1022,6 +1046,9 @@ class AppService {
1022
1046
  if (imageAspect !== undefined) {
1023
1047
  room.setImageAspect(imageAspect);
1024
1048
  }
1049
+ if (timeZone !== undefined) {
1050
+ room.setTimeZone(timeZone);
1051
+ }
1025
1052
  // Catches clearing the moderator, or pointing it at an agent this edit just
1026
1053
  // removed, while a member still needs one.
1027
1054
  this.assertModeratorAvailable(room);
@@ -1288,6 +1315,7 @@ class AppService {
1288
1315
  imageModel: room.getImageModel(),
1289
1316
  illustrationMode: room.getIllustrationMode(),
1290
1317
  imageAspect: room.getImageAspect(),
1318
+ timeZone: room.getTimeZone(),
1291
1319
  baseRoomDir: room.getBaseRoomDir(),
1292
1320
  pack: room.getPack(),
1293
1321
  isPublished: room.getIsPublished(),
@@ -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.',
@@ -127,6 +127,7 @@ class PackInstantiationService {
127
127
  imageModel: template.imageModel,
128
128
  illustrationMode: template.illustrationMode ?? 'on-request',
129
129
  imageAspect: template.imageAspect ?? 'square',
130
+ timeZone: template.timeZone,
130
131
  });
131
132
  room.saveMetadata();
132
133
  return { roomId, agentIds, warnings };
@@ -149,6 +149,12 @@ export interface PackRoomTemplate {
149
149
  illustrationMode?: 'off' | 'on-request' | 'auto';
150
150
  /** The default shape of the room's pictures. Absent means `square`. */
151
151
  imageAspect?: ImageAspect;
152
+ /**
153
+ * The IANA time zone the room's agents are told today's date in. Absent means
154
+ * they are not told — what a story or campaign wants. A name the runtime does
155
+ * not know is dropped when the pack is read.
156
+ */
157
+ timeZone?: string;
152
158
  /**
153
159
  * The roster, as loaded.
154
160
  *
@@ -67,6 +67,7 @@ exports.roomAgentKey = roomAgentKey;
67
67
  const fs = __importStar(require("fs"));
68
68
  const path = __importStar(require("path"));
69
69
  const app_types_1 = require("../../../shared/types/app.types");
70
+ const room_clock_1 = require("../room/room-clock");
70
71
  const prompt_resolver_1 = require("../config/prompt-resolver");
71
72
  const logger_1 = require("../common/logger");
72
73
  /** Subdirectories of a pack, by what they hold. */
@@ -321,6 +322,8 @@ function validateRoomTemplate(value, file) {
321
322
  ? { illustrationMode: value.illustrationMode }
322
323
  : {}),
323
324
  ...(app_types_1.IMAGE_ASPECTS.includes(value.imageAspect) && { imageAspect: value.imageAspect }),
325
+ ...(typeof value.timeZone === 'string' &&
326
+ (0, room_clock_1.isTimeZone)(value.timeZone.trim()) && { timeZone: value.timeZone.trim() }),
324
327
  agents,
325
328
  ...(isValidKey(value.roomLeader) && { roomLeader: value.roomLeader }),
326
329
  ...(isValidKey(value.moderator) && { moderator: value.moderator }),
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Today's real date, for rooms that work in the present.
3
+ *
4
+ * A model knows nothing of the date. Asked about "this year", an agent guesses
5
+ * from the newest thing it has seen, and an assistant answering about policies in
6
+ * force once asked the person to confirm what year it was. So a room can name a
7
+ * time zone, and every turn its agents take starts with the date and time there.
8
+ *
9
+ * Opt-in, never a default: a story or a campaign keeps its own clock (the room's
10
+ * situation time), and a real date beside it would be one more fact for a narrator
11
+ * to get wrong. And never cached: it goes in the per-turn prompt, which is sent
12
+ * uncached and kept out of history, so the minute changing costs nothing.
13
+ */
14
+ /**
15
+ * Whether a name is an IANA time zone this runtime knows — `America/Chicago`,
16
+ * `UTC`. Checked when the setting is made, so a typo is refused there rather than
17
+ * failing every turn afterwards.
18
+ */
19
+ export declare function isTimeZone(name: string): boolean;
20
+ /**
21
+ * The line an agent's turn opens with: "Today is Monday, November 2, 2026; the
22
+ * time is 9:58 PM (America/Chicago)."
23
+ *
24
+ * @param timeZone An IANA time zone, already checked with {@link isTimeZone}
25
+ * @param now The moment to describe. Defaults to now.
26
+ */
27
+ export declare function describeNow(timeZone: string, now?: Date): string;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ /**
3
+ * Today's real date, for rooms that work in the present.
4
+ *
5
+ * A model knows nothing of the date. Asked about "this year", an agent guesses
6
+ * from the newest thing it has seen, and an assistant answering about policies in
7
+ * force once asked the person to confirm what year it was. So a room can name a
8
+ * time zone, and every turn its agents take starts with the date and time there.
9
+ *
10
+ * Opt-in, never a default: a story or a campaign keeps its own clock (the room's
11
+ * situation time), and a real date beside it would be one more fact for a narrator
12
+ * to get wrong. And never cached: it goes in the per-turn prompt, which is sent
13
+ * uncached and kept out of history, so the minute changing costs nothing.
14
+ */
15
+ Object.defineProperty(exports, "__esModule", { value: true });
16
+ exports.isTimeZone = isTimeZone;
17
+ exports.describeNow = describeNow;
18
+ /**
19
+ * Whether a name is an IANA time zone this runtime knows — `America/Chicago`,
20
+ * `UTC`. Checked when the setting is made, so a typo is refused there rather than
21
+ * failing every turn afterwards.
22
+ */
23
+ function isTimeZone(name) {
24
+ if (!name || typeof name !== 'string')
25
+ return false;
26
+ try {
27
+ new Intl.DateTimeFormat('en-US', { timeZone: name });
28
+ return true;
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ /**
35
+ * The line an agent's turn opens with: "Today is Monday, November 2, 2026; the
36
+ * time is 9:58 PM (America/Chicago)."
37
+ *
38
+ * @param timeZone An IANA time zone, already checked with {@link isTimeZone}
39
+ * @param now The moment to describe. Defaults to now.
40
+ */
41
+ function describeNow(timeZone, now = new Date()) {
42
+ const date = now.toLocaleDateString('en-US', {
43
+ timeZone,
44
+ weekday: 'long',
45
+ year: 'numeric',
46
+ month: 'long',
47
+ day: 'numeric',
48
+ });
49
+ const time = now.toLocaleTimeString('en-US', { timeZone, hour: 'numeric', minute: '2-digit' });
50
+ return `Today is ${date}; the time is ${time} (${timeZone}).`;
51
+ }
@@ -92,6 +92,14 @@ export interface RoomConfig {
92
92
  * reused across every later scene whatever its shape.
93
93
  */
94
94
  imageAspect?: ImageAspect;
95
+ /**
96
+ * An IANA time zone (`America/Chicago`) in which every agent's turn is told
97
+ * today's date and time. Absent means the agents are not told, which is right
98
+ * for a story — it keeps its own clock — and was how every room worked before.
99
+ * A room that works in the present, an assistant answering about "this year",
100
+ * should set it. See `room-clock.ts`.
101
+ */
102
+ timeZone?: string;
95
103
  }
96
104
  /**
97
105
  * Every setting a room carries, without its identity or its content.
@@ -258,6 +258,7 @@ let RoomStoreService = RoomStoreService_1 = class RoomStoreService {
258
258
  imageModel: room.getImageModel(),
259
259
  illustrationMode: room.getIllustrationMode(),
260
260
  imageAspect: room.getImageAspect(),
261
+ timeZone: room.getTimeZone(),
261
262
  };
262
263
  }
263
264
  /**
@@ -293,6 +294,7 @@ let RoomStoreService = RoomStoreService_1 = class RoomStoreService {
293
294
  room.setImageModel(settings.imageModel);
294
295
  room.setIllustrationMode(settings.illustrationMode);
295
296
  room.setImageAspect(settings.imageAspect);
297
+ room.setTimeZone(settings.timeZone);
296
298
  room.setRoomLeader(settings.roomLeader);
297
299
  room.setTurnMode(settings.turnMode);
298
300
  room.setModerator(settings.moderator);
@@ -507,6 +509,7 @@ let RoomStoreService = RoomStoreService_1 = class RoomStoreService {
507
509
  room.setImageModel(config.imageModel);
508
510
  room.setIllustrationMode(config.illustrationMode);
509
511
  room.setImageAspect(config.imageAspect);
512
+ room.setTimeZone(config.timeZone);
510
513
  // Add agents to the room (loaded from adjacent agents directory)
511
514
  //
512
515
  // An id that resolves to nothing is a deleted agent the room still
@@ -587,6 +590,7 @@ let RoomStoreService = RoomStoreService_1 = class RoomStoreService {
587
590
  imageModel: room.getImageModel(),
588
591
  illustrationMode: room.getIllustrationMode(),
589
592
  imageAspect: room.getImageAspect(),
593
+ timeZone: room.getTimeZone(),
590
594
  };
591
595
  const metadataPath = path.join(roomDir, 'metadata.json');
592
596
  fs.writeFileSync(metadataPath, JSON.stringify(config, null, 2), 'utf-8');
@@ -159,6 +159,8 @@ export declare class Room {
159
159
  private illustrationMode;
160
160
  /** The default shape of this room's pictures. See {@link RoomConfig.imageAspect}. */
161
161
  private imageAspect;
162
+ /** Where the room tells its agents the date. See {@link RoomConfig.timeZone}. */
163
+ private timeZone;
162
164
  /**
163
165
  * Agents that work for this room but never take a turn in it: the illustrator
164
166
  * and the two artists.
@@ -235,6 +237,14 @@ export declare class Room {
235
237
  */
236
238
  getImageAspect(): ImageAspect;
237
239
  setImageAspect(aspect: ImageAspect | undefined): void;
240
+ /** @returns The time zone this room's agents are told the date in, or undefined when they are not told. */
241
+ getTimeZone(): string | undefined;
242
+ /**
243
+ * @param timeZone An IANA time zone, or empty/undefined to stop telling the
244
+ * agents the date. A name this runtime does not know is ignored with a
245
+ * warning — the endpoints refuse one before it gets here.
246
+ */
247
+ setTimeZone(timeZone: string | undefined): void;
238
248
  /**
239
249
  * Registers an agent that works for this room without ever taking a turn.
240
250
  * Idempotent, since the illustration service resolves its agents on every call.
@@ -1023,12 +1033,13 @@ export declare class Room {
1023
1033
  */
1024
1034
  setSituationTime(time: string): void;
1025
1035
  /**
1026
- * Builds the situation header shared by every agent's transient prompt: the
1027
- * in-story time on its own labeled line (flagged as a 24-hour clock so a character
1028
- * doesn't misread "10:30" as 10:30 PM), followed by the situation text. Either
1029
- * line is omitted when its value is empty.
1036
+ * Builds the situation header shared by every agent's transient prompt: today's
1037
+ * real date, when the room names a time zone; the in-story time on its own
1038
+ * labeled line (flagged as a 24-hour clock so a character doesn't misread
1039
+ * "10:30" as 10:30 PM); then the situation text. Each line is omitted when it
1040
+ * has nothing to say.
1030
1041
  *
1031
- * @returns The time and situation lines, or '' if both are empty
1042
+ * @returns The header lines, or '' if there are none
1032
1043
  */
1033
1044
  private buildSituationHeader;
1034
1045
  /**
@@ -7,6 +7,7 @@ const message_1 = require("./message");
7
7
  const nickname_1 = require("./nickname");
8
8
  const crypto_1 = require("crypto");
9
9
  const errors_1 = require("../common/errors");
10
+ const room_clock_1 = require("./room-clock");
10
11
  const logger_1 = require("../common/logger");
11
12
  /**
12
13
  * A Room that contains agents
@@ -187,6 +188,8 @@ class Room {
187
188
  illustrationMode = 'on-request';
188
189
  /** The default shape of this room's pictures. See {@link RoomConfig.imageAspect}. */
189
190
  imageAspect = 'square';
191
+ /** Where the room tells its agents the date. See {@link RoomConfig.timeZone}. */
192
+ timeZone;
190
193
  /**
191
194
  * Agents that work for this room but never take a turn in it: the illustrator
192
195
  * and the two artists.
@@ -330,6 +333,24 @@ class Room {
330
333
  setImageAspect(aspect) {
331
334
  this.imageAspect = aspect || 'square';
332
335
  }
336
+ /** @returns The time zone this room's agents are told the date in, or undefined when they are not told. */
337
+ getTimeZone() {
338
+ return this.timeZone;
339
+ }
340
+ /**
341
+ * @param timeZone An IANA time zone, or empty/undefined to stop telling the
342
+ * agents the date. A name this runtime does not know is ignored with a
343
+ * warning — the endpoints refuse one before it gets here.
344
+ */
345
+ setTimeZone(timeZone) {
346
+ const name = timeZone?.trim() || undefined;
347
+ if (name && !(0, room_clock_1.isTimeZone)(name)) {
348
+ logger_1.logger.warn(`Room ${this.name}: "${name}" is not a time zone; agents will not be told the date`);
349
+ this.timeZone = undefined;
350
+ return;
351
+ }
352
+ this.timeZone = name;
353
+ }
333
354
  /**
334
355
  * Registers an agent that works for this room without ever taking a turn.
335
356
  * Idempotent, since the illustration service resolves its agents on every call.
@@ -2375,15 +2396,21 @@ Recent Message: ${message.getContent()}
2375
2396
  this.currentSituationTime = time || '';
2376
2397
  }
2377
2398
  /**
2378
- * Builds the situation header shared by every agent's transient prompt: the
2379
- * in-story time on its own labeled line (flagged as a 24-hour clock so a character
2380
- * doesn't misread "10:30" as 10:30 PM), followed by the situation text. Either
2381
- * line is omitted when its value is empty.
2399
+ * Builds the situation header shared by every agent's transient prompt: today's
2400
+ * real date, when the room names a time zone; the in-story time on its own
2401
+ * labeled line (flagged as a 24-hour clock so a character doesn't misread
2402
+ * "10:30" as 10:30 PM); then the situation text. Each line is omitted when it
2403
+ * has nothing to say.
2382
2404
  *
2383
- * @returns The time and situation lines, or '' if both are empty
2405
+ * @returns The header lines, or '' if there are none
2384
2406
  */
2385
2407
  buildSituationHeader() {
2386
2408
  const lines = [];
2409
+ // The real date first, for a room that asked for it (see room-clock.ts). A
2410
+ // story never does, so its in-story time below stays the only clock.
2411
+ if (this.timeZone) {
2412
+ lines.push((0, room_clock_1.describeNow)(this.timeZone));
2413
+ }
2387
2414
  if (this.currentSituationTime) {
2388
2415
  lines.push(`Current time: ${this.currentSituationTime} (24-hour clock)`);
2389
2416
  }
@@ -3217,7 +3244,13 @@ Recent Message: ${message.getContent()}
3217
3244
  };
3218
3245
  for (const agent of responders) {
3219
3246
  this.pinHistoryOnHandoff(agent, nextMessage);
3220
- const continuing = agent.agentNickname === nextMessage.getSender();
3247
+ // Only a directed room selects the sender on purpose, through the bounded
3248
+ // allowance in selectResponders. A broadcast room selects everyone, the
3249
+ // sender included, and there the sender's own message must fall through to
3250
+ // perceive's hearing check, which drops it, rather than be handed back with
3251
+ // a note telling it to carry on: that has an agent answering itself after
3252
+ // every message it sends, with no bound on how many times.
3253
+ const continuing = this.turnMode === 'directed' && agent.agentNickname === nextMessage.getSender();
3221
3254
  this.perceive(agent, nextMessage, (message) => {
3222
3255
  agentsInProgress--;
3223
3256
  // 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
+ }
@@ -8,10 +8,22 @@
8
8
  * names it chose rather than from anything a model produced. That is the whole
9
9
  * safety argument, and it holds without a read-only database role behind it.
10
10
  *
11
- * The DSL arrives as one string parameter because {@link ToolParameter} cannot
11
+ * The DSL is declared as one parameter because {@link ToolParameter} cannot
12
12
  * express nesting. Models reproduce a shown example far more reliably than they
13
- * invent a shape, so the description carries two worked ones.
13
+ * invent a shape, so the description carries two worked ones. But every example
14
+ * a model sees — here and in the data guide — is the query itself, and a model
15
+ * following them sends the query's fields as the arguments, with no `query`
16
+ * around them. Refusing that cost a call on most first questions, so both forms
17
+ * are read: see {@link queryFromArgs}.
14
18
  */
15
19
  import { NativeToolDefinition } from '../native-tool.types';
20
+ /**
21
+ * The query, in either form a model sends it: wrapped in `query` — a JSON string
22
+ * or an object — as the parameter declares, or as the arguments themselves, the
23
+ * way the data guide shows every query. In the second form a nested value sent as
24
+ * a JSON string (`"filters": "[...]"`) is read as the JSON it holds; anything else
25
+ * passes through for {@link validateQuery} to judge.
26
+ */
27
+ export declare function queryFromArgs(args: Record<string, any>): Record<string, any>;
16
28
  export declare const describeDataTool: NativeToolDefinition;
17
29
  export declare const queryDataTool: NativeToolDefinition;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.queryDataTool = exports.describeDataTool = void 0;
4
+ exports.queryFromArgs = queryFromArgs;
4
5
  const coerce_1 = require("../shared/coerce");
5
6
  const data_registry_1 = require("../../data/data-registry");
6
7
  const query_validation_1 = require("../../data/query-validation");
@@ -11,6 +12,38 @@ const QUERY_EXAMPLE = '{"dataset": "claims", "filters": [{"field": "year", "op":
11
12
  '"orderBy": [{"by": "sum_incurred", "dir": "desc"}], "limit": 10}';
12
13
  const LIST_EXAMPLE = '{"dataset": "drivers", "filters": [{"field": "age", "op": "lt", "value": 30}, ' +
13
14
  '{"field": "active", "op": "eq", "value": true}], "select": ["firstName", "lastName", "age"]}';
15
+ /**
16
+ * The query, in either form a model sends it: wrapped in `query` — a JSON string
17
+ * or an object — as the parameter declares, or as the arguments themselves, the
18
+ * way the data guide shows every query. In the second form a nested value sent as
19
+ * a JSON string (`"filters": "[...]"`) is read as the JSON it holds; anything else
20
+ * passes through for {@link validateQuery} to judge.
21
+ */
22
+ function queryFromArgs(args) {
23
+ const wrapped = args?.query;
24
+ if (wrapped !== undefined && wrapped !== null && wrapped !== '') {
25
+ return (0, coerce_1.jsonObject)(wrapped, 'query', QUERY_EXAMPLE);
26
+ }
27
+ if (args?.dataset !== undefined && args.dataset !== null && args.dataset !== '') {
28
+ const fields = {};
29
+ for (const [key, value] of Object.entries(args)) {
30
+ if (key !== 'query')
31
+ fields[key] = parsedIfJson(value);
32
+ }
33
+ return fields;
34
+ }
35
+ throw new coerce_1.ArgumentError('query', wrapped, 'a JSON object naming a dataset', QUERY_EXAMPLE);
36
+ }
37
+ function parsedIfJson(value) {
38
+ if (typeof value !== 'string' || !/^\s*[[{]/.test(value))
39
+ return value;
40
+ try {
41
+ return JSON.parse(value);
42
+ }
43
+ catch {
44
+ return value;
45
+ }
46
+ }
14
47
  /** Names every dataset, for an error that teaches rather than just refuses. */
15
48
  function datasetNames() {
16
49
  return (0, data_registry_1.listDatasets)().map((set) => set.name);
@@ -83,13 +116,17 @@ exports.queryDataTool = {
83
116
  ' To keep only some groups, add "having": conditions on the query\'s own metrics by ' +
84
117
  'their "as", e.g. "having": [{"field": "sum_incurred", "op": "gt", "value": 100000}].' +
85
118
  ' Only the datasets and fields in your data guide exist; if a question needs ' +
86
- 'something that is not there, say so rather than substituting a field that looks close.',
119
+ 'something that is not there, say so rather than substituting a field that looks close.' +
120
+ ' Send the query as `query`, or its fields (dataset, filters, …) as the arguments themselves — either works.',
87
121
  parameters: [
88
122
  {
89
123
  name: 'query',
90
124
  type: 'string',
91
- description: 'The query as a JSON object. Example: ' + QUERY_EXAMPLE,
92
- required: true,
125
+ description: 'The query as a JSON object. Example: ' + QUERY_EXAMPLE +
126
+ ' May be left out when the query\'s own fields are sent as the arguments instead.',
127
+ // Not required, so the unwrapped form reaches the handler: a missing
128
+ // query is refused there, with the example, rather than here.
129
+ required: false,
93
130
  },
94
131
  ],
95
132
  handler: async (args, _helpers, context) => {
@@ -100,7 +137,7 @@ exports.queryDataTool = {
100
137
  error: 'This application has not made any data available to query.',
101
138
  };
102
139
  }
103
- const raw = (0, coerce_1.jsonObject)(args.query, 'query', QUERY_EXAMPLE);
140
+ const raw = queryFromArgs(args);
104
141
  const checked = (0, query_validation_1.validateQuery)(raw, (0, data_registry_1.listDatasets)());
105
142
  if (!checked.ok) {
106
143
  // A refusal, not a malfunction: it names what was allowed instead so
@@ -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 = {
@@ -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() {
@@ -236,6 +236,11 @@ export interface RoomDetails {
236
236
  * for another. Absent means 'square'. See {@link ImageAspect}.
237
237
  */
238
238
  imageAspect?: ImageAspect;
239
+ /**
240
+ * The IANA time zone in which this room's agents are told today's date on every
241
+ * turn. Absent means they are not told — a story keeps its own clock.
242
+ */
243
+ timeZone?: string;
239
244
  /**
240
245
  * Nickname of the agent that places messages it cannot route mechanically.
241
246
  * Only consulted in 'moderated' mode. Absent falls back to the first agent in
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "briyah",
3
- "version": "2.0.13",
3
+ "version": "2.0.15",
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",