briyah 2.0.6 → 2.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +105 -0
  2. package/data/packs/dnd5e/pack.json +7 -1
  3. package/dist-sdk/server/src/ai/agent.d.ts +27 -0
  4. package/dist-sdk/server/src/ai/agent.js +54 -13
  5. package/dist-sdk/server/src/app/user-service-factory.js +3 -0
  6. package/dist-sdk/server/src/app.controller.d.ts +7 -1
  7. package/dist-sdk/server/src/app.controller.js +55 -0
  8. package/dist-sdk/server/src/app.service.d.ts +114 -2
  9. package/dist-sdk/server/src/app.service.js +181 -4
  10. package/dist-sdk/server/src/documents/document-conversion.d.ts +70 -0
  11. package/dist-sdk/server/src/documents/document-conversion.js +341 -0
  12. package/dist-sdk/server/src/documents/library/chunking.d.ts +65 -0
  13. package/dist-sdk/server/src/documents/library/chunking.js +263 -0
  14. package/dist-sdk/server/src/documents/library/document-guide.builder.d.ts +2 -0
  15. package/dist-sdk/server/src/documents/library/document-guide.builder.js +58 -0
  16. package/dist-sdk/server/src/documents/library/document-registry.d.ts +22 -0
  17. package/dist-sdk/server/src/documents/library/document-registry.js +44 -0
  18. package/dist-sdk/server/src/documents/library/document.types.d.ts +108 -0
  19. package/dist-sdk/server/src/documents/library/document.types.js +20 -0
  20. package/dist-sdk/server/src/documents/library/embedding.d.ts +57 -0
  21. package/dist-sdk/server/src/documents/library/embedding.js +151 -0
  22. package/dist-sdk/server/src/packs/pack-manifest.d.ts +46 -0
  23. package/dist-sdk/server/src/packs/pack-manifest.js +46 -1
  24. package/dist-sdk/server/src/room/artifact-store.service.js +44 -11
  25. package/dist-sdk/server/src/room/artifact.d.ts +8 -0
  26. package/dist-sdk/server/src/room/room.js +7 -1
  27. package/dist-sdk/server/src/rpg/rpg-roster.d.ts +70 -29
  28. package/dist-sdk/server/src/rpg/rpg-roster.js +152 -41
  29. package/dist-sdk/server/src/rpg/rpg.service.d.ts +66 -29
  30. package/dist-sdk/server/src/rpg/rpg.service.js +140 -65
  31. package/dist-sdk/server/src/sdk/index.d.ts +12 -2
  32. package/dist-sdk/server/src/sdk/index.js +27 -1
  33. package/dist-sdk/server/src/tools/core/document.tools.d.ts +39 -0
  34. package/dist-sdk/server/src/tools/core/document.tools.js +391 -0
  35. package/dist-sdk/server/src/tools/core/index.js +2 -1
  36. package/dist-sdk/server/src/tools/native-tool.types.d.ts +37 -0
  37. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +23 -2
  38. package/dist-sdk/server/src/tools/tool-execution.service.js +30 -6
  39. package/dist-sdk/shared/types/app.types.d.ts +39 -5
  40. package/package.json +172 -167
