briyah 2.0.6 → 2.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +105 -0
  2. package/data/packs/dnd5e/pack.json +7 -1
  3. package/dist-sdk/server/src/ai/agent.d.ts +27 -0
  4. package/dist-sdk/server/src/ai/agent.js +54 -13
  5. package/dist-sdk/server/src/app/user-service-factory.js +3 -0
  6. package/dist-sdk/server/src/app.controller.d.ts +7 -1
  7. package/dist-sdk/server/src/app.controller.js +55 -0
  8. package/dist-sdk/server/src/app.service.d.ts +114 -2
  9. package/dist-sdk/server/src/app.service.js +181 -4
  10. package/dist-sdk/server/src/documents/document-conversion.d.ts +70 -0
  11. package/dist-sdk/server/src/documents/document-conversion.js +341 -0
  12. package/dist-sdk/server/src/documents/library/chunking.d.ts +65 -0
  13. package/dist-sdk/server/src/documents/library/chunking.js +263 -0
  14. package/dist-sdk/server/src/documents/library/document-guide.builder.d.ts +2 -0
  15. package/dist-sdk/server/src/documents/library/document-guide.builder.js +58 -0
  16. package/dist-sdk/server/src/documents/library/document-registry.d.ts +22 -0
  17. package/dist-sdk/server/src/documents/library/document-registry.js +44 -0
  18. package/dist-sdk/server/src/documents/library/document.types.d.ts +108 -0
  19. package/dist-sdk/server/src/documents/library/document.types.js +20 -0
  20. package/dist-sdk/server/src/documents/library/embedding.d.ts +57 -0
  21. package/dist-sdk/server/src/documents/library/embedding.js +151 -0
  22. package/dist-sdk/server/src/packs/pack-manifest.d.ts +46 -0
  23. package/dist-sdk/server/src/packs/pack-manifest.js +46 -1
  24. package/dist-sdk/server/src/room/artifact-store.service.js +44 -11
  25. package/dist-sdk/server/src/room/artifact.d.ts +8 -0
  26. package/dist-sdk/server/src/room/room.js +7 -1
  27. package/dist-sdk/server/src/rpg/rpg-roster.d.ts +70 -29
  28. package/dist-sdk/server/src/rpg/rpg-roster.js +152 -41
  29. package/dist-sdk/server/src/rpg/rpg.service.d.ts +66 -29
  30. package/dist-sdk/server/src/rpg/rpg.service.js +140 -65
  31. package/dist-sdk/server/src/sdk/index.d.ts +12 -2
  32. package/dist-sdk/server/src/sdk/index.js +27 -1
  33. package/dist-sdk/server/src/tools/core/document.tools.d.ts +39 -0
  34. package/dist-sdk/server/src/tools/core/document.tools.js +391 -0
  35. package/dist-sdk/server/src/tools/core/index.js +2 -1
  36. package/dist-sdk/server/src/tools/native-tool.types.d.ts +37 -0
  37. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +23 -2
  38. package/dist-sdk/server/src/tools/tool-execution.service.js +30 -6
  39. package/dist-sdk/shared/types/app.types.d.ts +39 -5
  40. package/package.json +172 -167
@@ -43,6 +43,9 @@ const core_1 = require("./tools/core");
43
43
  const app_types_1 = require("../../shared/types/app.types");
44
44
  const pdf_lib_1 = require("pdf-lib");
45
45
  const pdf_conversion_1 = require("./documents/pdf-conversion");
46
+ const document_conversion_1 = require("./documents/document-conversion");
47
+ const embedding_1 = require("./documents/library/embedding");
48
+ const document_tools_1 = require("./tools/core/document.tools");
46
49
  const app_types_2 = require("../../shared/types/app.types");
47
50
  const message_1 = require("./room/message");
48
51
  const logger_1 = require("./common/logger");
@@ -523,6 +526,70 @@ class AppService {
523
526
  agent.save();
524
527
  return { documentId: fileId };
525
528
  }
