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.
Files changed (55) hide show
  1. package/README.md +105 -0
  2. package/data/common/prompts/moderate.json +34 -0
  3. package/data/common/prompts/moderate.prompt +136 -0
  4. package/data/packs/dnd5e/pack.json +7 -1
  5. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +16 -0
  6. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +23 -0
  7. package/dist-sdk/server/src/ai/agent.d.ts +33 -0
  8. package/dist-sdk/server/src/ai/agent.js +64 -13
  9. package/dist-sdk/server/src/app/user-service-factory.js +3 -0
  10. package/dist-sdk/server/src/app.controller.d.ts +7 -1
  11. package/dist-sdk/server/src/app.controller.js +55 -0
  12. package/dist-sdk/server/src/app.service.d.ts +114 -2
  13. package/dist-sdk/server/src/app.service.js +181 -4
  14. package/dist-sdk/server/src/data/data-guide.builder.d.ts +2 -0
  15. package/dist-sdk/server/src/data/data-guide.builder.js +90 -0
  16. package/dist-sdk/server/src/data/data-registry.d.ts +32 -0
  17. package/dist-sdk/server/src/data/data-registry.js +61 -0
  18. package/dist-sdk/server/src/data/data.types.d.ts +158 -0
  19. package/dist-sdk/server/src/data/data.types.js +24 -0
  20. package/dist-sdk/server/src/data/query-validation.d.ts +45 -0
  21. package/dist-sdk/server/src/data/query-validation.js +245 -0
  22. package/dist-sdk/server/src/documents/document-conversion.d.ts +70 -0
  23. package/dist-sdk/server/src/documents/document-conversion.js +341 -0
  24. package/dist-sdk/server/src/documents/library/chunking.d.ts +65 -0
  25. package/dist-sdk/server/src/documents/library/chunking.js +263 -0
  26. package/dist-sdk/server/src/documents/library/document-guide.builder.d.ts +2 -0
  27. package/dist-sdk/server/src/documents/library/document-guide.builder.js +58 -0
  28. package/dist-sdk/server/src/documents/library/document-registry.d.ts +22 -0
  29. package/dist-sdk/server/src/documents/library/document-registry.js +44 -0
  30. package/dist-sdk/server/src/documents/library/document.types.d.ts +108 -0
  31. package/dist-sdk/server/src/documents/library/document.types.js +20 -0
  32. package/dist-sdk/server/src/documents/library/embedding.d.ts +57 -0
  33. package/dist-sdk/server/src/documents/library/embedding.js +151 -0
  34. package/dist-sdk/server/src/packs/pack-manifest.d.ts +46 -0
  35. package/dist-sdk/server/src/packs/pack-manifest.js +46 -1
  36. package/dist-sdk/server/src/room/artifact-store.service.js +44 -11
  37. package/dist-sdk/server/src/room/artifact.d.ts +8 -0
  38. package/dist-sdk/server/src/room/room.d.ts +7 -5
  39. package/dist-sdk/server/src/room/room.js +44 -7
  40. package/dist-sdk/server/src/rpg/rpg-roster.d.ts +70 -29
  41. package/dist-sdk/server/src/rpg/rpg-roster.js +152 -41
  42. package/dist-sdk/server/src/rpg/rpg.service.d.ts +66 -29
  43. package/dist-sdk/server/src/rpg/rpg.service.js +140 -65
  44. package/dist-sdk/server/src/sdk/index.d.ts +16 -2
  45. package/dist-sdk/server/src/sdk/index.js +37 -1
  46. package/dist-sdk/server/src/tools/core/data.tools.d.ts +17 -0
  47. package/dist-sdk/server/src/tools/core/data.tools.js +165 -0
  48. package/dist-sdk/server/src/tools/core/document.tools.d.ts +39 -0
  49. package/dist-sdk/server/src/tools/core/document.tools.js +391 -0
  50. package/dist-sdk/server/src/tools/core/index.js +3 -1
  51. package/dist-sdk/server/src/tools/native-tool.types.d.ts +37 -0
  52. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +23 -2
  53. package/dist-sdk/server/src/tools/tool-execution.service.js +30 -6
  54. package/dist-sdk/shared/types/app.types.d.ts +39 -5
  55. package/package.json +172 -167
@@ -26,10 +26,12 @@ import { AgentFactory } from './ai/agent-factory';
26
26
  import { RoomFactory } from './room/room-factory';
27
27
  import { EventEmitter } from 'events';
28
28
  import { PdfConversionOptions, PdfConversionResult } from './documents/pdf-conversion';