@@ -0,0 +1,391 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.documentTools = exports.unloadDocumentTool = exports.loadDocumentTool = exports.readDocumentTool = exports.findInDocumentsTool = exports.listDocumentsTool = void 0;
4
+ exports.libraryAttachmentName = libraryAttachmentName;
5
+ exports.isLibraryAttachment = isLibraryAttachment;
6
+ exports.libraryDocumentIdOf = libraryDocumentIdOf;
7
+ const coerce_1 = require("../shared/coerce");
8
+ const document_registry_1 = require("../../documents/library/document-registry");
9
+ /** A holding request past this many characters must be confirmed. Override with `DOCUMENT_LOAD_CONFIRM_CHARS`. */
10
+ const DEFAULT_LOAD_CONFIRM_CHARS = 60_000;
11
+ /** Library documents one agent may hold in total. Override with `DOCUMENT_LOAD_MAX_CHARS`. */
12
+ const DEFAULT_LOAD_MAX_CHARS = 400_000;
13
+ /** A page of `read_document` output. Leaves room under the tool budget for the envelope. */
14
+ const READ_PART_CHARS = 20_000;
15
+ /** Serialized characters of search hits, under the tool's own budget. */
16
+ const SEARCH_BUDGET = 14_000;
17
+ /** One excerpt's ceiling, so a single long passage cannot crowd out the rest. */
18
+ const EXCERPT_CHARS = 1_500;
19
+ const DEFAULT_HITS = 8;
20
+ const MAX_HITS = 20;
21
+ /** Rough characters per token, for telling an agent what holding a document costs. */
22
+ const CHARS_PER_TOKEN = 4;
23
+ const LIBRARY_MARKER = /\s\[library ([^\]]+)\]\.md$/;
24
+ /**
25
+ * The file name a held library document is attached under.
26
+ *
27
+ * It carries the document id so a held document can be found again, released,
28
+ * and told apart from the documents an agent's own configuration attached — a
29
+ * host resetting a conversation releases these and keeps those.
30
+ */
31
+ function libraryAttachmentName(documentId, name) {
32
+ const safe = (name || 'Document').replace(/[\\/:*?"<>|\[\]]/g, '_').slice(0, 120);
33
+ return `${safe} [library ${documentId}].md`;
34
+ }
35
+ /** Whether an attachment is a library document an agent chose to hold. */
36
+ function isLibraryAttachment(fileName) {
37
+ return LIBRARY_MARKER.test(fileName || '');
38
+ }
39
+ /** The library document id an attachment holds, or undefined for any other attachment. */
40
+ function libraryDocumentIdOf(fileName) {
41
+ return (fileName || '').match(LIBRARY_MARKER)?.[1];
42
+ }
43
+ function limitFromEnv(name, fallback) {
44
+ const value = Number(process.env[name]);
45
+ return Number.isFinite(value) && value > 0 ? value : fallback;
46
+ }
47
+ const unavailable = {
48
+ ok: false,
49
+ summary: 'No documents are available',
50
+ error: 'This application has not made any documents available to search.',
51
+ };
52
+ /** Every document in scope, each paired with the source that owns it. */
53
+ async function inScope(context) {
54
+ const listed = await Promise.all((0, document_registry_1.listDocumentSources)().map(async (source) => ((await source.list(context)) || []).map((document) => ({ source, document }))));
55
+ return listed.flat();
56
+ }
57
+ /** How an agent is told which documents it could have named. */
58
+ function choices(scope) {
59
+ return scope.map(({ document }) => ({ documentId: document.documentId, name: document.name }));
60
+ }
61
+ function unknownDocument(documentId, scope) {
62
+ return {
63
+ ok: false,
64
+ summary: `No document "${documentId}"`,
65
+ error: scope.length
66
+ ? `There is no document "${documentId}" here. Use one of these documentIds:`
67
+ : 'There are no documents here yet. The user can add some.',
68
+ ...(scope.length ? { available: choices(scope) } : {}),
69
+ };
70
+ }
71
+ /** An optional string argument: absent, null and empty all mean "not given". */
72
+ function optionalString(value, param) {
73
+ return value === undefined || value === null || value === '' ? '' : (0, coerce_1.str)(value, param);
74
+ }
75
+ function clip(text, max) {
76
+ return text.length <= max ? text : `${text.slice(0, max).trimEnd()} …`;
77
+ }
78
+ exports.listDocumentsTool = {
79
+ name: 'list_documents',
80
+ description: 'Lists the documents available to you: each one\'s documentId, name, kind, page count, ' +
81
+ '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) => {
85
+ if (!(0, document_registry_1.hasDocumentSources)())
86
+ return unavailable;
87
+ const scope = await inScope(context);
88
+ const held = await heldLibraryIds(helpers);
89
+ return {
90
+ 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
+ })),
103
+ };
104
+ },
105
+ maxResultChars: 12_000,
106
+ timeoutMs: 15_000,
107
+ };
108
+ exports.findInDocumentsTool = {
109
+ name: 'find_in_documents',
110
+ description: 'Searches the documents for passages about something, and returns the best matches ' +
111
+ 'with the document, page and section each came from. Search in the words the ' +
112
+ 'documents would use. Pass a documentId to search just one. Use read_document to ' +
113
+ 'see a whole page around a match. Cite the document and page whenever you use a passage.',
114
+ parameters: [
115
+ { name: 'query', type: 'string', description: 'What to look for.', required: true },
116
+ {
117
+ name: 'documentId',
118
+ type: 'string',
119
+ description: 'Search only this document. Omit to search them all.',
120
+ required: false,
121
+ },
122
+ {
123
+ name: 'limit',
124
+ type: 'number',
125
+ description: `How many passages to return, up to ${MAX_HITS}. Defaults to ${DEFAULT_HITS}.`,
126
+ required: false,
127
+ },
128
+ ],
129
+ handler: async (args, _helpers, context) => {
130
+ if (!(0, document_registry_1.hasDocumentSources)())
131
+ return unavailable;
132
+ const query = (0, coerce_1.str)(args.query, 'query');
133
+ if (!query) {
134
+ return { ok: false, summary: 'Nothing to search for', error: 'Say what to look for in "query".' };
135
+ }
136
+ const limit = Math.min(Math.max(1, (0, coerce_1.int)(args.limit, 'limit', DEFAULT_HITS)), MAX_HITS);
137
+ const scope = await inScope(context);
138
+ const wanted = optionalString(args.documentId, 'documentId');
139
+ let targets = scope;
140
+ if (wanted) {
141
+ targets = scope.filter(({ document }) => document.documentId === wanted);
142
+ if (!targets.length)
143
+ return unknownDocument(wanted, scope);
144
+ }
145
+ if (!targets.length) {
146
+ return { ok: true, summary: 'No documents to search', hits: [], note: 'There are no documents here yet.' };
147
+ }
148
+ // Group by source so each is asked only about its own documents.
149
+ const bySource = new Map();
150
+ for (const { source, document } of targets) {
151
+ bySource.set(source, [...(bySource.get(source) || []), document.documentId]);
152
+ }
153
+ // A source only ever knows its own documents, so the ids need passing only
154
+ // to narrow a search to the one the agent named.
155
+ const found = await Promise.all([...bySource].map(([source, documentIds]) => source.search(context, { query, limit, ...(wanted ? { documentIds } : {}) })));
156
+ const hits = found
157
+ .flat()
158
+ .sort((a, b) => b.score - a.score)
159
+ .slice(0, limit);
160
+ const notReady = targets.filter(({ document }) => document.state && document.state !== 'ready');
161
+ const shaped = fitHits(hits);
162
+ return {
163
+ ok: true,
164
+ summary: `Found ${shaped.length} passage(s) for "${clip(query, 60)}"`,
165
+ hits: shaped,
166
+ ...(notReady.length
167
+ ? {
168
+ note: 'These documents are not searchable yet and were not searched: ' +
169
+ notReady.map(({ document }) => `"${document.name}" (${document.state})`).join(', ') +
170
+ '. They can still be read with read_document.',
171
+ }
172
+ : shaped.length
173
+ ? {}
174
+ : { note: 'Nothing matched. Try the words the document itself would use, or read_document.' }),
175
+ };
176
+ },
177
+ maxResultChars: 16_000,
178
+ timeoutMs: 30_000,
179
+ };
180
+ exports.readDocumentTool = {
181
+ name: 'read_document',
182
+ description: 'Reads pages of a document. Give fromPage and toPage for a range, or omit them to read ' +
183
+ 'from the start. Long reads come back in parts — pass the nextPart you were given to ' +
184
+ 'continue. Cite the page numbers you read from.',
185
+ parameters: [
186
+ { name: 'documentId', type: 'string', description: 'The document to read.', required: true },
187
+ { name: 'fromPage', type: 'number', description: 'First page. Defaults to 1.', required: false },
188
+ { name: 'toPage', type: 'number', description: 'Last page. Defaults to the end.', required: false },
189
+ { name: 'part', type: 'number', description: 'Which part of a long read. Defaults to 1.', required: false },
190
+ ],
191
+ handler: async (args, _helpers, context) => {
192
+ if (!(0, document_registry_1.hasDocumentSources)())
193
+ return unavailable;
194
+ const documentId = (0, coerce_1.str)(args.documentId, 'documentId');
195
+ const scope = await inScope(context);
196
+ const match = scope.find(({ document }) => document.documentId === documentId);
197
+ if (!match)
198
+ return unknownDocument(documentId, scope);
199
+ const pageCount = Math.max(1, match.document.pages || 1);
200
+ const requestedFrom = (0, coerce_1.int)(args.fromPage, 'fromPage', 1);
201
+ if (requestedFrom > pageCount) {
202
+ return {
203
+ ok: false,
204
+ summary: 'Page out of range',
205
+ error: `"${match.document.name}" has ${pageCount} page(s); fromPage must be 1 to ${pageCount}.`,
206
+ };
207
+ }
208
+ const from = Math.max(1, requestedFrom);
209
+ const to = Math.min(Math.max(from, (0, coerce_1.int)(args.toPage, 'toPage', pageCount)), pageCount);
210
+ const read = await match.source.read(context, documentId, { from, to });
211
+ if (!read)
212
+ return unknownDocument(documentId, scope);
213
+ const text = read.pages
214
+ .map((page) => `--- Page ${page.pageNum}${page.label ? ` (${page.label})` : ''} ---\n${page.markdown}`)
215
+ .join('\n\n');
216
+ const parts = Math.max(1, Math.ceil(text.length / READ_PART_CHARS));
217
+ const part = Math.min(Math.max(1, (0, coerce_1.int)(args.part, 'part', 1)), parts);
218
+ const body = text.slice((part - 1) * READ_PART_CHARS, part * READ_PART_CHARS);
219
+ return {
220
+ ok: true,
221
+ summary: `Read "${read.name}" pages ${from}–${to}${parts > 1 ? `, part ${part} of ${parts}` : ''}`,
222
+ documentId,
223
+ name: read.name,
224
+ pageCount: read.pageCount,
225
+ fromPage: from,
226
+ toPage: to,
227
+ ...(parts > 1 ? { part, parts, ...(part < parts ? { nextPart: part + 1 } : {}) } : {}),
228
+ text: body,
229
+ };
230
+ },
231
+ maxResultChars: 24_000,
232
+ timeoutMs: 15_000,
233
+ };
234
+ exports.loadDocumentTool = {
235
+ name: 'load_document',
236
+ description: 'Holds a whole document in your context, so you can work across all of it at once. ' +
237
+ 'Use it only when the task needs the entire document — a full review, a summary of ' +
238
+ 'everything, or a comparison of two documents. To answer a question about part of a ' +
239
+ 'document, use find_in_documents and read_document instead: a held document is sent ' +
240
+ 'with every request you make until you unload it. Large documents need confirm: true, ' +
241
+ 'and you will be told the size first.',
242
+ parameters: [
243
+ { name: 'documentId', type: 'string', description: 'The document to hold.', required: true },
244
+ {
245
+ name: 'confirm',
246
+ type: 'boolean',
247
+ description: 'Set true to hold a large document after being told its size.',
248
+ required: false,
249
+ },
250
+ ],
251
+ handler: async (args, helpers, context) => {
252
+ if (!(0, document_registry_1.hasDocumentSources)())
253
+ return unavailable;
254
+ if (!helpers.documents) {
255
+ return {
256
+ ok: false,
257
+ summary: 'Cannot hold documents here',
258
+ error: 'Holding a document needs a calling agent. Use read_document instead.',
259
+ };
260
+ }
261
+ const documentId = (0, coerce_1.str)(args.documentId, 'documentId');
262
+ const scope = await inScope(context);
263
+ const match = scope.find(({ document }) => document.documentId === documentId);
264
+ if (!match)
265
+ return unknownDocument(documentId, scope);
266
+ const held = await helpers.documents.held();
267
+ if (held.some((file) => libraryDocumentIdOf(file.fileName) === documentId)) {
268
+ return {
269
+ ok: true,
270
+ summary: `Already holding "${match.document.name}"`,
271
+ note: 'It is already in your context. Work from it directly.',
272
+ };
273
+ }
274
+ const confirmAbove = limitFromEnv('DOCUMENT_LOAD_CONFIRM_CHARS', DEFAULT_LOAD_CONFIRM_CHARS);
275
+ const ceiling = limitFromEnv('DOCUMENT_LOAD_MAX_CHARS', DEFAULT_LOAD_MAX_CHARS);
276
+ const heldLibrary = held.filter((file) => isLibraryAttachment(file.fileName));
277
+ const alreadyHeld = heldLibrary.reduce((sum, file) => sum + file.chars, 0);
278
+ const size = match.document.chars;
279
+ if (alreadyHeld + size > ceiling) {
280
+ return {
281
+ ok: false,
282
+ summary: `"${match.document.name}" is too large to hold`,
283
+ error: `Holding it would put ${Math.round((alreadyHeld + size) / 1000)}k characters of documents in your ` +
284
+ `context; the limit is ${Math.round(ceiling / 1000)}k. ` +
285
+ (heldLibrary.length
286
+ ? 'Unload a document you have finished with, or read this one in pages with read_document.'
287
+ : 'Read it in pages with read_document, and use find_in_documents to locate what matters.'),
288
+ ...(heldLibrary.length ? { holding: heldLibrary.map(describeHeld) } : {}),
289
+ };
290
+ }
291
+ if (size > confirmAbove && !(0, coerce_1.bool)(args.confirm)) {
292
+ return {
293
+ ok: false,
294
+ summary: `Holding "${match.document.name}" needs confirmation`,
295
+ error: `"${match.document.name}" is about ${Math.round(size / CHARS_PER_TOKEN / 1000)}k tokens ` +
296
+ `(${match.document.pages} page(s)). Holding it adds that to every request you make until you ` +
297
+ 'unload it. If the task needs the whole document, call load_document again with confirm: true. ' +
298
+ 'If it needs part of it, use find_in_documents or read_document.',
299
+ chars: size,
300
+ };
301
+ }
302
+ const text = await match.source.fullText(context, documentId);
303
+ if (!text)
304
+ return unknownDocument(documentId, scope);
305
+ await helpers.documents.attach(libraryAttachmentName(documentId, text.name), `# ${text.name}\n\n${text.markdown}`);
306
+ return {
307
+ ok: true,
308
+ summary: `Holding "${text.name}" in full`,
309
+ note: 'The whole document is in your context from your next step. Unload it with ' +
310
+ 'unload_document when the work that needed it is done.',
311
+ holding: [...heldLibrary.map(describeHeld), { documentId, name: text.name, chars: text.markdown.length }],
312
+ };
313
+ },
314
+ timeoutMs: 30_000,
315
+ };
316
+ exports.unloadDocumentTool = {
317
+ name: 'unload_document',
318
+ description: 'Stops holding a document you loaded with load_document, so it is no longer sent with ' +
319
+ 'every request. You can still search and read it afterwards.',
320
+ parameters: [{ name: 'documentId', type: 'string', description: 'The document to let go of.', required: true }],
321
+ handler: async (args, helpers) => {
322
+ if (!helpers.documents) {
323
+ return { ok: false, summary: 'Cannot hold documents here', error: 'There is nothing held to unload.' };
324
+ }
325
+ const documentId = (0, coerce_1.str)(args.documentId, 'documentId');
326
+ const held = (await helpers.documents.held()).filter((file) => isLibraryAttachment(file.fileName));
327
+ const match = held.find((file) => libraryDocumentIdOf(file.fileName) === documentId);
328
+ if (!match) {
329
+ return {
330
+ ok: false,
331
+ summary: `Not holding "${documentId}"`,
332
+ error: held.length
333
+ ? 'You are not holding that document. You are holding:'
334
+ : 'You are not holding any documents.',
335
+ ...(held.length ? { holding: held.map(describeHeld) } : {}),
336
+ };
337
+ }
338
+ await helpers.documents.detach(match.documentId);
339
+ const name = match.fileName.replace(LIBRARY_MARKER, '');
340
+ return {
341
+ ok: true,
342
+ summary: `Stopped holding "${name}"`,
343
+ holding: held.filter((file) => file !== match).map(describeHeld),
344
+ };
345
+ },
346
+ timeoutMs: 15_000,
347
+ };
348
+ /** Every document tool, in the order an agent would reach for them. */
349
+ exports.documentTools = [
350
+ exports.listDocumentsTool,
351
+ exports.findInDocumentsTool,
352
+ exports.readDocumentTool,
353
+ exports.loadDocumentTool,
354
+ exports.unloadDocumentTool,
355
+ ];
356
+ async function heldLibraryIds(helpers) {
357
+ if (!helpers.documents)
358
+ return new Set();
359
+ const held = await helpers.documents.held();
360
+ return new Set(held.map((file) => libraryDocumentIdOf(file.fileName)).filter(Boolean));
361
+ }
362
+ function describeHeld(file) {
363
+ return {
364
+ documentId: libraryDocumentIdOf(file.fileName),
365
+ name: file.fileName.replace(LIBRARY_MARKER, ''),
366
+ chars: file.chars,
367
+ };
368
+ }
369
+ /** Trims excerpts until the hits fit, keeping every hit's citation whole. */
370
+ function fitHits(hits) {
371
+ let excerptChars = EXCERPT_CHARS;
372
+ let shaped = shape(hits, excerptChars);
373
+ while (JSON.stringify(shaped).length > SEARCH_BUDGET && excerptChars > 200) {
374
+ excerptChars = Math.floor(excerptChars * 0.75);
375
+ shaped = shape(hits, excerptChars);
376
+ }
377
+ while (shaped.length > 1 && JSON.stringify(shaped).length > SEARCH_BUDGET) {
378
+ shaped = shaped.slice(0, -1);
379
+ }
380
+ return shaped;
381
+ }
382
+ function shape(hits, excerptChars) {
383
+ return hits.map((hit) => ({
384
+ documentId: hit.documentId,
385
+ document: hit.name,
386
+ page: hit.pageNum,
387
+ ...(hit.heading ? { section: hit.heading } : {}),
388
+ excerpt: clip(hit.excerpt || '', excerptChars),
389
+ score: Math.round(hit.score * 1000) / 1000,
390
+ }));
391
+ }
@@ -17,6 +17,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.CORE_TOOL_GROUP = void 0;
18
18
  exports.coreTools = coreTools;
