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.
- package/README.md +105 -0
- package/data/packs/dnd5e/pack.json +7 -1
- package/dist-sdk/server/src/ai/agent.d.ts +27 -0
- package/dist-sdk/server/src/ai/agent.js +54 -13
- package/dist-sdk/server/src/app/user-service-factory.js +3 -0
- package/dist-sdk/server/src/app.controller.d.ts +7 -1
- package/dist-sdk/server/src/app.controller.js +55 -0
- package/dist-sdk/server/src/app.service.d.ts +114 -2
- package/dist-sdk/server/src/app.service.js +181 -4
- package/dist-sdk/server/src/documents/document-conversion.d.ts +70 -0
- package/dist-sdk/server/src/documents/document-conversion.js +341 -0
- package/dist-sdk/server/src/documents/library/chunking.d.ts +65 -0
- package/dist-sdk/server/src/documents/library/chunking.js +263 -0
- package/dist-sdk/server/src/documents/library/document-guide.builder.d.ts +2 -0
- package/dist-sdk/server/src/documents/library/document-guide.builder.js +58 -0
- package/dist-sdk/server/src/documents/library/document-registry.d.ts +22 -0
- package/dist-sdk/server/src/documents/library/document-registry.js +44 -0
- package/dist-sdk/server/src/documents/library/document.types.d.ts +108 -0
- package/dist-sdk/server/src/documents/library/document.types.js +20 -0
- package/dist-sdk/server/src/documents/library/embedding.d.ts +57 -0
- package/dist-sdk/server/src/documents/library/embedding.js +151 -0
- package/dist-sdk/server/src/packs/pack-manifest.d.ts +46 -0
- package/dist-sdk/server/src/packs/pack-manifest.js +46 -1
- package/dist-sdk/server/src/room/artifact-store.service.js +44 -11
- package/dist-sdk/server/src/room/artifact.d.ts +8 -0
- package/dist-sdk/server/src/room/room.js +7 -1
- package/dist-sdk/server/src/rpg/rpg-roster.d.ts +70 -29
- package/dist-sdk/server/src/rpg/rpg-roster.js +152 -41
- package/dist-sdk/server/src/rpg/rpg.service.d.ts +66 -29
- package/dist-sdk/server/src/rpg/rpg.service.js +140 -65
- package/dist-sdk/server/src/sdk/index.d.ts +12 -2
- package/dist-sdk/server/src/sdk/index.js +27 -1
- package/dist-sdk/server/src/tools/core/document.tools.d.ts +39 -0
- package/dist-sdk/server/src/tools/core/document.tools.js +391 -0
- package/dist-sdk/server/src/tools/core/index.js +2 -1
- package/dist-sdk/server/src/tools/native-tool.types.d.ts +37 -0
- package/dist-sdk/server/src/tools/tool-execution.service.d.ts +23 -2
- package/dist-sdk/server/src/tools/tool-execution.service.js +30 -6
- package/dist-sdk/shared/types/app.types.d.ts +39 -5
- package/package.json +172 -167
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cutting converted documents into passages worth embedding and searching.
|
|
3
|
+
*
|
|
4
|
+
* A chunk is the unit a search returns, so it has to stand on its own when an
|
|
5
|
+
* agent reads it with nothing around it. Three rules follow from that:
|
|
6
|
+
*
|
|
7
|
+
* - **A chunk never spans pages.** Every chunk carries exactly one page number,
|
|
8
|
+
* so a hit can say "page 12" and be right. Without that an agent can quote a
|
|
9
|
+
* clause but not tell the person where to find it, which to someone who has to
|
|
10
|
+
* act on the clause is worse than not quoting it.
|
|
11
|
+
* - **A chunk knows its heading.** Pages are not the only way a reader locates a
|
|
12
|
+
* passage, and for a Word document they are not a way at all — its pagination
|
|
13
|
+
* belongs to whatever renders it. The nearest headings above a chunk travel
|
|
14
|
+
* with it, so a hit can say "under 7.2 Indemnification".
|
|
15
|
+
* - **A table is never cut into rows without its header.** A loss run is mostly
|
|
16
|
+
* one long table; a piece of it without the column names is a list of numbers
|
|
17
|
+
* that means nothing to a search or to a reader. Each piece repeats the header.
|
|
18
|
+
*
|
|
19
|
+
* Sizes are in characters, not tokens: they only need to be roughly right, and a
|
|
20
|
+
* character count needs no tokenizer and gives the same answer everywhere.
|
|
21
|
+
*/
|
|
22
|
+
/** A page to be chunked. Matches both the PDF and the local conversion page shapes. */
|
|
23
|
+
export interface ChunkablePage {
|
|
24
|
+
pageNum: number;
|
|
25
|
+
markdown: string;
|
|
26
|
+
/** A name for the page — a workbook's sheet — used as the heading when the page has none. */
|
|
27
|
+
label?: string;
|
|
28
|
+
}
|
|
29
|
+
/** One searchable passage. */
|
|
30
|
+
export interface DocumentChunk {
|
|
31
|
+
pageNum: number;
|
|
32
|
+
/** Position in the document, from 0. Stable for the same input and options. */
|
|
33
|
+
index: number;
|
|
34
|
+
/** The nearest headings above the chunk, outermost first, joined with ' › '. */
|
|
35
|
+
heading?: string;
|
|
36
|
+
text: string;
|
|
37
|
+
}
|
|
38
|
+
export interface ChunkOptions {
|
|
39
|
+
/** A chunk's target ceiling. Defaults to 1,800 characters. */
|
|
40
|
+
maxChars?: number;
|
|
41
|
+
/**
|
|
42
|
+
* How much of a chunk's end is repeated at the start of the next one on the
|
|
43
|
+
* same page, so a sentence that straddles the cut is whole in one of them.
|
|
44
|
+
* Defaults to 200 characters. Never carried across a heading or a page.
|
|
45
|
+
*/
|
|
46
|
+
overlapChars?: number;
|
|
47
|
+
}
|
|
48
|
+
export declare const DEFAULT_CHUNK_MAX_CHARS = 1800;
|
|
49
|
+
export declare const DEFAULT_CHUNK_OVERLAP_CHARS = 200;
|
|
50
|
+
/**
|
|
51
|
+
* Cuts converted pages into chunks.
|
|
52
|
+
*
|
|
53
|
+
* Headings carry across pages — a section that continues onto the next page is
|
|
54
|
+
* still that section — but chunks and their overlap do not.
|
|
55
|
+
*/
|
|
56
|
+
export declare function chunkPages(pages: readonly ChunkablePage[], options?: ChunkOptions): DocumentChunk[];
|
|
57
|
+
/**
|
|
58
|
+
* The text to embed for a chunk: the passage with where it came from in front.
|
|
59
|
+
*
|
|
60
|
+
* A query like "the Acme contract's termination clause" should find the
|
|
61
|
+
* termination clause in the Acme contract. The passage alone often never names
|
|
62
|
+
* either, so the document's name and the chunk's headings are embedded with it.
|
|
63
|
+
* The stored text stays the bare passage, so nothing is repeated to a reader.
|
|
64
|
+
*/
|
|
65
|
+
export declare function embeddingInput(chunk: DocumentChunk, documentName?: string): string;
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Cutting converted documents into passages worth embedding and searching.
|
|
4
|
+
*
|
|
5
|
+
* A chunk is the unit a search returns, so it has to stand on its own when an
|
|
6
|
+
* agent reads it with nothing around it. Three rules follow from that:
|
|
7
|
+
*
|
|
8
|
+
* - **A chunk never spans pages.** Every chunk carries exactly one page number,
|
|
9
|
+
* so a hit can say "page 12" and be right. Without that an agent can quote a
|
|
10
|
+
* clause but not tell the person where to find it, which to someone who has to
|
|
11
|
+
* act on the clause is worse than not quoting it.
|
|
12
|
+
* - **A chunk knows its heading.** Pages are not the only way a reader locates a
|
|
13
|
+
* passage, and for a Word document they are not a way at all — its pagination
|
|
14
|
+
* belongs to whatever renders it. The nearest headings above a chunk travel
|
|
15
|
+
* with it, so a hit can say "under 7.2 Indemnification".
|
|
16
|
+
* - **A table is never cut into rows without its header.** A loss run is mostly
|
|
17
|
+
* one long table; a piece of it without the column names is a list of numbers
|
|
18
|
+
* that means nothing to a search or to a reader. Each piece repeats the header.
|
|
19
|
+
*
|
|
20
|
+
* Sizes are in characters, not tokens: they only need to be roughly right, and a
|
|
21
|
+
* character count needs no tokenizer and gives the same answer everywhere.
|
|
22
|
+
*/
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.DEFAULT_CHUNK_OVERLAP_CHARS = exports.DEFAULT_CHUNK_MAX_CHARS = void 0;
|
|
25
|
+
exports.chunkPages = chunkPages;
|
|
26
|
+
exports.embeddingInput = embeddingInput;
|
|
27
|
+
exports.DEFAULT_CHUNK_MAX_CHARS = 1_800;
|
|
28
|
+
exports.DEFAULT_CHUNK_OVERLAP_CHARS = 200;
|
|
29
|
+
/** How many levels of heading a chunk carries. Deeper paths stop helping and start costing. */
|
|
30
|
+
const HEADING_DEPTH = 3;
|
|
31
|
+
const PAGE_MARKER = /^<!--\s*Page \d+\s*-->$/;
|
|
32
|
+
/**
|
|
33
|
+
* Cuts converted pages into chunks.
|
|
34
|
+
*
|
|
35
|
+
* Headings carry across pages — a section that continues onto the next page is
|
|
36
|
+
* still that section — but chunks and their overlap do not.
|
|
37
|
+
*/
|
|
38
|
+
function chunkPages(pages, options = {}) {
|
|
39
|
+
const maxChars = Math.max(200, options.maxChars ?? exports.DEFAULT_CHUNK_MAX_CHARS);
|
|
40
|
+
const overlapChars = Math.min(Math.max(0, options.overlapChars ?? exports.DEFAULT_CHUNK_OVERLAP_CHARS), Math.floor(maxChars / 2));
|
|
41
|
+
const chunks = [];
|
|
42
|
+
// Outermost first; index = level - 1.
|
|
43
|
+
const headings = [];
|
|
44
|
+
for (const page of pages) {
|
|
45
|
+
const blocks = splitIntoBlocks(page.markdown || '');
|
|
46
|
+
if (!blocks.length) {
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
let parts = [];
|
|
50
|
+
let size = 0;
|
|
51
|
+
let heading = currentHeading(headings) ?? page.label;
|
|
52
|
+
// Whether the chunk under construction holds anything besides carried-over overlap.
|
|
53
|
+
let hasContent = false;
|
|
54
|
+
let lastWasTable = false;
|
|
55
|
+
const flush = (carryOverlap) => {
|
|
56
|
+
if (!hasContent) {
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const text = parts.join('\n\n').trim();
|
|
60
|
+
chunks.push({ pageNum: page.pageNum, index: chunks.length, ...(heading && { heading }), text });
|
|
61
|
+
const carried = carryOverlap && !lastWasTable ? tail(text, overlapChars) : '';
|
|
62
|
+
parts = carried ? [carried] : [];
|
|
63
|
+
size = carried.length;
|
|
64
|
+
hasContent = false;
|
|
65
|
+
};
|
|
66
|
+
const add = (text, isTable) => {
|
|
67
|
+
if (hasContent && size + text.length + 2 > maxChars) {
|
|
68
|
+
flush(true);
|
|
69
|
+
}
|
|
70
|
+
if (!hasContent) {
|
|
71
|
+
// A chunk is labelled with the heading its own content sits under,
|
|
72
|
+
// not the one its carried-over overlap came from.
|
|
73
|
+
heading = currentHeading(headings) ?? page.label;
|
|
74
|
+
}
|
|
75
|
+
parts.push(text);
|
|
76
|
+
size += text.length + 2;
|
|
77
|
+
hasContent = true;
|
|
78
|
+
lastWasTable = isTable;
|
|
79
|
+
};
|
|
80
|
+
for (const block of blocks) {
|
|
81
|
+
if (block.kind === 'heading') {
|
|
82
|
+
// A new section starts a new chunk, with no overlap from the last
|
|
83
|
+
// one — mixing the end of one clause into the start of the next is
|
|
84
|
+
// exactly what makes a passage misleading out of context.
|
|
85
|
+
flush(false);
|
|
86
|
+
parts = [];
|
|
87
|
+
size = 0;
|
|
88
|
+
headings.length = Math.min(headings.length, block.level - 1);
|
|
89
|
+
headings[block.level - 1] = block.text.replace(/^#+\s*/, '').trim();
|
|
90
|
+
add(block.text, false);
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
for (const piece of fit(block, maxChars)) {
|
|
94
|
+
add(piece, block.kind === 'table');
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
flush(false);
|
|
98
|
+
// Overlap never reaches the next page.
|
|
99
|
+
parts = [];
|
|
100
|
+
size = 0;
|
|
101
|
+
}
|
|
102
|
+
return chunks;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* The text to embed for a chunk: the passage with where it came from in front.
|
|
106
|
+
*
|
|
107
|
+
* A query like "the Acme contract's termination clause" should find the
|
|
108
|
+
* termination clause in the Acme contract. The passage alone often never names
|
|
109
|
+
* either, so the document's name and the chunk's headings are embedded with it.
|
|
110
|
+
* The stored text stays the bare passage, so nothing is repeated to a reader.
|
|
111
|
+
*/
|
|
112
|
+
function embeddingInput(chunk, documentName) {
|
|
113
|
+
const context = [
|
|
114
|
+
documentName ? `Document: ${documentName}` : null,
|
|
115
|
+
chunk.heading ? `Section: ${chunk.heading}` : null,
|
|
116
|
+
`Page: ${chunk.pageNum}`,
|
|
117
|
+
].filter(Boolean);
|
|
118
|
+
return `${context.join('\n')}\n\n${chunk.text}`;
|
|
119
|
+
}
|
|
120
|
+
function currentHeading(headings) {
|
|
121
|
+
const path = headings.filter(Boolean).slice(-HEADING_DEPTH);
|
|
122
|
+
return path.length ? path.join(' › ') : undefined;
|
|
123
|
+
}
|
|
124
|
+
/** Splits a page's Markdown into headings, tables, fenced code and paragraphs. */
|
|
125
|
+
function splitIntoBlocks(markdown) {
|
|
126
|
+
const lines = markdown.replace(/\r\n?/g, '\n').split('\n');
|
|
127
|
+
const blocks = [];
|
|
128
|
+
let paragraph = [];
|
|
129
|
+
const endParagraph = () => {
|
|
130
|
+
const text = paragraph.join('\n').trim();
|
|
131
|
+
if (text) {
|
|
132
|
+
blocks.push({ kind: 'text', text });
|
|
133
|
+
}
|
|
134
|
+
paragraph = [];
|
|
135
|
+
};
|
|
136
|
+
for (let i = 0; i < lines.length; i++) {
|
|
137
|
+
const line = lines[i];
|
|
138
|
+
const trimmed = line.trim();
|
|
139
|
+
if (PAGE_MARKER.test(trimmed)) {
|
|
140
|
+
endParagraph();
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const heading = trimmed.match(/^(#{1,6})\s+\S/);
|
|
144
|
+
if (heading) {
|
|
145
|
+
endParagraph();
|
|
146
|
+
blocks.push({ kind: 'heading', text: trimmed, level: heading[1].length });
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
if (trimmed.startsWith('```')) {
|
|
150
|
+
endParagraph();
|
|
151
|
+
const code = [line];
|
|
152
|
+
while (++i < lines.length) {
|
|
153
|
+
code.push(lines[i]);
|
|
154
|
+
if (lines[i].trim().startsWith('```'))
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
blocks.push({ kind: 'code', text: code.join('\n') });
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (trimmed.startsWith('|')) {
|
|
161
|
+
endParagraph();
|
|
162
|
+
const rows = [trimmed];
|
|
163
|
+
while (i + 1 < lines.length && lines[i + 1].trim().startsWith('|')) {
|
|
164
|
+
rows.push(lines[++i].trim());
|
|
165
|
+
}
|
|
166
|
+
blocks.push({ kind: 'table', text: rows.join('\n') });
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
if (!trimmed) {
|
|
170
|
+
endParagraph();
|
|
171
|
+
continue;
|
|
172
|
+
}
|
|
173
|
+
paragraph.push(line);
|
|
174
|
+
}
|
|
175
|
+
endParagraph();
|
|
176
|
+
return blocks;
|
|
177
|
+
}
|
|
178
|
+
/** Splits a block that would not fit in one chunk; returns it whole when it would. */
|
|
179
|
+
function fit(block, maxChars) {
|
|
180
|
+
if (block.text.length <= maxChars) {
|
|
181
|
+
return [block.text];
|
|
182
|
+
}
|
|
183
|
+
if (block.kind === 'table') {
|
|
184
|
+
return splitTable(block.text, maxChars);
|
|
185
|
+
}
|
|
186
|
+
return splitProse(block.text, maxChars);
|
|
187
|
+
}
|
|
188
|
+
/** Cuts a table between rows, repeating its header and separator at the top of every piece. */
|
|
189
|
+
function splitTable(table, maxChars) {
|
|
190
|
+
const rows = table.split('\n');
|
|
191
|
+
const hasHeader = rows.length > 1 && /^\|\s*:?-{3,}/.test(rows[1]);
|
|
192
|
+
const header = hasHeader ? rows.slice(0, 2) : [];
|
|
193
|
+
const body = hasHeader ? rows.slice(2) : rows;
|
|
194
|
+
const headerSize = header.reduce((sum, row) => sum + row.length + 1, 0);
|
|
195
|
+
const pieces = [];
|
|
196
|
+
let current = [];
|
|
197
|
+
let size = headerSize;
|
|
198
|
+
for (const row of body) {
|
|
199
|
+
if (current.length && size + row.length + 1 > maxChars) {
|
|
200
|
+
pieces.push([...header, ...current].join('\n'));
|
|
201
|
+
current = [];
|
|
202
|
+
size = headerSize;
|
|
203
|
+
}
|
|
204
|
+
// A single row longer than a chunk is kept whole: cutting a row apart
|
|
205
|
+
// would separate a value from the column that names it.
|
|
206
|
+
current.push(row);
|
|
207
|
+
size += row.length + 1;
|
|
208
|
+
}
|
|
209
|
+
if (current.length) {
|
|
210
|
+
pieces.push([...header, ...current].join('\n'));
|
|
211
|
+
}
|
|
212
|
+
return pieces;
|
|
213
|
+
}
|
|
214
|
+
/** Cuts prose between sentences, and a sentence longer than a chunk between words. */
|
|
215
|
+
function splitProse(text, maxChars) {
|
|
216
|
+
const sentences = text.split(/(?<=[.!?;:])\s+(?=\S)/);
|
|
217
|
+
const pieces = [];
|
|
218
|
+
let current = '';
|
|
219
|
+
for (const sentence of sentences) {
|
|
220
|
+
for (const part of sentence.length > maxChars ? splitAtWords(sentence, maxChars) : [sentence]) {
|
|
221
|
+
if (current && current.length + part.length + 1 > maxChars) {
|
|
222
|
+
pieces.push(current);
|
|
223
|
+
current = '';
|
|
224
|
+
}
|
|
225
|
+
current = current ? `${current} ${part}` : part;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
if (current) {
|
|
229
|
+
pieces.push(current);
|
|
230
|
+
}
|
|
231
|
+
return pieces;
|
|
232
|
+
}
|
|
233
|
+
function splitAtWords(text, maxChars) {
|
|
234
|
+
const pieces = [];
|
|
235
|
+
let rest = text;
|
|
236
|
+
while (rest.length > maxChars) {
|
|
237
|
+
let cut = rest.lastIndexOf(' ', maxChars);
|
|
238
|
+
if (cut < maxChars / 2) {
|
|
239
|
+
cut = maxChars; // no usable space: a very long token, cut it
|
|
240
|
+
}
|
|
241
|
+
pieces.push(rest.slice(0, cut).trim());
|
|
242
|
+
rest = rest.slice(cut).trim();
|
|
243
|
+
}
|
|
244
|
+
if (rest) {
|
|
245
|
+
pieces.push(rest);
|
|
246
|
+
}
|
|
247
|
+
return pieces;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* The end of a chunk to carry into the next one, starting at a word boundary.
|
|
251
|
+
*
|
|
252
|
+
* A chunk shorter than twice the overlap carries nothing: the overlap exists to
|
|
253
|
+
* bridge a cut through a passage, and carrying most of a short chunk forward
|
|
254
|
+
* would repeat it rather than bridge anything.
|
|
255
|
+
*/
|
|
256
|
+
function tail(text, maxChars) {
|
|
257
|
+
if (maxChars <= 0 || text.length < maxChars * 2) {
|
|
258
|
+
return '';
|
|
259
|
+
}
|
|
260
|
+
const start = text.length - maxChars;
|
|
261
|
+
const boundary = text.indexOf(' ', start);
|
|
262
|
+
return (boundary === -1 ? text.slice(start) : text.slice(boundary + 1)).trim();
|
|
263
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildDocumentGuideMarkdown = buildDocumentGuideMarkdown;
|
|
4
|
+
/**
|
|
5
|
+
* Renders how to use the document library, as a document to attach to an agent.
|
|
6
|
+
*
|
|
7
|
+
* Unlike the data guide, this does not list what is in the library. A library
|
|
8
|
+
* changes while an agent works — the person uploads a contract mid-conversation —
|
|
9
|
+
* and an attached document is frozen into the agent's cached prefix when it is
|
|
10
|
+
* attached, so a listing would be wrong exactly when it mattered. What does not
|
|
11
|
+
* change is how the tools are best used, and that is what this carries.
|
|
12
|
+
* `list_documents` is the live answer to what is there.
|
|
13
|
+
*/
|
|
14
|
+
const document_registry_1 = require("./document-registry");
|
|
15
|
+
/** @returns The guide, or an empty string when no source is registered */
|
|
16
|
+
function buildDocumentGuideMarkdown() {
|
|
17
|
+
const sources = (0, document_registry_1.listDocumentSources)();
|
|
18
|
+
if (sources.length === 0) {
|
|
19
|
+
return '';
|
|
20
|
+
}
|
|
21
|
+
const lines = [
|
|
22
|
+
'# Working With Documents',
|
|
23
|
+
'',
|
|
24
|
+
...sources.map((source) => `- **${source.name}**: ${source.description}`),
|
|
25
|
+
'',
|
|
26
|
+
'## Look things up; hold only what you must',
|
|
27
|
+
'',
|
|
28
|
+
'There are two ways to use a document, and they cost very different amounts.',
|
|
29
|
+
'',
|
|
30
|
+
'1. **Look it up.** `find_in_documents` finds passages about something; `read_document`',
|
|
31
|
+
' reads the pages around them. Only what you read goes into your history. Use this',
|
|
32
|
+
' for any question about *part* of a document: what the contract says about',
|
|
33
|
+
' termination, the limit on a policy, which claims were over $100,000.',
|
|
34
|
+
'2. **Hold it.** `load_document` puts the entire document into your context, where',
|
|
35
|
+
' it is sent with every request you make until you `unload_document` it. Use this',
|
|
36
|
+
' only when the work needs all of it at once: reviewing a whole contract,',
|
|
37
|
+
' summarising everything in it, or comparing two documents side by side.',
|
|
38
|
+
'',
|
|
39
|
+
'When you do hold a document, tell the person you are reading the whole thing. When',
|
|
40
|
+
'the work that needed it is done, unload it.',
|
|
41
|
+
'',
|
|
42
|
+
'## Every time',
|
|
43
|
+
'',
|
|
44
|
+
'- **Start with `list_documents`** unless you listed them in this same piece of work.',
|
|
45
|
+
' Documents are added while you work.',
|
|
46
|
+
'- **Search in the document\'s own words.** A contract says "hold harmless" and',
|
|
47
|
+
' "indemnify"; a loss run says "incurred" and "reserve". Try a second phrasing before',
|
|
48
|
+
' concluding something is not there.',
|
|
49
|
+
'- **Cite the document and page** for every fact you take from one: *(Acme Master',
|
|
50
|
+
' Services Agreement, p. 12)*. A person acting on a clause needs to find it.',
|
|
51
|
+
'- **Quote exact wording when it matters** — a limit, an exclusion, a deadline — rather',
|
|
52
|
+
' than paraphrasing it. A paraphrase of a legal clause can change what it means.',
|
|
53
|
+
'- **Say so when a document does not answer the question.** Never fill a gap with what',
|
|
54
|
+
' a document of that kind usually says.',
|
|
55
|
+
'',
|
|
56
|
+
];
|
|
57
|
+
return lines.join('\n');
|
|
58
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The process-global registry of host document sources.
|
|
3
|
+
*
|
|
4
|
+
* Module state, for the reason the data registry is: a source is registered once
|
|
5
|
+
* at boot and is the same for every room, and a tool handler runs with no Nest
|
|
6
|
+
* scope to inject into. Scope — whose documents a call may see — rides the tool
|
|
7
|
+
* context and never lives here.
|
|
8
|
+
*/
|
|
9
|
+
import { DocumentSource } from './document.types';
|
|
10
|
+
/**
|
|
11
|
+
* Registers (or replaces) a document source.
|
|
12
|
+
* @param source The host's document source
|
|
13
|
+
*/
|
|
14
|
+
export declare function registerDocumentSource(source: DocumentSource): void;
|
|
15
|
+
/** Removes a document source. @returns True if one was removed */
|
|
16
|
+
export declare function unregisterDocumentSource(name: string): boolean;
|
|
17
|
+
/** @returns Every registered source, in registration order */
|
|
18
|
+
export declare function listDocumentSources(): DocumentSource[];
|
|
19
|
+
/** @returns Whether any source is registered — the tools say so rather than failing oddly */
|
|
20
|
+
export declare function hasDocumentSources(): boolean;
|
|
21
|
+
/** Test seam. */
|
|
22
|
+
export declare function resetDocumentSources(): void;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.registerDocumentSource = registerDocumentSource;
|
|
4
|
+
exports.unregisterDocumentSource = unregisterDocumentSource;
|
|
5
|
+
exports.listDocumentSources = listDocumentSources;
|
|
6
|
+
exports.hasDocumentSources = hasDocumentSources;
|
|
7
|
+
exports.resetDocumentSources = resetDocumentSources;
|
|
8
|
+
const logger_1 = require("../../common/logger");
|
|
9
|
+
const sources = new Map();
|
|
10
|
+
const REQUIRED = ['list', 'search', 'read', 'fullText'];
|
|
11
|
+
/**
|
|
12
|
+
* Registers (or replaces) a document source.
|
|
13
|
+
* @param source The host's document source
|
|
14
|
+
*/
|
|
15
|
+
function registerDocumentSource(source) {
|
|
16
|
+
if (!source?.name) {
|
|
17
|
+
throw new Error('A document source needs a name');
|
|
18
|
+
}
|
|
19
|
+
for (const method of REQUIRED) {
|
|
20
|
+
if (typeof source[method] !== 'function') {
|
|
21
|
+
throw new Error(`Document source "${source.name}" must have a ${String(method)} function`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
if (sources.has(source.name)) {
|
|
25
|
+
logger_1.logger.warn(`Document source "${source.name}" is already registered; overwriting`);
|
|
26
|
+
}
|
|
27
|
+
sources.set(source.name, source);
|
|
28
|
+
}
|
|
29
|
+
/** Removes a document source. @returns True if one was removed */
|
|
30
|
+
function unregisterDocumentSource(name) {
|
|
31
|
+
return sources.delete(name);
|
|
32
|
+
}
|
|
33
|
+
/** @returns Every registered source, in registration order */
|
|
34
|
+
function listDocumentSources() {
|
|
35
|
+
return [...sources.values()];
|
|
36
|
+
}
|
|
37
|
+
/** @returns Whether any source is registered — the tools say so rather than failing oddly */
|
|
38
|
+
function hasDocumentSources() {
|
|
39
|
+
return sources.size > 0;
|
|
40
|
+
}
|
|
41
|
+
/** Test seam. */
|
|
42
|
+
function resetDocumentSources() {
|
|
43
|
+
sources.clear();
|
|
44
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A host's library of documents, made searchable and readable by an agent.
|
|
3
|
+
*
|
|
4
|
+
* The host keeps the documents — its database, its tenancy, its idea of who may
|
|
5
|
+
* see what — and answers four questions about them. Briyah supplies everything
|
|
6
|
+
* between those answers and a model: the tools, argument checking, refusals that
|
|
7
|
+
* name the valid choices, result budgets, pagination, and holding a document in
|
|
8
|
+
* an agent's context when the work needs all of it at once.
|
|
9
|
+
*
|
|
10
|
+
* Every method receives the opaque tool context the host passed when it started
|
|
11
|
+
* the interaction. That is the only place scope comes from. A document id an
|
|
12
|
+
* agent supplies is checked against what `list` returns for that scope before
|
|
13
|
+
* any other method sees it, so a host never has to trust one.
|
|
14
|
+
*
|
|
15
|
+
* `chunkPages` and `embedTexts` are exported alongside for a host building the
|
|
16
|
+
* index this searches, but nothing here requires them: `search` is the host's,
|
|
17
|
+
* and full-text, vector or both are all fine behind it.
|
|
18
|
+
*/
|
|
19
|
+
/** One document as an agent sees it listed. */
|
|
20
|
+
export interface DocumentSummary {
|
|
21
|
+
/** Unique within the source. What every tool takes. */
|
|
22
|
+
documentId: string;
|
|
23
|
+
/** What a person calls it — a title, or the file name. */
|
|
24
|
+
name: string;
|
|
25
|
+
/** The host's word for what it is, e.g. `contract` or `loss run`. */
|
|
26
|
+
kind?: string;
|
|
27
|
+
/** Pages as a reader counts them. A Word document is one. */
|
|
28
|
+
pages: number;
|
|
29
|
+
/** Size of its text, so an agent can judge what holding it would cost. */
|
|
30
|
+
chars: number;
|
|
31
|
+
/** ISO date it was added. */
|
|
32
|
+
addedAt?: string;
|
|
33
|
+
/** A paragraph describing it, when the host has one. */
|
|
34
|
+
summary?: string;
|
|
35
|
+
/**
|
|
36
|
+
* Whether it can be searched yet. A document still being indexed can be read
|
|
37
|
+
* but not found; one that failed can be read if its text exists at all.
|
|
38
|
+
* Defaults to `ready`.
|
|
39
|
+
*/
|
|
40
|
+
state?: 'ready' | 'indexing' | 'failed';
|
|
41
|
+
}
|
|
42
|
+
export interface DocumentSearchRequest {
|
|
43
|
+
/** What to look for, in the agent's words. Never empty. */
|
|
44
|
+
query: string;
|
|
45
|
+
/** Restricts the search to these documents. Absent means every document in scope. */
|
|
46
|
+
documentIds?: string[];
|
|
47
|
+
/** How many passages to return. Briyah clamps it; hosts need not. */
|
|
48
|
+
limit: number;
|
|
49
|
+
}
|
|
50
|
+
/** One passage a search found. */
|
|
51
|
+
export interface DocumentHit {
|
|
52
|
+
documentId: string;
|
|
53
|
+
/** The document's name, so a hit can be cited without another call. */
|
|
54
|
+
name: string;
|
|
55
|
+
pageNum: number;
|
|
56
|
+
/** The headings above the passage, when the host knows them. */
|
|
57
|
+
heading?: string;
|
|
58
|
+
/** The passage. Briyah trims it to fit the result; send it whole. */
|
|
59
|
+
excerpt: string;
|
|
60
|
+
/**
|
|
61
|
+
* Higher is better. Hits from different sources are merged by it, so a host
|
|
62
|
+
* with more than one source should keep scores on a common scale.
|
|
63
|
+
*/
|
|
64
|
+
score: number;
|
|
65
|
+
}
|
|
66
|
+
/** A span of pages, inclusive, 1-based. */
|
|
67
|
+
export interface PageRange {
|
|
68
|
+
from: number;
|
|
69
|
+
to: number;
|
|
70
|
+
}
|
|
71
|
+
export interface DocumentPage {
|
|
72
|
+
pageNum: number;
|
|
73
|
+
markdown: string;
|
|
74
|
+
/** A name for the page, when it has one — a workbook's sheet. */
|
|
75
|
+
label?: string;
|
|
76
|
+
}
|
|
77
|
+
export interface DocumentPages {
|
|
78
|
+
documentId: string;
|
|
79
|
+
name: string;
|
|
80
|
+
/** The document's page count, whatever range was asked for. */
|
|
81
|
+
pageCount: number;
|
|
82
|
+
pages: DocumentPage[];
|
|
83
|
+
}
|
|
84
|
+
export interface DocumentText {
|
|
85
|
+
documentId: string;
|
|
86
|
+
name: string;
|
|
87
|
+
markdown: string;
|
|
88
|
+
}
|
|
89
|
+
/** A host's documents. */
|
|
90
|
+
export interface DocumentSource {
|
|
91
|
+
name: string;
|
|
92
|
+
/** One sentence for the agent: what these documents are. */
|
|
93
|
+
description: string;
|
|
94
|
+
/** Every document the context may see. Called often; keep it cheap. */
|
|
95
|
+
list(context: unknown): Promise<DocumentSummary[]>;
|
|
96
|
+
/**
|
|
97
|
+
* Passages matching a query, best first. Only ever called with document ids
|
|
98
|
+
* that `list` returned for the same context.
|
|
99
|
+
*/
|
|
100
|
+
search(context: unknown, request: DocumentSearchRequest): Promise<DocumentHit[]>;
|
|
101
|
+
/**
|
|
102
|
+
* The pages in a range. Briyah clamps the range to the document. Returning
|
|
103
|
+
* null means the document is not there after all.
|
|
104
|
+
*/
|
|
105
|
+
read(context: unknown, documentId: string, range: PageRange): Promise<DocumentPages | null>;
|
|
106
|
+
/** The whole document, for holding in an agent's context. Null as for `read`. */
|
|
107
|
+
fullText(context: unknown, documentId: string): Promise<DocumentText | null>;
|
|
108
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* A host's library of documents, made searchable and readable by an agent.
|
|
4
|
+
*
|
|
5
|
+
* The host keeps the documents — its database, its tenancy, its idea of who may
|
|
6
|
+
* see what — and answers four questions about them. Briyah supplies everything
|
|
7
|
+
* between those answers and a model: the tools, argument checking, refusals that
|
|
8
|
+
* name the valid choices, result budgets, pagination, and holding a document in
|
|
9
|
+
* an agent's context when the work needs all of it at once.
|
|
10
|
+
*
|
|
11
|
+
* Every method receives the opaque tool context the host passed when it started
|
|
12
|
+
* the interaction. That is the only place scope comes from. A document id an
|
|
13
|
+
* agent supplies is checked against what `list` returns for that scope before
|
|
14
|
+
* any other method sees it, so a host never has to trust one.
|
|
15
|
+
*
|
|
16
|
+
* `chunkPages` and `embedTexts` are exported alongside for a host building the
|
|
17
|
+
* index this searches, but nothing here requires them: `search` is the host's,
|
|
18
|
+
* and full-text, vector or both are all fine behind it.
|
|
19
|
+
*/
|
|
20
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turning text into vectors for semantic search.
|
|
3
|
+
*
|
|
4
|
+
* Anthropic publishes no embeddings endpoint, so this defaults to OpenAI's
|
|
5
|
+
* `text-embedding-3-small`. The provider sits behind {@link EmbeddingProvider} so
|
|
6
|
+
* a host can supply another, and so tests never reach a network.
|
|
7
|
+
*
|
|
8
|
+
* The dimension is the one number a host has to agree with: it is baked into the
|
|
9
|
+
* vector column of whatever database stores the result, and a model that returns
|
|
10
|
+
* a different length would fail every insert — or worse, succeed against a column
|
|
11
|
+
* declared without one. So {@link EMBEDDING_DIMENSIONS} is exported for the host's
|
|
12
|
+
* migration to use, and every response is checked against what was asked for.
|
|
13
|
+
*/
|
|
14
|
+
/** The default model. Override with `EMBEDDING_MODEL` or per call. */
|
|
15
|
+
export declare const DEFAULT_EMBEDDING_MODEL = "text-embedding-3-small";
|
|
16
|
+
/**
|
|
17
|
+
* The vector length a host's schema should declare. `text-embedding-3-small`
|
|
18
|
+
* produces 1536 natively. Override with `EMBEDDING_DIMENSIONS` only together with
|
|
19
|
+
* a migration — the column and the model have to change as one.
|
|
20
|
+
*/
|
|
21
|
+
export declare const EMBEDDING_DIMENSIONS = 1536;
|
|
22
|
+
/** A source of embeddings. */
|
|
23
|
+
export interface EmbeddingProvider {
|
|
24
|
+
/**
|
|
25
|
+
* Embeds a batch. Returns one vector per input, in input order, and the tokens
|
|
26
|
+
* the provider billed for the batch.
|
|
27
|
+
*/
|
|
28
|
+
embed(texts: string[], model: string, dimensions: number): Promise<{
|
|
29
|
+
vectors: number[][];
|
|
30
|
+
tokens: number;
|
|
31
|
+
}>;
|
|
32
|
+
}
|
|
33
|
+
export interface EmbeddingOptions {
|
|
34
|
+
/** Defaults to `EMBEDDING_MODEL`, then {@link DEFAULT_EMBEDDING_MODEL}. */
|
|
35
|
+
model?: string;
|
|
36
|
+
/** Defaults to `EMBEDDING_DIMENSIONS`, then {@link EMBEDDING_DIMENSIONS}. */
|
|
37
|
+
dimensions?: number;
|
|
38
|
+
/** Defaults to OpenAI with `OPENAI_API_KEY`. */
|
|
39
|
+
provider?: EmbeddingProvider;
|
|
40
|
+
/** Called as batches complete, for a caller with somewhere to show it. */
|
|
41
|
+
onProgress?: (message: string) => void;
|
|
42
|
+
}
|
|
43
|
+
export interface EmbeddingResult {
|
|
44
|
+
/** One per input, in input order. */
|
|
45
|
+
vectors: number[][];
|
|
46
|
+
model: string;
|
|
47
|
+
dimensions: number;
|
|
48
|
+
tokens: number;
|
|
49
|
+
/** In dollars, priced from `model_prices.json`. Zero for a model with no price entry. */
|
|
50
|
+
cost: number;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Embeds texts in as few requests as the provider's limits allow.
|
|
54
|
+
*
|
|
55
|
+
* @throws If the provider is unavailable, or returns vectors of the wrong length
|
|
56
|
+
*/
|
|
57
|
+
export declare function embedTexts(texts: readonly string[], options?: EmbeddingOptions): Promise<EmbeddingResult>;
|