briyah 2.0.5 → 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/common/prompts/moderate.json +34 -0
- package/data/common/prompts/moderate.prompt +136 -0
- package/data/packs/dnd5e/pack.json +7 -1
- package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +16 -0
- package/dist-sdk/server/src/ai/LLM/base-ai.service.js +23 -0
- package/dist-sdk/server/src/ai/agent.d.ts +33 -0
- package/dist-sdk/server/src/ai/agent.js +64 -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/data/data-guide.builder.d.ts +2 -0
- package/dist-sdk/server/src/data/data-guide.builder.js +90 -0
- package/dist-sdk/server/src/data/data-registry.d.ts +32 -0
- package/dist-sdk/server/src/data/data-registry.js +61 -0
- package/dist-sdk/server/src/data/data.types.d.ts +158 -0
- package/dist-sdk/server/src/data/data.types.js +24 -0
- package/dist-sdk/server/src/data/query-validation.d.ts +45 -0
- package/dist-sdk/server/src/data/query-validation.js +245 -0
- 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.d.ts +7 -5
- package/dist-sdk/server/src/room/room.js +44 -7
- 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 +16 -2
- package/dist-sdk/server/src/sdk/index.js +37 -1
- package/dist-sdk/server/src/tools/core/data.tools.d.ts +17 -0
- package/dist-sdk/server/src/tools/core/data.tools.js +165 -0
- 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 +3 -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,341 @@
|
|
|
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 pdf_conversion_1 = require("./pdf-conversion");
|
|
66
|
+
/** Thrown for a file that cannot be read. `message` is written for the person who uploaded it. */
|
|
67
|
+
class UnsupportedDocumentError extends Error {
|
|
68
|
+
constructor(message) {
|
|
69
|
+
super(message);
|
|
70
|
+
this.name = 'UnsupportedDocumentError';
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
exports.UnsupportedDocumentError = UnsupportedDocumentError;
|
|
74
|
+
const DEFAULT_MAX_ROWS_PER_SHEET = 5_000;
|
|
75
|
+
const ZIP_MAGIC = [0x50, 0x4b, 0x03, 0x04];
|
|
76
|
+
const PDF_MAGIC = [0x25, 0x50, 0x44, 0x46];
|
|
77
|
+
/** Word 97–2003 and Excel 97–2003 share this OLE compound-file signature. */
|
|
78
|
+
const OLE_MAGIC = [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1];
|
|
79
|
+
const TEXT_EXTENSIONS = new Set(['md', 'markdown', 'txt', 'csv', 'tsv', 'text']);
|
|
80
|
+
function startsWith(bytes, magic) {
|
|
81
|
+
return magic.every((byte, index) => bytes[index] === byte);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Whether a ZIP archive contains an entry. Entry names are stored uncompressed
|
|
85
|
+
* in the local and central directory headers, so a byte search finds them
|
|
86
|
+
* without unpacking anything.
|
|
87
|
+
*/
|
|
88
|
+
function zipContains(bytes, entryName) {
|
|
89
|
+
return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).indexOf(entryName, 0, 'latin1') !== -1;
|
|
90
|
+
}
|
|
91
|
+
/** Text files essentially never contain a NUL byte; binary files essentially always do. */
|
|
92
|
+
function looksLikeText(bytes) {
|
|
93
|
+
const sample = bytes.subarray(0, Math.min(bytes.length, 8192));
|
|
94
|
+
return !sample.includes(0);
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Decides what a file is from its contents, using the name only to break ties.
|
|
98
|
+
*
|
|
99
|
+
* .docx and .xlsx are both ZIP archives, so their magic bytes are identical; the
|
|
100
|
+
* archive's entries are what tell them apart. The extension alone is never
|
|
101
|
+
* trusted over the contents — a renamed file is refused rather than misread.
|
|
102
|
+
*/
|
|
103
|
+
function detectDocumentType(bytes, fileName) {
|
|
104
|
+
const extension = (fileName || '').toLowerCase().split('.').pop() || '';
|
|
105
|
+
if (!bytes || bytes.length === 0) {
|
|
106
|
+
return { type: 'unsupported', reason: 'The file is empty.' };
|
|
107
|
+
}
|
|
108
|
+
if (startsWith(bytes, PDF_MAGIC)) {
|
|
109
|
+
return { type: 'pdf' };
|
|
110
|
+
}
|
|
111
|
+
if (startsWith(bytes, ZIP_MAGIC)) {
|
|
112
|
+
if (zipContains(bytes, 'word/document.xml'))
|
|
113
|
+
return { type: 'docx' };
|
|
114
|
+
if (zipContains(bytes, 'xl/workbook.xml'))
|
|
115
|
+
return { type: 'xlsx' };
|
|
116
|
+
if (zipContains(bytes, 'ppt/presentation.xml')) {
|
|
117
|
+
return { type: 'unsupported', reason: 'PowerPoint files cannot be read yet. Save it as a PDF and upload that instead.' };
|
|
118
|
+
}
|
|
119
|
+
return { type: 'unsupported', reason: `"${fileName}" is a compressed archive, not a document that can be read.` };
|
|
120
|
+
}
|
|
121
|
+
if (startsWith(bytes, OLE_MAGIC)) {
|
|
122
|
+
const kind = extension === 'xls' ? 'Excel 97–2003 (.xls)' : extension === 'doc' ? 'Word 97–2003 (.doc)' : 'older Office';
|
|
123
|
+
const modern = extension === 'xls' ? '.xlsx' : '.docx';
|
|
124
|
+
return {
|
|
125
|
+
type: 'unsupported',
|
|
126
|
+
reason: `${kind} files cannot be read. Open it and save it as ${modern} or PDF, then upload that.`,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
if (looksLikeText(bytes)) {
|
|
130
|
+
// Text is recognised by its content, so a file with no extension or an
|
|
131
|
+
// unusual one still reads. The extension list only decides what a binary
|
|
132
|
+
// file with a text extension is: nothing readable.
|
|
133
|
+
return { type: 'text' };
|
|
134
|
+
}
|
|
135
|
+
if (TEXT_EXTENSIONS.has(extension)) {
|
|
136
|
+
return { type: 'unsupported', reason: `"${fileName}" is named as a text file but contains binary data.` };
|
|
137
|
+
}
|
|
138
|
+
return {
|
|
139
|
+
type: 'unsupported',
|
|
140
|
+
reason: `"${fileName}" is not a file type that can be read. PDF, Word (.docx), Excel (.xlsx) and plain text are supported.`,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Converts a Word, Excel or plain-text file to Markdown pages, locally.
|
|
145
|
+
*
|
|
146
|
+
* @throws {UnsupportedDocumentError} For a PDF (which needs the AI path) or anything unreadable
|
|
147
|
+
*/
|
|
148
|
+
async function convertLocalDocument(bytes, fileName, options = {}) {
|
|
149
|
+
const detection = detectDocumentType(bytes, fileName);
|
|
150
|
+
if (detection.type === 'unsupported') {
|
|
151
|
+
throw new UnsupportedDocumentError(detection.reason);
|
|
152
|
+
}
|
|
153
|
+
if (detection.type === 'pdf') {
|
|
154
|
+
throw new UnsupportedDocumentError('A PDF is converted page by page with convertPdfToMarkdownPages, not locally.');
|
|
155
|
+
}
|
|
156
|
+
let pages;
|
|
157
|
+
let warnings;
|
|
158
|
+
if (detection.type === 'docx') {
|
|
159
|
+
({ pages, warnings } = await convertDocx(bytes));
|
|
160
|
+
}
|
|
161
|
+
else if (detection.type === 'xlsx') {
|
|
162
|
+
({ pages, warnings } = await convertXlsx(bytes, options.maxRowsPerSheet ?? DEFAULT_MAX_ROWS_PER_SHEET));
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
const text = new TextDecoder('utf-8').decode(bytes).replace(/^/, '');
|
|
166
|
+
pages = [{ pageNum: 1, markdown: text }];
|
|
167
|
+
warnings = [];
|
|
168
|
+
}
|
|
169
|
+
if (pages.every((page) => !page.markdown.trim())) {
|
|
170
|
+
throw new UnsupportedDocumentError(`"${fileName}" contains no readable text.`);
|
|
171
|
+
}
|
|
172
|
+
return { type: detection.type, pages, markdown: assemble(pages), warnings };
|
|
173
|
+
}
|
|
174
|
+
function assemble(pages) {
|
|
175
|
+
return pages.map((page) => `${(0, pdf_conversion_1.pageMarker)(page.pageNum)}\n${page.markdown}\n`).join('\n');
|
|
176
|
+
}
|
|
177
|
+
// ---------------------------------------------------------------------------
|
|
178
|
+
// Word
|
|
179
|
+
// ---------------------------------------------------------------------------
|
|
180
|
+
async function convertDocx(bytes) {
|
|
181
|
+
const result = await mammoth.convertToHtml({ buffer: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength) }, {
|
|
182
|
+
// mammoth's default inlines every image as a base64 data URI, which
|
|
183
|
+
// would put megabytes of encoded pixels into the Markdown — and from
|
|
184
|
+
// there into every chunk, embedding and context that touches it. An
|
|
185
|
+
// empty src keeps the image's place and its alt text, and nothing else.
|
|
186
|
+
convertImage: mammoth.images.imgElement(async () => ({ src: '' })),
|
|
187
|
+
});
|
|
188
|
+
const images = (result.value.match(/<img\b/g) || []).length;
|
|
189
|
+
const warnings = result.messages
|
|
190
|
+
.filter((message) => message.type === 'warning')
|
|
191
|
+
.map((message) => message.message)
|
|
192
|
+
// Unrecognised paragraph styles are routine in real documents and say
|
|
193
|
+
// nothing a reader needs; they would bury the warnings that matter.
|
|
194
|
+
.filter((message) => !/^Unrecognised (paragraph|run) style/.test(message));
|
|
195
|
+
if (images) {
|
|
196
|
+
warnings.push(`${images} image(s) were left out; only their captions, where they had any, are kept.`);
|
|
197
|
+
}
|
|
198
|
+
return { pages: [{ pageNum: 1, markdown: htmlToMarkdown(result.value).trim() }], warnings };
|
|
199
|
+
}
|
|
200
|
+
function htmlToMarkdown(html) {
|
|
201
|
+
const turndown = new turndown_1.default({
|
|
202
|
+
headingStyle: 'atx',
|
|
203
|
+
codeBlockStyle: 'fenced',
|
|
204
|
+
bulletListMarker: '-',
|
|
205
|
+
emDelimiter: '*',
|
|
206
|
+
});
|
|
207
|
+
turndown.addRule('image', {
|
|
208
|
+
filter: 'img',
|
|
209
|
+
replacement: (_content, node) => {
|
|
210
|
+
const alt = (node.getAttribute('alt') || '').trim();
|
|
211
|
+
return alt ? `[Image: ${alt}]` : '[Image]';
|
|
212
|
+
},
|
|
213
|
+
});
|
|
214
|
+
// Turndown keeps tables as raw HTML by default. The GFM plugin converts them,
|
|
215
|
+
// but only when the first row is marked up as a header — and Word marks a
|
|
216
|
+
// header row only when the author ticked "Repeat as header row", which almost
|
|
217
|
+
// nobody does. So every table is converted, taking its first row as the header.
|
|
218
|
+
turndown.addRule('table', {
|
|
219
|
+
filter: 'table',
|
|
220
|
+
replacement: (_content, node) => {
|
|
221
|
+
const rows = Array.from(node.querySelectorAll('tr'));
|
|
222
|
+
const grid = rows
|
|
223
|
+
.map((row) => Array.from(row.querySelectorAll('th, td')).map((cell) => tableCell(turndown.turndown(cell.innerHTML))))
|
|
224
|
+
.filter((cells) => cells.length > 0);
|
|
225
|
+
return grid.length ? `\n\n${markdownTable(grid)}\n\n` : '';
|
|
226
|
+
},
|
|
227
|
+
});
|
|
228
|
+
return turndown.turndown(html);
|
|
229
|
+
}
|
|
230
|
+
// ---------------------------------------------------------------------------
|
|
231
|
+
// Excel
|
|
232
|
+
// ---------------------------------------------------------------------------
|
|
233
|
+
async function convertXlsx(bytes, maxRows) {
|
|
234
|
+
const workbook = new exceljs_1.default.Workbook();
|
|
235
|
+
await workbook.xlsx.load(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength));
|
|
236
|
+
const pages = [];
|
|
237
|
+
const warnings = [];
|
|
238
|
+
for (const sheet of workbook.worksheets) {
|
|
239
|
+
// A hidden sheet is one the author chose not to show — usually lookup
|
|
240
|
+
// tables. Reading it would put numbers in an answer that the user cannot
|
|
241
|
+
// find in the workbook, so it is left out, and said so.
|
|
242
|
+
if (sheet.state && sheet.state !== 'visible') {
|
|
243
|
+
warnings.push(`Hidden sheet "${sheet.name}" was left out.`);
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
const grid = [];
|
|
247
|
+
let truncated = 0;
|
|
248
|
+
sheet.eachRow({ includeEmpty: false }, (row) => {
|
|
249
|
+
if (grid.length >= maxRows) {
|
|
250
|
+
truncated++;
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
const cells = [];
|
|
254
|
+
row.eachCell({ includeEmpty: true }, (cell, column) => {
|
|
255
|
+
cells[column - 1] = tableCell(cellText(cell));
|
|
256
|
+
});
|
|
257
|
+
grid.push(Array.from(cells, (value) => value ?? ''));
|
|
258
|
+
});
|
|
259
|
+
const trimmed = trimEmptyColumns(grid);
|
|
260
|
+
if (!trimmed.length) {
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
const lines = [`## Sheet: ${sheet.name}`, '', markdownTable(trimmed)];
|
|
264
|
+
if (truncated) {
|
|
265
|
+
const note = `Only the first ${maxRows.toLocaleString()} rows of "${sheet.name}" are included; ${truncated.toLocaleString()} more were left out.`;
|
|
266
|
+
lines.push('', `> ${note}`);
|
|
267
|
+
warnings.push(note);
|
|
268
|
+
}
|
|
269
|
+
pages.push({ pageNum: pages.length + 1, markdown: lines.join('\n'), label: sheet.name });
|
|
270
|
+
}
|
|
271
|
+
return { pages, warnings };
|
|
272
|
+
}
|
|
273
|
+
/** A cell as a person reading the workbook would see it. */
|
|
274
|
+
function cellText(cell) {
|
|
275
|
+
// A merged range shows its value once, in its top-left cell. Repeating it in
|
|
276
|
+
// every covered cell would turn one title into a row of six.
|
|
277
|
+
if (cell.isMerged && cell.master && cell.master.address !== cell.address) {
|
|
278
|
+
return '';
|
|
279
|
+
}
|
|
280
|
+
let value = cell.value;
|
|
281
|
+
if (value && typeof value === 'object' && !(value instanceof Date)) {
|
|
282
|
+
if ('result' in value)
|
|
283
|
+
value = value.result; // a formula: show what it evaluates to
|
|
284
|
+
else if ('richText' in value)
|
|
285
|
+
value = value.richText.map((part) => part.text).join('');
|
|
286
|
+
else if ('text' in value)
|
|
287
|
+
value = value.text; // a hyperlink: show its text
|
|
288
|
+
else if ('error' in value)
|
|
289
|
+
value = value.error;
|
|
290
|
+
}
|
|
291
|
+
if (value === null || value === undefined)
|
|
292
|
+
return '';
|
|
293
|
+
if (value instanceof Date)
|
|
294
|
+
return formatDate(value);
|
|
295
|
+
if (typeof value === 'number')
|
|
296
|
+
return formatNumber(value, cell.numFmt);
|
|
297
|
+
return String(value);
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Excel stores dates as local wall-clock values with no zone, and ExcelJS reads
|
|
301
|
+
* them back as UTC. So a date is formatted from its UTC fields, which recovers
|
|
302
|
+
* the date the author typed rather than shifting it by the server's offset.
|
|
303
|
+
*/
|
|
304
|
+
function formatDate(value) {
|
|
305
|
+
const iso = value.toISOString();
|
|
306
|
+
return iso.endsWith('T00:00:00.000Z') ? iso.slice(0, 10) : iso.slice(0, 16).replace('T', ' ');
|
|
307
|
+
}
|
|
308
|
+
/** A percentage stored as 0.15 is shown as 15% — a reader told "0.15" for a loss ratio is misled. */
|
|
309
|
+
function formatNumber(value, numFmt) {
|
|
310
|
+
if (numFmt && numFmt.includes('%')) {
|
|
311
|
+
return `${parseFloat((value * 100).toFixed(4))}%`;
|
|
312
|
+
}
|
|
313
|
+
return String(value);
|
|
314
|
+
}
|
|
315
|
+
function trimEmptyColumns(grid) {
|
|
316
|
+
const width = grid.reduce((max, row) => {
|
|
317
|
+
let last = row.length - 1;
|
|
318
|
+
while (last >= 0 && !row[last])
|
|
319
|
+
last--;
|
|
320
|
+
return Math.max(max, last + 1);
|
|
321
|
+
}, 0);
|
|
322
|
+
return grid.map((row) => Array.from({ length: width }, (_, index) => row[index] ?? '')).filter((row) => row.some(Boolean));
|
|
323
|
+
}
|
|
324
|
+
// ---------------------------------------------------------------------------
|
|
325
|
+
// Tables
|
|
326
|
+
// ---------------------------------------------------------------------------
|
|
327
|
+
/** One cell's text, made safe to sit inside a GFM table row. */
|
|
328
|
+
function tableCell(text) {
|
|
329
|
+
return text
|
|
330
|
+
.trim()
|
|
331
|
+
.replace(/\|/g, '\\|')
|
|
332
|
+
.replace(/\s*\n\s*/g, '<br>');
|
|
333
|
+
}
|
|
334
|
+
/** A GFM table, taking the first row as the header and padding ragged rows. */
|
|
335
|
+
function markdownTable(grid) {
|
|
336
|
+
const width = Math.max(...grid.map((row) => row.length));
|
|
337
|
+
const pad = (row) => Array.from({ length: width }, (_, index) => row[index] ?? '');
|
|
338
|
+
const line = (row) => `| ${pad(row).join(' | ')} |`;
|
|
339
|
+
const [header, ...body] = grid;
|
|
340
|
+
return [line(header), `| ${Array.from({ length: width }, () => '---').join(' | ')} |`, ...body.map(line)].join('\n');
|
|
341
|
+
}
|
|
@@ -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
|
+
}
|