19
19
  const data_tools_1 = require("./data.tools");
20
+ const document_tools_1 = require("./document.tools");
20
21
  const illustrate_tool_1 = require("./illustrate.tool");
21
22
  const rename_tool_1 = require("./rename.tool");
22
23
  /** The name the UI groups these under, in place of a pack name. */
@@ -29,5 +30,5 @@ exports.CORE_TOOL_GROUP = 'core';
29
30
  * @returns The tool definitions
30
31
  */
31
32
  function coreTools() {
32
- return [rename_tool_1.renameAgentTool, illustrate_tool_1.illustrateTool, data_tools_1.describeDataTool, data_tools_1.queryDataTool];
33
+ return [rename_tool_1.renameAgentTool, illustrate_tool_1.illustrateTool, data_tools_1.describeDataTool, data_tools_1.queryDataTool, ...document_tools_1.documentTools];
33
34
  }
@@ -254,6 +254,38 @@ export interface ToolIllustration {
254
254
  */
255
255
  portrait(characterName: string, profile: string): PortraitTicket;
256
256
  }
257
+ /** A document held in an agent's context. */
258
+ export interface ToolHeldDocument {
259
+ /** The attachment's id — what {@link ToolAgentDocuments.detach} takes. */
260
+ documentId: string;
261
+ fileName: string;
262
+ /** Its size in characters (bytes, for a binary file). */
263
+ chars: number;
264
+ }
265
+ /**
266
+ * The documents held in the calling agent's context — the ones prepended to
267
+ * every request it makes.
268
+ *
269
+ * Scoped to the caller by Briyah, from the room's own record of who is calling,
270
+ * so a tool can hold documents for the agent that asked and for no other.
271
+ *
272
+ * Holding a document is the expensive way to use it: it rides every one of the
273
+ * agent's subsequent requests until it is detached. It is the right way when the
274
+ * work needs the whole document at once — a full review, a comparison of two —
275
+ * and the wrong way to look one thing up.
276
+ */
277
+ export interface ToolAgentDocuments {
278
+ /**
279
+ * Attaches text to the calling agent's context. A document already held under
280
+ * the same file name is replaced rather than duplicated.
281
+ * @returns The new attachment's id
282
+ */
283
+ attach(fileName: string, body: string): Promise<string>;
284
+ /** Detaches one of the calling agent's documents. @returns Whether it was held */
285
+ detach(documentId: string): Promise<boolean>;
286
+ /** Everything the calling agent holds, including documents its configuration attached. */
287
+ held(): Promise<ToolHeldDocument[]>;
288
+ }
257
289
  export interface ToolHelpers {
258
290
  fetch: typeof fetch;
259
291
  /**
@@ -273,6 +305,11 @@ export interface ToolHelpers {
273
305
  * rather than dereferencing it.
274
306
  */
275
307
  illustration?: ToolIllustration;
308
+ /**
309
+ * The documents held in the calling agent's context. Absent when there is no
310
+ * calling agent — the tool-test endpoint — or the host wired no store.
311
+ */
312
+ documents?: ToolAgentDocuments;
276
313
  }
