briyah 2.0.6 → 2.0.8

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 +394 -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,394 @@
1
+ "use strict";
2
+ /**
3
+ * Turning an uploaded file into Markdown pages, whatever kind of file it was.
4
+ *
5
+ * PDFs go through the per-page AI conversion in `pdf-conversion.ts`, because a
6
+ * PDF is a picture of a page and needs reading. Word and Excel files do not: they
7
+ * already carry their text and structure, so they convert locally, instantly and
8
+ * for nothing. This module owns that local half, plus the one decision both
9
+ * halves depend on — what kind of file this actually is.
10
+ *
11
+ * That decision is the part worth getting right. A host that assumed "not a PDF,
12
+ * so text" would decode a .docx as UTF-8 and hand an agent a page of mojibake,
13
+ * which the agent then summarises with complete confidence. So an unrecognised
14
+ * file is refused with a reason a person can act on, never guessed at.
15
+ *
16
+ * Page numbers mean what a reader would expect. A PDF has real pages. A Word
17
+ * document does not — its pagination is decided by whatever renders it — so it
18
+ * comes back as one page, and an agent locates a passage by its heading instead
19
+ * of by a page number that would not match the user's screen. A workbook comes
20
+ * back as one page per visible sheet, labelled with the sheet's name.
21
+ */
22
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
23
+ if (k2 === undefined) k2 = k;
24
+ var desc = Object.getOwnPropertyDescriptor(m, k);
25
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
26
+ desc = { enumerable: true, get: function() { return m[k]; } };
27
+ }
28
+ Object.defineProperty(o, k2, desc);
29
+ }) : (function(o, m, k, k2) {
30
+ if (k2 === undefined) k2 = k;
31
+ o[k2] = m[k];
32
+ }));
33
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
34
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
35
+ }) : function(o, v) {
36
+ o["default"] = v;
37
+ });
38
+ var __importStar = (this && this.__importStar) || (function () {
39
+ var ownKeys = function(o) {
40
+ ownKeys = Object.getOwnPropertyNames || function (o) {
41
+ var ar = [];
42
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
43
+ return ar;
44
+ };
45
+ return ownKeys(o);
46
+ };
47
+ return function (mod) {
48
+ if (mod && mod.__esModule) return mod;
49
+ var result = {};
50
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
51
+ __setModuleDefault(result, mod);
52
+ return result;
53
+ };
54
+ })();
55
+ var __importDefault = (this && this.__importDefault) || function (mod) {
56
+ return (mod && mod.__esModule) ? mod : { "default": mod };
57
+ };
58
+ Object.defineProperty(exports, "__esModule", { value: true });
59
+ exports.UnsupportedDocumentError = void 0;
60
+ exports.detectDocumentType = detectDocumentType;
61
+ exports.convertLocalDocument = convertLocalDocument;
62
+ const mammoth = __importStar(require("mammoth"));
63
+ const turndown_1 = __importDefault(require("turndown"));
64
+ const exceljs_1 = __importDefault(require("exceljs"));
65
+ const jszip_1 = __importDefault(require("jszip"));
66
+ const pdf_conversion_1 = require("./pdf-conversion");
67
+ /** Thrown for a file that cannot be read. `message` is written for the person who uploaded it. */
68
+ class UnsupportedDocumentError extends Error {
69
+ constructor(message) {
70
+ super(message);
71
+ this.name = 'UnsupportedDocumentError';
72
+ }
73
+ }
74
+ exports.UnsupportedDocumentError = UnsupportedDocumentError;
75
+ const DEFAULT_MAX_ROWS_PER_SHEET = 5_000;
76
+ const ZIP_MAGIC = [0x50, 0x4b, 0x03, 0x04];
77
+ const PDF_MAGIC = [0x25, 0x50, 0x44, 0x46];
78
+ /** Word 97–2003 and Excel 97–2003 share this OLE compound-file signature. */
79
+ const OLE_MAGIC = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1];
80
+ const TEXT_EXTENSIONS = new Set(['md', 'markdown', 'txt', 'csv', 'tsv', 'text']);
81
+ function startsWith(bytes, magic) {
82
+ return magic.every((byte, index) => bytes[index] === byte);
83
+ }
84
+ /**
85
+ * Whether a ZIP archive contains an entry. Entry names are stored uncompressed
86
+ * in the local and central directory headers, so a byte search finds them
87
+ * without unpacking anything.
88
+ */
89
+ function zipContains(bytes, entryName) {
90
+ return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).indexOf(entryName, 0, 'latin1') !== -1;
91
+ }
92
+ /** Text files essentially never contain a NUL byte; binary files essentially always do. */
93
+ function looksLikeText(bytes) {
94
+ const sample = bytes.subarray(0, Math.min(bytes.length, 8192));
95
+ return !sample.includes(0);
96
+ }
97
+ /**
98
+ * Decides what a file is from its contents, using the name only to break ties.
99
+ *
100
+ * .docx and .xlsx are both ZIP archives, so their magic bytes are identical; the
101
+ * archive's entries are what tell them apart. The extension alone is never
102
+ * trusted over the contents — a renamed file is refused rather than misread.
103
+ */
104
+ function detectDocumentType(bytes, fileName) {
105
+ const extension = (fileName || '').toLowerCase().split('.').pop() || '';
106
+ if (!bytes || bytes.length === 0) {
107
+ return { type: 'unsupported', reason: 'The file is empty.' };
108
+ }
109
+ if (startsWith(bytes, PDF_MAGIC)) {
110
+ return { type: 'pdf' };
111
+ }
112
+ if (startsWith(bytes, ZIP_MAGIC)) {
113
+ if (zipContains(bytes, 'word/document.xml'))
114
+ return { type: 'docx' };
115
+ if (zipContains(bytes, 'xl/workbook.xml'))
116
+ return { type: 'xlsx' };
117
+ if (zipContains(bytes, 'ppt/presentation.xml')) {
118
+ return { type: 'unsupported', reason: 'PowerPoint files cannot be read yet. Save it as a PDF and upload that instead.' };
119
+ }
120
+ return { type: 'unsupported', reason: `"${fileName}" is a compressed archive, not a document that can be read.` };
121
+ }
122
+ if (startsWith(bytes, OLE_MAGIC)) {
123
+ const kind = extension === 'xls' ? 'Excel 97–2003 (.xls)' : extension === 'doc' ? 'Word 97–2003 (.doc)' : 'older Office';
124
+ const modern = extension === 'xls' ? '.xlsx' : '.docx';
125
+ return {
126
+ type: 'unsupported',
127
+ reason: `${kind} files cannot be read. Open it and save it as ${modern} or PDF, then upload that.`,
128
+ };
129
+ }
130
+ if (looksLikeText(bytes)) {
131
+ // Text is recognised by its content, so a file with no extension or an
132
+ // unusual one still reads. The extension list only decides what a binary
133
+ // file with a text extension is: nothing readable.
134
+ return { type: 'text' };
135
+ }
136
+ if (TEXT_EXTENSIONS.has(extension)) {
137
+ return { type: 'unsupported', reason: `"${fileName}" is named as a text file but contains binary data.` };
138
+ }
139
+ return {
140
+ type: 'unsupported',
141
+ reason: `"${fileName}" is not a file type that can be read. PDF, Word (.docx), Excel (.xlsx) and plain text are supported.`,
142
+ };
143
+ }
144
+ /**
145
+ * Converts a Word, Excel or plain-text file to Markdown pages, locally.
146
+ *
147
+ * @throws {UnsupportedDocumentError} For a PDF (which needs the AI path) or anything unreadable
148
+ */
149
+ async function convertLocalDocument(bytes, fileName, options = {}) {
150
+ const detection = detectDocumentType(bytes, fileName);
151
+ if (detection.type === 'unsupported') {
152
+ throw new UnsupportedDocumentError(detection.reason);
153
+ }
154
+ if (detection.type === 'pdf') {
155
+ throw new UnsupportedDocumentError('A PDF is converted page by page with convertPdfToMarkdownPages, not locally.');
156
+ }
157
+ let pages;
158
+ let warnings;
159
+ if (detection.type === 'docx') {
160
+ ({ pages, warnings } = await convertDocx(bytes));
161
+ }
162
+ else if (detection.type === 'xlsx') {
163
+ ({ pages, warnings } = await convertXlsx(bytes, options.maxRowsPerSheet ?? DEFAULT_MAX_ROWS_PER_SHEET));
164
+ }
165
+ else {
166
+ const text = new TextDecoder('utf-8').decode(bytes).replace(/^/, '');
167
+ pages = [{ pageNum: 1, markdown: text }];
168
+ warnings = [];
169
+ }
170
+ if (pages.every((page) => !page.markdown.trim())) {
171
+ throw new UnsupportedDocumentError(`"${fileName}" contains no readable text.`);
172
+ }
173
+ return { type: detection.type, pages, markdown: assemble(pages), warnings };
174
+ }
175
+ function assemble(pages) {
176
+ return pages.map((page) => `${(0, pdf_conversion_1.pageMarker)(page.pageNum)}\n${page.markdown}\n`).join('\n');
177
+ }
178
+ // ---------------------------------------------------------------------------
179
+ // Word
180
+ // ---------------------------------------------------------------------------
181
+ async function convertDocx(bytes) {
182
+ const result = await mammoth.convertToHtml({ buffer: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength) }, {
183
+ // mammoth's default inlines every image as a base64 data URI, which
184
+ // would put megabytes of encoded pixels into the Markdown — and from
185
+ // there into every chunk, embedding and context that touches it. An
186
+ // empty src keeps the image's place and its alt text, and nothing else.
187
+ convertImage: mammoth.images.imgElement(async () => ({ src: '' })),
188
+ });
189
+ const images = (result.value.match(/<img\b/g) || []).length;
190
+ const warnings = result.messages
191
+ .filter((message) => message.type === 'warning')
192
+ .map((message) => message.message)
193
+ // Unrecognised paragraph styles are routine in real documents and say
194
+ // nothing a reader needs; they would bury the warnings that matter.
195
+ .filter((message) => !/^Unrecognised (paragraph|run) style/.test(message));
196
+ if (images) {
197
+ warnings.push(`${images} image(s) were left out; only their captions, where they had any, are kept.`);
198
+ }
199
+ return { pages: [{ pageNum: 1, markdown: htmlToMarkdown(result.value).trim() }], warnings };
200
+ }
201
+ function htmlToMarkdown(html) {
202
+ const turndown = new turndown_1.default({
203
+ headingStyle: 'atx',
204
+ codeBlockStyle: 'fenced',
205
+ bulletListMarker: '-',
206
+ emDelimiter: '*',
207
+ });
208
+ turndown.addRule('image', {
209
+ filter: 'img',
210
+ replacement: (_content, node) => {
211
+ const alt = (node.getAttribute('alt') || '').trim();
212
+ return alt ? `[Image: ${alt}]` : '[Image]';
213
+ },
214
+ });
215
+ // Turndown keeps tables as raw HTML by default. The GFM plugin converts them,
216
+ // but only when the first row is marked up as a header — and Word marks a
217
+ // header row only when the author ticked "Repeat as header row", which almost
218
+ // nobody does. So every table is converted, taking its first row as the header.
219
+ turndown.addRule('table', {
220
+ filter: 'table',
221
+ replacement: (_content, node) => {
222
+ const rows = Array.from(node.querySelectorAll('tr'));
223
+ const grid = rows
224
+ .map((row) => Array.from(row.querySelectorAll('th, td')).map((cell) => tableCell(turndown.turndown(cell.innerHTML))))
225
+ .filter((cells) => cells.length > 0);
226
+ return grid.length ? `\n\n${markdownTable(grid)}\n\n` : '';
227
+ },
228
+ });
229
+ return turndown.turndown(html);
230
+ }
231
+ // ---------------------------------------------------------------------------
232
+ // Excel
233
+ // ---------------------------------------------------------------------------
234
+ async function loadWorkbook(bytes) {
235
+ const workbook = new exceljs_1.default.Workbook();
236
+ await workbook.xlsx.load(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
237
+ return workbook;
238
+ }
239
+ /**
240
+ * Lower-cases a workbook's worksheet part names, and every reference to them.
241
+ *
242
+ * ExcelJS finds worksheets by the lower-case names Excel itself writes —
243
+ * `xl/worksheets/sheet1.xml` — and a workbook whose parts are named
244
+ * `Sheet1.xml` loads with no error and no sheets. Excel opens such files
245
+ * without complaint, and carrier systems produce them: the first one found was
246
+ * a National Interstate loss run. The part names are case-insensitive by the
247
+ * package spec, so renaming them changes nothing about what the file means.
248
+ *
249
+ * @returns The repaired archive, or null when there was nothing to rename
250
+ */
251
+ async function lowerCaseWorksheetParts(bytes) {
252
+ const zip = await jszip_1.default.loadAsync(bytes);
253
+ const renames = [];
254
+ zip.forEach((entry) => {
255
+ const lower = entry.replace(/^(xl\/worksheets\/(?:_rels\/)?)(sheet\d+\.xml(?:\.rels)?)$/i, (_match, dir, file) => dir + file.toLowerCase());
256
+ if (lower !== entry) {
257
+ renames.push([entry, lower]);
258
+ }
259
+ });
260
+ if (!renames.length) {
261
+ return null;
262
+ }
263
+ for (const [from, to] of renames) {
264
+ const content = await zip.file(from).async('uint8array');
265
+ zip.remove(from);
266
+ zip.file(to, content);
267
+ }
268
+ // The workbook's relationships and the content-type overrides both name the parts.
269
+ for (const part of ['xl/_rels/workbook.xml.rels', '[Content_Types].xml']) {
270
+ const file = zip.file(part);
271
+ if (file) {
272
+ const xml = await file.async('string');
273
+ zip.file(part, xml.replace(/(worksheets\/)(sheet\d+\.xml)/gi, (_match, dir, name) => dir + name.toLowerCase()));
274
+ }
275
+ }
276
+ return zip.generateAsync({ type: 'uint8array' });
277
+ }
278
+ async function convertXlsx(bytes, maxRows) {
279
+ let workbook = await loadWorkbook(bytes);
280
+ if (workbook.worksheets.length === 0) {
281
+ const repaired = await lowerCaseWorksheetParts(bytes);
282
+ if (repaired) {
283
+ workbook = await loadWorkbook(repaired);
284
+ }
285
+ }
286
+ if (workbook.worksheets.length === 0) {
287
+ throw new UnsupportedDocumentError('No worksheets could be found in this workbook. Open it in Excel, save it again as .xlsx, and upload that.');
288
+ }
289
+ const pages = [];
290
+ const warnings = [];
291
+ for (const sheet of workbook.worksheets) {
292
+ // A hidden sheet is one the author chose not to show — usually lookup
293
+ // tables. Reading it would put numbers in an answer that the user cannot
294
+ // find in the workbook, so it is left out, and said so.
295
+ if (sheet.state && sheet.state !== 'visible') {
296
+ warnings.push(`Hidden sheet "${sheet.name}" was left out.`);
297
+ continue;
298
+ }
299
+ const grid = [];
300
+ let truncated = 0;
301
+ sheet.eachRow({ includeEmpty: false }, (row) => {
302
+ if (grid.length >= maxRows) {
303
+ truncated++;
304
+ return;
305
+ }
306
+ const cells = [];
307
+ row.eachCell({ includeEmpty: true }, (cell, column) => {
308
+ cells[column - 1] = tableCell(cellText(cell));
309
+ });
310
+ grid.push(Array.from(cells, (value) => value ?? ''));
311
+ });
312
+ const trimmed = trimEmptyColumns(grid);
313
+ if (!trimmed.length) {
314
+ continue;
315
+ }
316
+ const lines = [`## Sheet: ${sheet.name}`, '', markdownTable(trimmed)];
317
+ if (truncated) {
318
+ const note = `Only the first ${maxRows.toLocaleString()} rows of "${sheet.name}" are included; ${truncated.toLocaleString()} more were left out.`;
319
+ lines.push('', `> ${note}`);
320
+ warnings.push(note);
321
+ }
322
+ pages.push({ pageNum: pages.length + 1, markdown: lines.join('\n'), label: sheet.name });
323
+ }
324
+ return { pages, warnings };
325
+ }
326
+ /** A cell as a person reading the workbook would see it. */
327
+ function cellText(cell) {
328
+ // A merged range shows its value once, in its top-left cell. Repeating it in
329
+ // every covered cell would turn one title into a row of six.
330
+ if (cell.isMerged && cell.master && cell.master.address !== cell.address) {
331
+ return '';
332
+ }
333
+ let value = cell.value;
334
+ if (value && typeof value === 'object' && !(value instanceof Date)) {
335
+ if ('result' in value)
336
+ value = value.result; // a formula: show what it evaluates to
337
+ else if ('richText' in value)
338
+ value = value.richText.map((part) => part.text).join('');
339
+ else if ('text' in value)
340
+ value = value.text; // a hyperlink: show its text
341
+ else if ('error' in value)
342
+ value = value.error;
343
+ }
344
+ if (value === null || value === undefined)
345
+ return '';
346
+ if (value instanceof Date)
347
+ return formatDate(value);
348
+ if (typeof value === 'number')
349
+ return formatNumber(value, cell.numFmt);
350
+ return String(value);
351
+ }
352
+ /**
353
+ * Excel stores dates as local wall-clock values with no zone, and ExcelJS reads
354
+ * them back as UTC. So a date is formatted from its UTC fields, which recovers
355
+ * the date the author typed rather than shifting it by the server's offset.
356
+ */
357
+ function formatDate(value) {
358
+ const iso = value.toISOString();
359
+ return iso.endsWith('T00:00:00.000Z') ? iso.slice(0, 10) : iso.slice(0, 16).replace('T', ' ');
360
+ }
361
+ /** A percentage stored as 0.15 is shown as 15% — a reader told "0.15" for a loss ratio is misled. */
362
+ function formatNumber(value, numFmt) {
363
+ if (numFmt && numFmt.includes('%')) {
364
+ return `${parseFloat((value * 100).toFixed(4))}%`;
365
+ }
366
+ return String(value);
367
+ }
368
+ function trimEmptyColumns(grid) {
369
+ const width = grid.reduce((max, row) => {
370
+ let last = row.length - 1;
371
+ while (last >= 0 && !row[last])
372
+ last--;
373
+ return Math.max(max, last + 1);
374
+ }, 0);
375
+ return grid.map((row) => Array.from({ length: width }, (_, index) => row[index] ?? '')).filter((row) => row.some(Boolean));
376
+ }
377
+ // ---------------------------------------------------------------------------
378
+ // Tables
379
+ // ---------------------------------------------------------------------------
380
+ /** One cell's text, made safe to sit inside a GFM table row. */
381
+ function tableCell(text) {
382
+ return text
383
+ .trim()
384
+ .replace(/\|/g, '\\|')
385
+ .replace(/\s*\n\s*/g, '<br>');
386
+ }
387
+ /** A GFM table, taking the first row as the header and padding ragged rows. */
388
+ function markdownTable(grid) {
389
+ const width = Math.max(...grid.map((row) => row.length));
390
+ const pad = (row) => Array.from({ length: width }, (_, index) => row[index] ?? '');
391
+ const line = (row) => `| ${pad(row).join(' | ')} |`;
392
+ const [header, ...body] = grid;
393
+ return [line(header), `| ${Array.from({ length: width }, () => '---').join(' | ')} |`, ...body.map(line)].join('\n');
394
+ }
@@ -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;