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.
- package/README.md +105 -0
- package/data/packs/dnd5e/pack.json +7 -1
- package/dist-sdk/server/src/ai/agent.d.ts +27 -0
- package/dist-sdk/server/src/ai/agent.js +54 -13
- package/dist-sdk/server/src/app/user-service-factory.js +3 -0
- package/dist-sdk/server/src/app.controller.d.ts +7 -1
- package/dist-sdk/server/src/app.controller.js +55 -0
- package/dist-sdk/server/src/app.service.d.ts +114 -2
- package/dist-sdk/server/src/app.service.js +181 -4
- package/dist-sdk/server/src/documents/document-conversion.d.ts +70 -0
- package/dist-sdk/server/src/documents/document-conversion.js +394 -0
- package/dist-sdk/server/src/documents/library/chunking.d.ts +65 -0
- package/dist-sdk/server/src/documents/library/chunking.js +263 -0
- package/dist-sdk/server/src/documents/library/document-guide.builder.d.ts +2 -0
- package/dist-sdk/server/src/documents/library/document-guide.builder.js +58 -0
- package/dist-sdk/server/src/documents/library/document-registry.d.ts +22 -0
- package/dist-sdk/server/src/documents/library/document-registry.js +44 -0
- package/dist-sdk/server/src/documents/library/document.types.d.ts +108 -0
- package/dist-sdk/server/src/documents/library/document.types.js +20 -0
- package/dist-sdk/server/src/documents/library/embedding.d.ts +57 -0
- package/dist-sdk/server/src/documents/library/embedding.js +151 -0
- package/dist-sdk/server/src/packs/pack-manifest.d.ts +46 -0
- package/dist-sdk/server/src/packs/pack-manifest.js +46 -1
- package/dist-sdk/server/src/room/artifact-store.service.js +44 -11
- package/dist-sdk/server/src/room/artifact.d.ts +8 -0
- package/dist-sdk/server/src/room/room.js +7 -1
- package/dist-sdk/server/src/rpg/rpg-roster.d.ts +70 -29
- package/dist-sdk/server/src/rpg/rpg-roster.js +152 -41
- package/dist-sdk/server/src/rpg/rpg.service.d.ts +66 -29
- package/dist-sdk/server/src/rpg/rpg.service.js +140 -65
- package/dist-sdk/server/src/sdk/index.d.ts +12 -2
- package/dist-sdk/server/src/sdk/index.js +27 -1
- package/dist-sdk/server/src/tools/core/document.tools.d.ts +39 -0
- package/dist-sdk/server/src/tools/core/document.tools.js +391 -0
- package/dist-sdk/server/src/tools/core/index.js +2 -1
- package/dist-sdk/server/src/tools/native-tool.types.d.ts +37 -0
- package/dist-sdk/server/src/tools/tool-execution.service.d.ts +23 -2
- package/dist-sdk/server/src/tools/tool-execution.service.js +30 -6
- package/dist-sdk/shared/types/app.types.d.ts +39 -5
- package/package.json +172 -167
|
@@ -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
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
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>;
|