277
314
  /**
278
315
  * An opaque, per-invocation value supplied by the host when it starts an
@@ -1,7 +1,16 @@
1
1
  import { ToolDefinition, ToolRunResult } from '../../../shared/types/app.types';
2
2
  import { ToolStoreService } from './tool-store.service';
3
3
  import { NativeToolRegistry } from './native-tool-registry.service';
4
- import { NativeToolDefinition, ToolHelpers, ToolContext, ToolIllustration, ToolPackDocuments, ToolRoomAccess } from './native-tool.types';
4
+ import { NativeToolDefinition, ToolHeldDocument, ToolHelpers, ToolContext, ToolIllustration, ToolPackDocuments, ToolRoomAccess } from './native-tool.types';
5
+ /**
6
+ * @internal What {@link ToolAgentDocuments} is built on: attachment for any agent,
7
+ * by id. Tools never see this — they get a copy bound to the calling agent.
8
+ */
9
+ export interface AgentDocumentStore {
10
+ attach(agentId: string, fileName: string, body: string): Promise<string>;
11
+ detach(agentId: string, documentId: string): Promise<boolean>;
12
+ held(agentId: string): Promise<ToolHeldDocument[]>;
13
+ }
5
14
  type CompiledTool = (args: Record<string, any>, helpers: ToolHelpers, context: ToolContext) => Promise<any>;