29
+ import { DocumentFileType, DocumentPage, LocalConversionOptions } from './documents/document-conversion';
30
+ import { EmbeddingOptions, EmbeddingResult } from './documents/library/embedding';
29
31
  import { AgentInfo, RoomInfo, RoomDetails, RoomIllustrationMode, RoomTurnMode, CreateRoomResponse, CreateAgentResponse, CreateRoomAgentRequest, FileList, PromptFileContent, PromptFoldersResponse, PromptFilesResponse, PromptScope, PromptFolderDefaults, PromptFolderDefaultsResponse, ProcessTextResponse, PreparedPromptResponse, AttachDocumentResponse, AgentMessagesResponse, RoomMessagesResponse, SendMessageResult, StoryInfo, StoryState, Character, Transaction, TransactionHistoryResponse, ToolDefinition, ToolSummary, ToolRunResult } from '../../shared/types/app.types';
30
32
  import { RoomMessage } from './room/message';
31
33
  import { ToolStoreService } from './tools/tool-store.service';
32
- import { ToolExecutionService } from './tools/tool-execution.service';
34
+ import { AgentDocumentStore, ToolExecutionService } from './tools/tool-execution.service';
33
35
  /**
34
36
  * Agent settings that {@link AppService.createAgent} takes as an object rather
35
37
  * than a positional parameter.
@@ -105,6 +107,24 @@ export interface PdfMarkdownOptions extends PdfConversionOptions {
105
107
  export interface PdfMarkdownResult extends Omit<PdfConversionResult, 'agents'> {
106
108
  agents: Agent[];
107
109
  }
110
+ /** Options for {@link AppService.convertDocumentToMarkdown}. The PDF options apply only to a PDF. */
111
+ export interface DocumentMarkdownOptions extends PdfMarkdownOptions, LocalConversionOptions {
112
+ }
113
+ /** Any supported upload, converted. The same shape whatever the file was. */
114
+ export interface DocumentMarkdownResult {
115
+ type: Exclude<DocumentFileType, 'unsupported'>;
116
+ pages: DocumentPage[];
117
+ /** The pages assembled with `<!-- Page N -->` markers. */
118
+ markdown: string;
119
+ /** PDF pages that could not be read. Always empty for other types. */
120
+ failedPages: number[];
121
+ /** What the conversion cost. Zero for anything but a PDF. */
122
+ totalCost: number;
123
+ /** The conversion agents, for a caller that reads costs off them. Empty for anything but a PDF. */
124
+ agents: Agent[];
125
+ /** What a reader should know was changed or left out. */
126
+ warnings: string[];
127
+ }
108
128
  export declare class AppService {
109
129
  private readonly aiFactoryService;
110
130
  private readonly agentStore;
@@ -347,6 +367,28 @@ export declare class AppService {
347
367
  * @throws {Error} If no agent with the given ID exists
348
368
  */
349
369
  attachDocument(agentId: string, fileName: string, fileData: Buffer): Promise<AttachDocumentResponse>;
370
+ /**
371
+ * Releases every library document an agent is holding — the ones
372
+ * `load_document` attached — and keeps the documents its configuration
373
+ * attached. {@link resetRoom} does this itself; call it directly to let go of
374
+ * held documents without resetting anything else.
375
+ *
376
+ * @param agentId - The agent's ID
377
+ * @returns How many documents were released
378
+ */
379
+ releaseLibraryDocuments(agentId: string): Promise<number>;
380
+ /**
381
+ * @internal The store behind a tool's `helpers.documents`, which the tool
382
+ * execution service binds to one calling agent at a time.
383
+ *
384
+ * Two differences from {@link attachDocument} and {@link deleteAttachedFileById},
385
+ * both on purpose. Attaching a name the agent already holds replaces that
386
+ * document: attaching over it directly keeps the old entry's id while
387
+ * returning a new one, so a later detach by the returned id would miss. And
388
+ * detaching is scoped to the one agent rather than searching all of them, so
389
+ * a tool cannot detach another agent's document by guessing its id.
390
+ */
391
+ agentDocumentStore(): AgentDocumentStore;
350
392
  /**
351
393
  * Returns every prompt folder name this user can reach.
352
394
  *
@@ -667,6 +709,18 @@ export declare class AppService {
667
709
  * Returns empty messages with zero counts if the agent is not found.
668
710
  */
669
711
  getAgentMessages(agentId: string, fromIndex?: number): Promise<AgentMessagesResponse>;
712
+ /**
713
+ * Removes the newest message from an agent's conversation.
714
+ *
715
+ * Returns the conversation as it now stands rather than nothing, because the
716
+ * caller is a button somebody clicks repeatedly: a second round trip for the new
717
+ * transcript would show the list lagging a click behind on a slow connection.
718
+ *
719
+ * @param agentId The agent whose history to shorten
720
+ * @returns The remaining messages and the agent's running totals
721
+ * @throws {NotFoundError} If there is no such agent
722
+ */
723
+ deleteLastAgentMessage(agentId: string): Promise<AgentMessagesResponse>;
670
724
  /**
671
725
  * Gets messages from a story's room starting from a specific index
672
726
  * @param storyId The story ID
@@ -1232,10 +1286,27 @@ export declare class AppService {
1232
1286
  * Agent configurations (model, prompt, files) are preserved; only conversation
1233
1287
  * history and artifacts are removed.
1234
1288
  *
1289
+ * Pass `keepArtifacts` when the artifacts are the point of the room rather
1290
+ * than scratch state. An assistant that writes a report for a person is the
1291
+ * case: "start a new conversation" means forget what we said, not destroy
1292
+ * what you made me. Kept artifacts stay visible to the agents that could see
1293
+ * them before, so an agent can still revise its own work after the reset.
1294
+ *
1295
+ * Library documents an agent chose to hold with `load_document` are released
1296
+ * first. Resetting re-attaches everything an agent still holds, so without
1297
+ * this a contract loaded for one conversation would ride every request of
1298
+ * the next. Documents the agent's own configuration attached are kept, as
1299
+ * before. Pass `keepHeldDocuments` to keep the library ones too.
1300
+ *
1235
1301
  * @param roomId - The room's ID
1302
+ * @param options.keepArtifacts - Keep the room's artifacts. Defaults to false.
1303
+ * @param options.keepHeldDocuments - Keep library documents agents are holding. Defaults to false.
1236
1304
  * @throws {NotFoundError} If the room does not exist
1237
1305
  */
1238
- resetRoom(roomId: string): Promise<void>;
1306
+ resetRoom(roomId: string, options?: {
1307
+ keepArtifacts?: boolean;
1308
+ keepHeldDocuments?: boolean;
1309
+ }): Promise<void>;
1239
1310
  /**
1240
1311
  * Resets a story to the beginning while preserving artifacts and the opening scene.
1241
1312
  *
@@ -1871,6 +1942,47 @@ export declare class AppService {
1871
1942
  * ```
1872
1943
  */
1873
1944
  convertPdfToMarkdownPages(pdfBuffer: Buffer | Uint8Array, options?: PdfMarkdownOptions): Promise<PdfMarkdownResult>;
1945
+ /**
1946
+ * Embeds texts for semantic search, and charges what it cost to this user's
1947
+ * balance the way every other model call is charged.
1948
+ *
1949
+ * The module-level `embedTexts` does the work and is exported for a host that
1950
+ * keeps its own accounting; this is the one to call otherwise, so embedding a
1951
+ * document library is not the one AI cost that goes unrecorded.
1952
+ *
1953
+ * @param texts - What to embed; one vector comes back per text, in order
1954
+ * @param options - Model, dimensions, provider and progress; every field has a default
1955
+ * @returns The vectors, and the tokens and dollars they cost
1956
+ */
1957
+ embedTexts(texts: readonly string[], options?: EmbeddingOptions): Promise<EmbeddingResult>;
1958
+ /**
1959
+ * Converts any supported upload to Markdown pages — PDF, Word (.docx), Excel
1960
+ * (.xlsx) or plain text — so a host handles one result shape whatever arrived.
1961
+ *
1962
+ * The type is decided from the file's contents, not its name. A PDF goes
1963
+ * through {@link convertPdfToMarkdownPages} and costs AI calls; Word, Excel and
1964
+ * text convert locally, instantly and for nothing. Anything else is refused
1965
+ * with a reason written for the person who uploaded it — never decoded as text
1966
+ * and handed on, which is how a .docx turns into a page of mojibake that an
1967
+ * agent then summarises with confidence.
1968
+ *
1969
+ * @param fileBuffer - The uploaded file
1970
+ * @param fileName - Its name, used only to word error messages and break ties
1971
+ * @param options - The PDF options, plus `maxRowsPerSheet` for workbooks
1972
+ * @returns The pages, the assembled Markdown, what failed, what was left out, and the cost
1973
+ * @throws {UnsupportedDocumentError} If the file is not a type that can be read
1974
+ *
1975
+ * @example
1976
+ * ```typescript
1977
+ * try {
1978
+ * const doc = await appService.convertDocumentToMarkdown(buffer, 'contract.docx');
1979
+ * doc.warnings.forEach((warning) => console.warn(warning));
1980
+ * } catch (error) {
1981
+ * if (error instanceof UnsupportedDocumentError) respondWith(415, error.message);
1982
+ * }
1983
+ * ```
1984
+ */
1985
+ convertDocumentToMarkdown(fileBuffer: Buffer | Uint8Array, fileName: string, options?: DocumentMarkdownOptions): Promise<DocumentMarkdownResult>;
1874
1986
  /**
1875
1987
  * Converts a whole PDF in one request, for a document short enough that page
1876
1988
  * continuity is worth more than page-level recovery.
@@ -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,2 @@
1
+ /** @returns The schema guide, or an empty string when nothing is registered */
2
+ export declare function buildDataGuideMarkdown(): string;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildDataGuideMarkdown = buildDataGuideMarkdown;
4
+ const data_registry_1 = require("./data-registry");
5
+ /** @returns The schema guide, or an empty string when nothing is registered */
6
+ function buildDataGuideMarkdown() {
7
+ const sources = (0, data_registry_1.listDataSources)();
8
+ if (sources.length === 0) {
9
+ return '';
10
+ }
11
+ const lines = [
12
+ '# Data You Can Query',
13
+ '',
14
+ 'Each heading below is a **dataset** — a collection of records you can ask',
15
+ 'questions about with the `query_data` tool. Under it are the fields you may',
16
+ 'filter on, group by, and aggregate.',
17
+ '',
18
+ 'You never write SQL. You describe the question as JSON:',
19
+ '',
20
+ '```json',
21
+ '{"dataset": "claims", "groupBy": ["customer"],',
22
+ ' "metrics": [{"fn": "sum", "field": "incurred"}],',
23
+ ' "orderBy": [{"by": "sum_incurred", "dir": "desc"}], "limit": 10}',
24
+ '```',
25
+ '',
26
+ 'A query with no `groupBy` and no `metrics` lists rows. With either, it',
27
+ 'aggregates: `groupBy` gives the dimensions, `metrics` the numbers.',
28
+ '',
29
+ '**Only what is listed here exists.** A field that is not on a dataset cannot',
30
+ 'be filtered, grouped or summed, and two datasets can only be related if a',
31
+ 'field says so. If a question needs something absent, say the system does not',
32
+ 'record it — do not answer with a field that looks close enough.',
33
+ '',
34
+ 'Read each dataset\'s notes before you trust an answer: they say what a set',
35
+ 'excludes and which definition a metric uses.',
36
+ '',
37
+ ];
38
+ for (const source of sources) {
39
+ if (sources.length > 1) {
40
+ lines.push(`## ${source.name}`);
41
+ if (source.description) {
42
+ lines.push(source.description);
43
+ }
44
+ lines.push('');
45
+ }
46
+ for (const set of source.datasets || []) {
47
+ lines.push(...describeDataset(set, sources.length > 1 ? '###' : '##'));
48
+ }
49
+ }
50
+ return lines.join('\n');
51
+ }
52
+ function describeDataset(set, heading) {
53
+ const lines = [`${heading} ${set.label || set.name}`, ''];
54
+ lines.push(`- dataset: \`${set.name}\``);
55
+ lines.push(`- ${set.description}`);
56
+ if (set.notes?.length) {
57
+ lines.push('- Important:');
58
+ for (const note of set.notes) {
59
+ lines.push(` - ${note}`);
60
+ }
61
+ }
62
+ lines.push('- Fields:');
63
+ for (const field of set.fields) {
64
+ lines.push(` - ${describeField(field)}`);
65
+ }
66
+ lines.push('');
67
+ return lines;
68
+ }
69
+ /** One field line: what it is, and what may be done with it. */
70
+ function describeField(field) {
71
+ const parts = [`\`${field.name}\` (${field.type}`];
72
+ if (field.type === 'enum' && field.enumValues?.length) {
73
+ parts.push(`: ${field.enumValues.join(' | ')}`);
74
+ }
75
+ parts.push(')');
76
+ const caps = [];
77
+ if (field.filterable === false) {
78
+ caps.push('not filterable');
79
+ }
80
+ if (field.groupable === false) {
81
+ caps.push('not groupable');
82
+ }
83
+ if (field.aggregates?.length) {
84
+ caps.push(field.aggregates.join('/'));
85
+ }
86
+ const label = field.label && field.label !== field.name ? ` — ${field.label}` : '';
87
+ const description = field.description ? `. ${field.description}` : '';
88
+ const capText = caps.length ? ` [${caps.join(', ')}]` : '';
89
+ return `${parts.join('')}${label}${capText}${description}`;
90
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The process-global registry of host data sources.
3
+ *
4
+ * Module state rather than an injectable, for the same reason
5
+ * {@link NativeToolRegistry} is process-global: a data source is registered once
6
+ * by the host at boot and is the same for every room, and a tool handler runs
7
+ * with no Nest scope to inject into. Per-user and per-tenant scoping does not
8
+ * belong here — it rides the opaque tool context, which is the only thing that
9
+ * knows *whose* data a call is for.
10
+ */
11
+ import { DataSet, DataSource } from './data.types';
12
+ /**
13
+ * Registers (or replaces) a data source.
14
+ *
15
+ * Dataset names are global: two sources cannot both offer `claims`, because an
16
+ * agent names a dataset and nothing else, so a duplicate would be ambiguous at
17
+ * exactly the moment it mattered.
18
+ * @param source The host's data source
19
+ */
20
+ export declare function registerDataSource(source: DataSource): void;
21
+ /** Removes a data source. @returns True if one was removed */
22
+ export declare function unregisterDataSource(name: string): boolean;
23
+ /** @returns Every registered source, in registration order */
24
+ export declare function listDataSources(): DataSource[];
25
+ /** @returns Every dataset any source offers, flattened as an agent sees them */
26
+ export declare function listDatasets(): DataSet[];
27
+ /** @returns The source that owns a dataset, or undefined */
28
+ export declare function sourceForDataset(datasetName: string): DataSource | undefined;
29
+ /** @returns Whether any source is registered — the tools say so rather than failing oddly */
30
+ export declare function hasDataSources(): boolean;
31
+ /** Test seam. */
32
+ export declare function resetDataSources(): void;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerDataSource = registerDataSource;
4
+ exports.unregisterDataSource = unregisterDataSource;
5
+ exports.listDataSources = listDataSources;
6
+ exports.listDatasets = listDatasets;
7
+ exports.sourceForDataset = sourceForDataset;
8
+ exports.hasDataSources = hasDataSources;
9
+ exports.resetDataSources = resetDataSources;
10
+ const logger_1 = require("../common/logger");
11
+ const sources = new Map();
12
+ /**
13
+ * Registers (or replaces) a data source.
14
+ *
15
+ * Dataset names are global: two sources cannot both offer `claims`, because an
16
+ * agent names a dataset and nothing else, so a duplicate would be ambiguous at
17
+ * exactly the moment it mattered.
18
+ * @param source The host's data source
19
+ */
20
+ function registerDataSource(source) {
21
+ if (!source?.name) {
22
+ throw new Error('A data source needs a name');
23
+ }
24
+ if (typeof source.execute !== 'function') {
25
+ throw new Error(`Data source "${source.name}" must have an execute function`);
26
+ }
27
+ for (const set of source.datasets || []) {
28
+ const owner = sourceForDataset(set.name);
29
+ if (owner && owner.name !== source.name) {
30
+ throw new Error(`Dataset "${set.name}" is already offered by data source "${owner.name}"`);
31
+ }
32
+ }
33
+ if (sources.has(source.name)) {
34
+ logger_1.logger.warn(`Data source "${source.name}" is already registered; overwriting`);
35
+ }
36
+ sources.set(source.name, source);
37
+ }
38
+ /** Removes a data source. @returns True if one was removed */
39
+ function unregisterDataSource(name) {
40
+ return sources.delete(name);
41
+ }
42
+ /** @returns Every registered source, in registration order */
43
+ function listDataSources() {
44
+ return [...sources.values()];
45
+ }
46
+ /** @returns Every dataset any source offers, flattened as an agent sees them */
47
+ function listDatasets() {
48
+ return listDataSources().flatMap((source) => source.datasets || []);
49
+ }
50
+ /** @returns The source that owns a dataset, or undefined */
51
+ function sourceForDataset(datasetName) {
52
+ return listDataSources().find((source) => (source.datasets || []).some((set) => set.name === datasetName));
53
+ }
54
+ /** @returns Whether any source is registered — the tools say so rather than failing oddly */
55
+ function hasDataSources() {
56
+ return sources.size > 0;
57
+ }
58
+ /** Test seam. */
59
+ function resetDataSources() {
60
+ sources.clear();
61
+ }