529
+ /**
530
+ * Releases every library document an agent is holding — the ones
531
+ * `load_document` attached — and keeps the documents its configuration
532
+ * attached. {@link resetRoom} does this itself; call it directly to let go of
533
+ * held documents without resetting anything else.
534
+ *
535
+ * @param agentId - The agent's ID
536
+ * @returns How many documents were released
537
+ */
538
+ async releaseLibraryDocuments(agentId) {
539
+ const store = this.agentDocumentStore();
540
+ let released = 0;
541
+ for (const file of await store.held(agentId)) {
542
+ if ((0, document_tools_1.isLibraryAttachment)(file.fileName) && (await store.detach(agentId, file.documentId))) {
543
+ released++;
544
+ }
545
+ }
546
+ return released;
547
+ }
548
+ /**
549
+ * @internal The store behind a tool's `helpers.documents`, which the tool
550
+ * execution service binds to one calling agent at a time.
551
+ *
552
+ * Two differences from {@link attachDocument} and {@link deleteAttachedFileById},
553
+ * both on purpose. Attaching a name the agent already holds replaces that
554
+ * document: attaching over it directly keeps the old entry's id while
555
+ * returning a new one, so a later detach by the returned id would miss. And
556
+ * detaching is scoped to the one agent rather than searching all of them, so
557
+ * a tool cannot detach another agent's document by guessing its id.
558
+ */
559
+ agentDocumentStore() {
560
+ const agentFor = async (agentId) => {
561
+ const agent = await this.agentStore.getAgent(agentId);
562
+ if (!agent)
563
+ throw new errors_1.NotFoundError(`Agent ${agentId} not found`);
564
+ return agent;
565
+ };
566
+ const detach = async (agentId, documentId) => {
567
+ const agent = await agentFor(agentId);
568
+ if (!agent.attachedFiles.some((file) => file.fileId === documentId)) {
569
+ return false;
570
+ }
571
+ this.attachedFileService.deleteFile(agentId, documentId);
572
+ agent.attachedFiles = agent.attachedFiles.filter((file) => file.fileId !== documentId);
573
+ agent.save();
574
+ return true;
575
+ };
576
+ return {
577
+ attach: async (agentId, fileName, body) => {
578
+ const agent = await agentFor(agentId);
579
+ for (const previous of agent.attachedFiles.filter((file) => file.fileName === fileName)) {
580
+ await detach(agentId, previous.fileId);
581
+ }
582
+ const { documentId } = await this.attachDocument(agentId, fileName, Buffer.from(body, 'utf8'));
583
+ return documentId;
584
+ },
585
+ detach,
586
+ held: async (agentId) => (await agentFor(agentId)).attachedFiles.map((file) => ({
587
+ documentId: file.fileId,
588
+ fileName: file.fileName,
589
+ chars: file.size ?? 0,
590
+ })),
591
+ };
592
+ }
526
593
  /**
527
594
  * Returns every prompt folder name this user can reach.
528
595
  *
@@ -1308,6 +1375,28 @@ class AppService {
1308
1375
  totalCost: agent.totalCost,
1309
1376
  };
1310
1377
  }
1378
+ /**
1379
+ * Removes the newest message from an agent's conversation.
1380
+ *
1381
+ * Returns the conversation as it now stands rather than nothing, because the
1382
+ * caller is a button somebody clicks repeatedly: a second round trip for the new
1383
+ * transcript would show the list lagging a click behind on a slow connection.
1384
+ *
1385
+ * @param agentId The agent whose history to shorten
1386
+ * @returns The remaining messages and the agent's running totals
1387
+ * @throws {NotFoundError} If there is no such agent
1388
+ */
1389
+ async deleteLastAgentMessage(agentId) {
1390
+ const agent = await this.agentStore.getAgent(agentId);
1391
+ if (!agent) {
1392
+ throw new errors_1.NotFoundError(`Agent ${agentId} not found`);
1393
+ }
1394
+ // Deliberately not reported: a history holding nothing but its framing is the
1395
+ // same answer as one message removed — an empty transcript — and the button
1396
+ // is allowed to bottom out under a finger that keeps pressing it.
1397
+ agent.deleteLastMessage();
1398
+ return await this.getAgentMessages(agentId, 0);
1399
+ }
1311
1400
  /**
1312
1401
  * Gets messages from a story's room starting from a specific index
1313
1402
  * @param storyId The story ID
@@ -2540,10 +2629,24 @@ class AppService {
2540
2629
  * Agent configurations (model, prompt, files) are preserved; only conversation
2541
2630
  * history and artifacts are removed.
2542
2631
  *
2632
+ * Pass `keepArtifacts` when the artifacts are the point of the room rather
2633
+ * than scratch state. An assistant that writes a report for a person is the
2634
+ * case: "start a new conversation" means forget what we said, not destroy
2635
+ * what you made me. Kept artifacts stay visible to the agents that could see
2636
+ * them before, so an agent can still revise its own work after the reset.
2637
+ *
2638
+ * Library documents an agent chose to hold with `load_document` are released
2639
+ * first. Resetting re-attaches everything an agent still holds, so without
2640
+ * this a contract loaded for one conversation would ride every request of
2641
+ * the next. Documents the agent's own configuration attached are kept, as
2642
+ * before. Pass `keepHeldDocuments` to keep the library ones too.
2643
+ *
2543
2644
  * @param roomId - The room's ID
2645
+ * @param options.keepArtifacts - Keep the room's artifacts. Defaults to false.
2646
+ * @param options.keepHeldDocuments - Keep library documents agents are holding. Defaults to false.
2544
2647
  * @throws {NotFoundError} If the room does not exist
2545
2648
  */