6
15
  /**
7
16
  * Executes tools an agent calls with the EXECUTE action. Tools come from two
@@ -21,6 +30,7 @@ export declare class ToolExecutionService {
21
30
  private readonly allowUserAuthoredTools;
22
31
  private readonly packDocuments?;
23
32
  private compiledCache;
33
+ private agentDocuments?;
24
34
  /**
25
35
  * @param toolStore The user's store of user-authored tools
26
36
  * @param nativeRegistry The process-wide registry of host-implemented tools
@@ -38,6 +48,11 @@ export declare class ToolExecutionService {
38
48
  * @returns The compiled async function
39
49
  */
40
50
  static compile(tool: ToolDefinition): CompiledTool;
51
+ /**
52
+ * @internal Wires the store behind `helpers.documents`. Set after construction
53
+ * because the store is the AppService, which is built after this service.
54
+ */
55
+ setAgentDocumentStore(store: AgentDocumentStore): void;
41
56
  /**
42
57
  * The room-facing entry point: validates the grant, the tool, and the
43
58
  * arguments before running. All failures are returned in-band as
@@ -47,9 +62,15 @@ export declare class ToolExecutionService {
47
62
  * @param grantedNames The tool names granted to the calling agent
48
63
  * @param context The host's opaque per-invocation context
49
64
  * @param room Access to the calling agent's room, exposed as helpers.room
65
+ * @param illustration The room's illustration capability, exposed as helpers.illustration
66
+ * @param callerAgentId The calling agent's id, from the room's own record of
67
+ * who is calling — never from anything the agent sent. `helpers.documents`
68
+ * is bound to it.
50
69
  * @returns The tool run result
51
70
  */
