briyah 2.0.13 → 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
@@ -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.',
@@ -3217,7 +3217,13 @@ Recent Message: ${message.getContent()}
3217
3217
  };
3218
3218
  for (const agent of responders) {
3219
3219
  this.pinHistoryOnHandoff(agent, nextMessage);
3220
- 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();
3221
3227
  this.perceive(agent, nextMessage, (message) => {
3222
3228
  agentsInProgress--;
3223
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
+ }
@@ -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() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "briyah",
3
- "version": "2.0.13",
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",