2546
- async resetRoom(roomId) {
2649
+ async resetRoom(roomId, options = {}) {
2547
2650
  // Get the room
2548
2651
  const room = await this.roomStore.getRoom(roomId);
2549
2652
  if (!room) {
@@ -2553,13 +2656,18 @@ class AppService {
2553
2656
  const storageDir = room.getStorageDir() || this.roomStore.getDefaultStorageDir();
2554
2657
  // Clear room messages (both in-memory and on disk)
2555
2658
  this.roomStore.clearRoomMessages(roomId, storageDir);
2556
- // Clear all artifacts (delete files and clear in-memory)
2557
- this.roomStore.deleteAllArtifactFiles(roomId, storageDir);
2558
- room.setArtifacts([]);
2659
+ if (!options.keepArtifacts) {
2660
+ // Clear all artifacts (delete files and clear in-memory)
2661
+ this.roomStore.deleteAllArtifactFiles(roomId, storageDir);
2662
+ room.setArtifacts([]);
2663
+ }
2559
2664
  // Reset each agent using the existing reloadAgent logic
2560
2665
  const warnings = [];
2561
2666
  for (const agent of room.getAgents()) {
2562
2667
  try {
2668
+ if (!options.keepHeldDocuments) {
2669
+ await this.releaseLibraryDocuments(agent.id);
2670
+ }
2563
2671
  // Use existing reloadAgent functionality to clear history and re-attach files
2564
2672
  this.reloadAgent(agent.id);
2565
2673
  }
@@ -3517,6 +3625,75 @@ class AppService {
3517
3625
  const result = await (0, pdf_conversion_1.convertPdfToMarkdown)(pdfBuffer, renderPage, options);
3518
3626
  return result;
3519
3627
  }
3628
+ /**
3629
+ * Embeds texts for semantic search, and charges what it cost to this user's
3630
+ * balance the way every other model call is charged.
3631
+ *
3632
+ * The module-level `embedTexts` does the work and is exported for a host that
3633
+ * keeps its own accounting; this is the one to call otherwise, so embedding a
3634
+ * document library is not the one AI cost that goes unrecorded.
3635
+ *
3636
+ * @param texts - What to embed; one vector comes back per text, in order
3637
+ * @param options - Model, dimensions, provider and progress; every field has a default
3638
+ * @returns The vectors, and the tokens and dollars they cost
3639
+ */
3640
+ async embedTexts(texts, options = {}) {
3641
+ const result = await (0, embedding_1.embedTexts)(texts, options);
3642
+ if (result.cost > 0) {
3643
+ this.balanceService.decrementBalance(result.cost, 0);
3644
+ }
3645
+ return result;
3646
+ }
3647
+ /**
3648
+ * Converts any supported upload to Markdown pages — PDF, Word (.docx), Excel
3649
+ * (.xlsx) or plain text — so a host handles one result shape whatever arrived.
3650
+ *
3651
+ * The type is decided from the file's contents, not its name. A PDF goes
3652
+ * through {@link convertPdfToMarkdownPages} and costs AI calls; Word, Excel and
3653
+ * text convert locally, instantly and for nothing. Anything else is refused
3654
+ * with a reason written for the person who uploaded it — never decoded as text
3655
+ * and handed on, which is how a .docx turns into a page of mojibake that an
3656
+ * agent then summarises with confidence.
3657
+ *
3658
+ * @param fileBuffer - The uploaded file
3659
+ * @param fileName - Its name, used only to word error messages and break ties
3660
+ * @param options - The PDF options, plus `maxRowsPerSheet` for workbooks
3661
+ * @returns The pages, the assembled Markdown, what failed, what was left out, and the cost
3662
+ * @throws {UnsupportedDocumentError} If the file is not a type that can be read
3663
+ *
3664
+ * @example
3665
+ * ```typescript
3666
+ * try {
3667
+ * const doc = await appService.convertDocumentToMarkdown(buffer, 'contract.docx');
3668
+ * doc.warnings.forEach((warning) => console.warn(warning));
3669
+ * } catch (error) {
3670
+ * if (error instanceof UnsupportedDocumentError) respondWith(415, error.message);
3671
+ * }
3672
+ * ```
3673
+ */
3674
+ async convertDocumentToMarkdown(fileBuffer, fileName, options = {}) {
3675
+ const bytes = fileBuffer instanceof Uint8Array ? fileBuffer : new Uint8Array(fileBuffer);
3676
+ const detection = (0, document_conversion_1.detectDocumentType)(bytes, fileName);
3677
+ if (detection.type === 'unsupported') {
3678
+ throw new document_conversion_1.UnsupportedDocumentError(detection.reason);
3679
+ }
3680
+ if (detection.type !== 'pdf') {
3681
+ const local = await (0, document_conversion_1.convertLocalDocument)(bytes, fileName, options);
3682
+ return { ...local, failedPages: [], totalCost: 0, agents: [] };
3683
+ }
3684
+ const pdf = await this.convertPdfToMarkdownPages(bytes, options);
3685
+ return {
3686
+ type: 'pdf',
3687
+ pages: pdf.pages.map((page) => ({ pageNum: page.pageNum, markdown: page.markdown })),
3688
+ markdown: pdf.markdown,
3689
+ failedPages: pdf.failedPages,
3690
+ totalCost: pdf.totalCost,
3691
+ agents: pdf.agents,
3692
+ warnings: pdf.failedPages.length
3693
+ ? [`Page(s) ${pdf.failedPages.join(', ')} could not be read and are missing from the text.`]
3694
+ : [],
3695
+ };
3696
+ }
3520
3697
  /**
3521
3698
  * Converts a whole PDF in one request, for a document short enough that page
3522
3699
  * continuity is worth more than page-level recovery.
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Turning an uploaded file into Markdown pages, whatever kind of file it was.
3
+ *
4
+ * PDFs go through the per-page AI conversion in `pdf-conversion.ts`, because a
5
+ * PDF is a picture of a page and needs reading. Word and Excel files do not: they
6
+ * already carry their text and structure, so they convert locally, instantly and
7
+ * for nothing. This module owns that local half, plus the one decision both
8
+ * halves depend on — what kind of file this actually is.
9
+ *
10
+ * That decision is the part worth getting right. A host that assumed "not a PDF,
11
+ * so text" would decode a .docx as UTF-8 and hand an agent a page of mojibake,
12
+ * which the agent then summarises with complete confidence. So an unrecognised
13
+ * file is refused with a reason a person can act on, never guessed at.
14
+ *
15
+ * Page numbers mean what a reader would expect. A PDF has real pages. A Word
16
+ * document does not — its pagination is decided by whatever renders it — so it
17
+ * comes back as one page, and an agent locates a passage by its heading instead
18
+ * of by a page number that would not match the user's screen. A workbook comes
19
+ * back as one page per visible sheet, labelled with the sheet's name.
20
+ */
21
+ /** What a file turned out to be. */
22
+ export type DocumentFileType = 'pdf' | 'docx' | 'xlsx' | 'text' | 'unsupported';
23
+ export interface DocumentTypeDetection {
24
+ type: DocumentFileType;
25
+ /** Why the file cannot be read, phrased for the person who uploaded it. Set only when unsupported. */
26
+ reason?: string;
27
+ }
28
+ /** One page of a converted document. */
29
+ export interface DocumentPage {
30
+ /** 1-based. For a workbook, the sheet's position among the sheets converted. */
31
+ pageNum: number;
32
+ markdown: string;
33
+ /** A name for the page when it has one — a workbook's sheet name. */
34
+ label?: string;
35
+ }
36
+ /** A locally converted document. PDFs are not produced here; see `convertPdfToMarkdownPages`. */
37
+ export interface LocalDocumentConversion {
38
+ type: 'docx' | 'xlsx' | 'text';
39
+ pages: DocumentPage[];
40
+ /** The pages assembled with `<!-- Page N -->` markers, the same format the PDF path writes. */
41
+ markdown: string;
42
+ /** Things the reader should know were changed or left out: hidden sheets, truncated rows, images. */
43
+ warnings: string[];
44
+ }
45
+ export interface LocalConversionOptions {
46
+ /**
47
+ * Rows kept per worksheet. A sheet past this is cut, and the cut is stated in
48
+ * the page and in `warnings` — a silently shortened schedule reads as complete.
49
+ * Defaults to 5,000.
50
+ */
51
+ maxRowsPerSheet?: number;
52
+ }
53
+ /** Thrown for a file that cannot be read. `message` is written for the person who uploaded it. */
54
+ export declare class UnsupportedDocumentError extends Error {
55
+ constructor(message: string);
56
+ }
57
+ /**
58
+ * Decides what a file is from its contents, using the name only to break ties.
59
+ *
60
+ * .docx and .xlsx are both ZIP archives, so their magic bytes are identical; the
61
+ * archive's entries are what tell them apart. The extension alone is never
62
+ * trusted over the contents — a renamed file is refused rather than misread.
63
+ */
64
+ export declare function detectDocumentType(bytes: Uint8Array, fileName: string): DocumentTypeDetection;
65
+ /**
66
+ * Converts a Word, Excel or plain-text file to Markdown pages, locally.
67
+ *
68
+ * @throws {UnsupportedDocumentError} For a PDF (which needs the AI path) or anything unreadable
69
+ */
70
+ export declare function convertLocalDocument(bytes: Uint8Array, fileName: string, options?: LocalConversionOptions): Promise<LocalDocumentConversion>;
@@ -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
+ }