52
- runForAgent(name: string, contentJson: string, grantedNames: string[], context?: ToolContext, room?: ToolRoomAccess, illustration?: ToolIllustration): Promise<ToolRunResult>;
71
+ runForAgent(name: string, contentJson: string, grantedNames: string[], context?: ToolContext, room?: ToolRoomAccess, illustration?: ToolIllustration, callerAgentId?: string): Promise<ToolRunResult>;
72
+ /** `helpers.documents` for one agent, or undefined when there is no caller or no store. */
73
+ private documentsFor;
53
74
  /**
54
75
  * Runs a tool for the API test endpoint. Same validation as the agent path,
55
76
  * minus the grant check, so the Test panel shows the errors agents would get.
@@ -24,6 +24,7 @@ class ToolExecutionService {
24
24
  allowUserAuthoredTools;
25
25
  packDocuments;
26
26
  compiledCache = new Map();
27
+ agentDocuments;
27
28
  /**
28
29
  * @param toolStore The user's store of user-authored tools
29
30
  * @param nativeRegistry The process-wide registry of host-implemented tools
@@ -48,6 +49,13 @@ class ToolExecutionService {
48
49
  static compile(tool) {
49
50
  return new AsyncFunction('args', 'helpers', 'context', tool.code);
50
51
  }
52
+ /**
53
+ * @internal Wires the store behind `helpers.documents`. Set after construction
54
+ * because the store is the AppService, which is built after this service.
55
+ */
56
+ setAgentDocumentStore(store) {
57
+ this.agentDocuments = store;
58
+ }
51
59
  /**
52
60
  * The room-facing entry point: validates the grant, the tool, and the
53
61
  * arguments before running. All failures are returned in-band as
@@ -57,9 +65,13 @@ class ToolExecutionService {
57
65
  * @param grantedNames The tool names granted to the calling agent
58
66
  * @param context The host's opaque per-invocation context
59
67
  * @param room Access to the calling agent's room, exposed as helpers.room
68
+ * @param illustration The room's illustration capability, exposed as helpers.illustration
69
+ * @param callerAgentId The calling agent's id, from the room's own record of
70
+ * who is calling — never from anything the agent sent. `helpers.documents`
71
+ * is bound to it.
60
72
  * @returns The tool run result
61
73
  */
62
- async runForAgent(name, contentJson, grantedNames, context, room, illustration) {
74
+ async runForAgent(name, contentJson, grantedNames, context, room, illustration, callerAgentId) {
63
75
  if (!grantedNames.includes(name)) {
64
76
  return { ok: false, error: `Tool "${name}" is not available to you` };
65
77
  }
@@ -75,7 +87,18 @@ class ToolExecutionService {
75
87
  return { ok: false, error: 'Arguments must be a JSON object of named parameters' };
76
88
  }
77
89
  }
78
- return this.runValidated(name, args, context, room, illustration);
90
+ return this.runValidated(name, args, context, room, illustration, this.documentsFor(callerAgentId));
91
+ }
92
+ /** `helpers.documents` for one agent, or undefined when there is no caller or no store. */
93
+ documentsFor(agentId) {
94
+ const store = this.agentDocuments;
95
+ if (!store || !agentId)
96
+ return undefined;
97
+ return {
98
+ attach: (fileName, body) => store.attach(agentId, fileName, body),
99
+ detach: (documentId) => store.detach(agentId, documentId),
100
+ held: () => store.held(agentId),
101
+ };
79
102
  }
80
103
  /**
81
104
  * Runs a tool for the API test endpoint. Same validation as the agent path,
@@ -99,14 +122,14 @@ class ToolExecutionService {
99
122
  * @param room Access to the calling agent's room, if any
100
123
  * @returns The tool run result
101
124
  */
102
- async runValidated(name, args, context, room, illustration) {
125
+ async runValidated(name, args, context, room, illustration, documents) {
103
126
  // Native tools take precedence and are always available.
104
127
  const nativeTool = this.nativeRegistry.getTool(name);
105
128
  if (nativeTool) {
106
129
  const invalid = ToolExecutionService.validateParams(nativeTool.parameters, args);
107
130
  if (invalid)
108
131
  return { ok: false, error: invalid };
109
- return this.execute(name, nativeTool.timeoutMs, nativeTool.maxResultChars, (helpers) => nativeTool.handler(args, helpers, context), room, illustration);
132
+ return this.execute(name, nativeTool.timeoutMs, nativeTool.maxResultChars, (helpers) => nativeTool.handler(args, helpers, context), room, illustration, documents);
110
133
  }
111
134
  if (!this.allowUserAuthoredTools) {
112
135
  return { ok: false, error: `Tool "${name}" does not exist` };
@@ -125,7 +148,7 @@ class ToolExecutionService {
125
148
  catch (e) {
126
149
  return { ok: false, error: `Tool code does not compile: ${e.message}` };
127
150
  }
128
- return this.execute(name, tool.timeoutMs, tool.maxResultChars, (helpers) => fn(args, helpers, context), room, illustration);
151
+ return this.execute(name, tool.timeoutMs, tool.maxResultChars, (helpers) => fn(args, helpers, context), room, illustration, documents);
129
152
  }
130
153
  /**
131
154
  * Checks the LLM-supplied arguments against the declared parameters:
@@ -167,7 +190,7 @@ class ToolExecutionService {
167
190
  * @param room Access to the calling agent's room, omitted when there is none
168
191
  * @returns The tool run result
169
192
  */
170
- async execute(name, toolTimeoutMs, toolMaxResultChars, invoke, room, illustration) {
193
+ async execute(name, toolTimeoutMs, toolMaxResultChars, invoke, room, illustration, documents) {
171
194
  const timeoutMs = Math.min(toolTimeoutMs || DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS);
172
195
  const controller = new AbortController();
173
196
  const helpers = {
@@ -175,6 +198,7 @@ class ToolExecutionService {
175
198
  ...(room ? { room } : {}),
176
199
  ...(illustration ? { illustration } : {}),
177
200
  ...(this.packDocuments ? { packDocuments: this.packDocuments } : {}),
201
+ ...(documents ? { documents } : {}),
178
202
  };
179
203
  let timeoutHandle;
180
204
  const timeout = new Promise((_, reject) => {