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.
- 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 +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.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
package/README.md
CHANGED
|
@@ -180,6 +180,10 @@ interface BriyahConfigOptions {
|
|
|
180
180
|
- `BRIYAH_DATA_PATH` - Global default data path (overridden by constructor `dataPath`)
|
|
181
181
|
- `USER_SERVICE_CACHE_TIMEOUT_MINUTES` - Cache timeout (overridden by constructor option)
|
|
182
182
|
- `ALLOW_USER_AUTHORED_TOOLS` - `"true"` to let users author/run their own tools (overridden by the `allowUserAuthoredTools` option). Default off.
|
|
183
|
+
- `EMBEDDING_MODEL` - Model for `embedTexts`, default `text-embedding-3-small` (see Example 13)
|
|
184
|
+
- `EMBEDDING_DIMENSIONS` - Vector length, default `1536`. Change only together with your database column
|
|
185
|
+
- `DOCUMENT_LOAD_CONFIRM_CHARS` - A document larger than this must be confirmed before `load_document` holds it, default `60000`
|
|
186
|
+
- `DOCUMENT_LOAD_MAX_CHARS` - The most library text one agent may hold at once, default `400000`
|
|
183
187
|
|
|
184
188
|
**Retired:**
|
|
185
189
|
- `BRIYAH_TOOL_PACKS` - Read in 1.5 to choose which tool packs to register. It is not read in
|
|
@@ -1229,6 +1233,107 @@ where `agents[].controlledByHuman` identifies the person's character. Then
|
|
|
1229
1233
|
`ensureRoomStateCallback(roomId)` before subscribing — without it the emitter on a resumed room
|
|
1230
1234
|
never fires.
|
|
1231
1235
|
|
|
1236
|
+
### Example 12: Letting an agent query your data
|
|
1237
|
+
|
|
1238
|
+
Declare what may be asked about, supply one function that runs a query, and grant the core
|
|
1239
|
+
`query_data` / `describe_data` tools. There is no query language for the model to write and no
|
|
1240
|
+
tool to implement: the agent describes a question as JSON, and Briyah checks every dataset, field,
|
|
1241
|
+
operator and aggregate in it against your declarations **before your executor sees it**. Your
|
|
1242
|
+
executor therefore builds its statement only from names you chose. A refusal names the valid
|
|
1243
|
+
choices, so the agent corrects itself instead of guessing again.
|
|
1244
|
+
|
|
1245
|
+
```typescript
|
|
1246
|
+
import { registerDataSource, buildDataGuideMarkdown, DataSet } from 'briyah';
|
|
1247
|
+
|
|
1248
|
+
const datasets: DataSet[] = [{
|
|
1249
|
+
name: 'claims',
|
|
1250
|
+
description: 'One row per claim.',
|
|
1251
|
+
notes: ['Losses cannot be broken down by vehicle — say so rather than approximating.'],
|
|
1252
|
+
fields: [
|
|
1253
|
+
{ name: 'customer', type: 'string', aggregates: ['count'] },
|
|
1254
|
+
{ name: 'dateOfLoss', type: 'date' },
|
|
1255
|
+
{ name: 'incurred', type: 'number', filterable: false, aggregates: ['sum', 'avg', 'max'] },
|
|
1256
|
+
],
|
|
1257
|
+
}];
|
|
1258
|
+
|
|
1259
|
+
registerDataSource({
|
|
1260
|
+
name: 'crm',
|
|
1261
|
+
description: 'Customer records.',
|
|
1262
|
+
datasets,
|
|
1263
|
+
execute: async (query, context) => {
|
|
1264
|
+
const { tenant } = context as { tenant: string }; // scope from context, never from the model
|
|
1265
|
+
return { rows: await myDb.run(tenant, query) }; // query is already validated
|
|
1266
|
+
},
|
|
1267
|
+
});
|
|
1268
|
+
|
|
1269
|
+
analyst.toolNames = ['query_data', 'describe_data'];
|
|
1270
|
+
// The schema, rendered for the agent's cached prefix, so it can write a correct query first time.
|
|
1271
|
+
await app.attachDocument(analyst.id, 'data-guide.md', Buffer.from(buildDataGuideMarkdown()));
|
|
1272
|
+
```
|
|
1273
|
+
|
|
1274
|
+
Put what a result silently excludes, and which of two plausible definitions a metric uses, in
|
|
1275
|
+
`notes`: they are rendered into the guide verbatim, and an answer that ignores them is wrong in a
|
|
1276
|
+
way nobody notices.
|
|
1277
|
+
|
|
1278
|
+
### Example 13: A searchable document library
|
|
1279
|
+
|
|
1280
|
+
Register a `DocumentSource` that can list, search, read and return your documents, and five core
|
|
1281
|
+
tools become usable: `list_documents`, `find_in_documents`, `read_document`, `load_document` and
|
|
1282
|
+
`unload_document`. Briyah does the scope checking, refusals, result budgets and pagination; you
|
|
1283
|
+
own storage, tenancy and search.
|
|
1284
|
+
|
|
1285
|
+
```typescript
|
|
1286
|
+
import {
|
|
1287
|
+
registerDocumentSource, buildDocumentGuideMarkdown,
|
|
1288
|
+
chunkPages, embeddingInput, EMBEDDING_DIMENSIONS,
|
|
1289
|
+
} from 'briyah';
|
|
1290
|
+
|
|
1291
|
+
// Ingest: any upload → pages → chunks → vectors. PDF, Word (.docx), Excel (.xlsx) and text all
|
|
1292
|
+
// come back in one shape; anything else throws UnsupportedDocumentError with a message written
|
|
1293
|
+
// for the person who uploaded it.
|
|
1294
|
+
const doc = await app.convertDocumentToMarkdown(fileBytes, 'contract.docx');
|
|
1295
|
+
const chunks = chunkPages(doc.pages); // one page each, headings attached
|
|
1296
|
+
const { vectors } = await app.embedTexts(chunks.map((c) => embeddingInput(c, 'Acme MSA')));
|
|
1297
|
+
await myDb.saveChunks(documentId, chunks, vectors); // your column: vector(EMBEDDING_DIMENSIONS)
|
|
1298
|
+
|
|
1299
|
+
registerDocumentSource({
|
|
1300
|
+
name: 'contracts',
|
|
1301
|
+
description: 'Contracts the customer has uploaded.',
|
|
1302
|
+
list: (context) => myDb.listDocuments(context),
|
|
1303
|
+
search: (context, { query, documentIds, limit }) => myDb.search(context, query, documentIds, limit),
|
|
1304
|
+
read: (context, documentId, { from, to }) => myDb.pages(context, documentId, from, to),
|
|
1305
|
+
fullText: (context, documentId) => myDb.text(context, documentId),
|
|
1306
|
+
});
|
|
1307
|
+
|
|
1308
|
+
assistant.toolNames = ['list_documents', 'find_in_documents', 'read_document', 'load_document', 'unload_document'];
|
|
1309
|
+
await app.attachDocument(assistant.id, 'working-with-documents.md', Buffer.from(buildDocumentGuideMarkdown()));
|
|
1310
|
+
```
|
|
1311
|
+
|
|
1312
|
+
**Scope.** A document id the agent supplies is used only after Briyah finds it in what your
|
|
1313
|
+
`list` returned for this call's context. Your `search`, `read` and `fullText` never see an id the
|
|
1314
|
+
context cannot.
|
|
1315
|
+
|
|
1316
|
+
**Looking up versus holding.** `find_in_documents` and `read_document` put only what the agent
|
|
1317
|
+
read into its history. `load_document` holds a whole document in the agent's context, where it
|
|
1318
|
+
rides every request until `unload_document` — the right tool for "review this contract" or
|
|
1319
|
+
"compare these two", and the wrong one for looking something up. Past
|
|
1320
|
+
`DOCUMENT_LOAD_CONFIRM_CHARS` the agent must confirm, and is told the cost; past
|
|
1321
|
+
`DOCUMENT_LOAD_MAX_CHARS` in total it is refused and told to read in pages.
|
|
1322
|
+
|
|
1323
|
+
**Resetting a conversation.** `resetRoom` releases the library documents agents are holding, so a
|
|
1324
|
+
new conversation starts clean, and keeps the documents their own configuration attached. Pass
|
|
1325
|
+
`{ keepHeldDocuments: true }` to keep both. `app.releaseLibraryDocuments(agentId)` lets go of them
|
|
1326
|
+
without a reset, and `isLibraryAttachment(fileName)` tells the two kinds apart.
|
|
1327
|
+
|
|
1328
|
+
**Artifacts.** `resetRoom(roomId, { keepArtifacts: true })` keeps what agents wrote. The default
|
|
1329
|
+
still deletes them. Every artifact now carries `createdAt` and `updatedAt`.
|
|
1330
|
+
|
|
1331
|
+
**Embedding.** Anthropic publishes no embeddings endpoint, so `embedTexts` defaults to OpenAI's
|
|
1332
|
+
`text-embedding-3-small` with `OPENAI_API_KEY`. Pass an `EmbeddingProvider` to use another.
|
|
1333
|
+
`app.embedTexts` charges the cost to the user's balance; the module-level `embedTexts` does not,
|
|
1334
|
+
for a host keeping its own accounting. The vector length has to match your column, so declare
|
|
1335
|
+
the column from `EMBEDDING_DIMENSIONS` and change the model and the column together.
|
|
1336
|
+
|
|
1232
1337
|
## Data Storage
|
|
1233
1338
|
|
|
1234
1339
|
Briyah stores data in the following structure:
|
|
@@ -2,5 +2,11 @@
|
|
|
2
2
|
"pack": "dnd5e",
|
|
3
3
|
"title": "D&D 5th Edition",
|
|
4
4
|
"description": "Run a fifth-edition tabletop game in a room: dice, character sheets, the rules engine and the bestiary, with prompt folders for a Dungeon Master, a Battle Master, players and two specialists. A game is an ordinary room assembled from these pieces — build one from a room template here, or let the RPG page do it for you.",
|
|
5
|
-
"version": "1.0.0"
|
|
5
|
+
"version": "1.0.0",
|
|
6
|
+
"table": {
|
|
7
|
+
"room": "campaign",
|
|
8
|
+
"playerAgent": "player",
|
|
9
|
+
"playerNoun": "Player",
|
|
10
|
+
"maxPlayers": 6
|
|
11
|
+
}
|
|
6
12
|
}
|
|
@@ -216,6 +216,33 @@ export declare class Agent {
|
|
|
216
216
|
pinHistory(): void;
|
|
217
217
|
/** How many trailing messages the pin protects from trimming. */
|
|
218
218
|
private pinnedMessageCount;
|
|
219
|
+
/**
|
|
220
|
+
* How many messages at the head of history are framing rather than conversation.
|
|
221
|
+
*
|
|
222
|
+
* The developer instructions an agent was built with, and the summary a
|
|
223
|
+
* compaction leaves in their place. Both are the ground the rest of the
|
|
224
|
+
* conversation was written against, so every path that removes messages — the
|
|
225
|
+
* rolling window and {@link deleteLastMessage} — treats this as its floor.
|
|
226
|
+
*
|
|
227
|
+
* Content is read defensively because a history entry's shape is the provider's:
|
|
228
|
+
* most write `content`, Google AI writes `parts`.
|
|
229
|
+
*/
|
|
230
|
+
private systemMessageCount;
|
|
231
|
+
/**
|
|
232
|
+
* Drops the newest message from history.
|
|
233
|
+
*
|
|
234
|
+
* From the end only, which is what makes it safe to call repeatedly: the head of
|
|
235
|
+
* history is untouched, so a provider that requires the conversation to open on a
|
|
236
|
+
* user message still gets one. It can leave two messages of the same role
|
|
237
|
+
* adjacent, which the APIs accept and fold into a single turn.
|
|
238
|
+
*
|
|
239
|
+
* The caller decides what a message is worth — nothing here asks whether the
|
|
240
|
+
* message being removed is an agent's answer or the prompt that drew it, because
|
|
241
|
+
* a person undoing a turn wants both gone and clicks twice.
|
|
242
|
+
*
|
|
243
|
+
* @returns True when a message was removed, false when only framing was left
|
|
244
|
+
*/
|
|
245
|
+
deleteLastMessage(): boolean;
|
|
219
246
|
/**
|
|
220
247
|
* Trims conversation history to keep only the last N messages if maxHistoryMessages is set
|
|
221
248
|
* Preserves system messages (role: 'developer') at the start of history
|
|
@@ -333,6 +333,59 @@ class Agent {
|
|
|
333
333
|
}
|
|
334
334
|
return this.history.length - this.historyPin;
|
|
335
335
|
}
|
|
336
|
+
/**
|
|
337
|
+
* How many messages at the head of history are framing rather than conversation.
|
|
338
|
+
*
|
|
339
|
+
* The developer instructions an agent was built with, and the summary a
|
|
340
|
+
* compaction leaves in their place. Both are the ground the rest of the
|
|
341
|
+
* conversation was written against, so every path that removes messages — the
|
|
342
|
+
* rolling window and {@link deleteLastMessage} — treats this as its floor.
|
|
343
|
+
*
|
|
344
|
+
* Content is read defensively because a history entry's shape is the provider's:
|
|
345
|
+
* most write `content`, Google AI writes `parts`.
|
|
346
|
+
*/
|
|
347
|
+
systemMessageCount() {
|
|
348
|
+
let count = 0;
|
|
349
|
+
for (const message of this.history) {
|
|
350
|
+
const isSummary = typeof message?.content === 'string' &&
|
|
351
|
+
message.content.includes('[CONVERSATION HISTORY SUMMARY]');
|
|
352
|
+
if (message?.role === 'developer' || isSummary) {
|
|
353
|
+
count++;
|
|
354
|
+
}
|
|
355
|
+
else {
|
|
356
|
+
break;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
return count;
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Drops the newest message from history.
|
|
363
|
+
*
|
|
364
|
+
* From the end only, which is what makes it safe to call repeatedly: the head of
|
|
365
|
+
* history is untouched, so a provider that requires the conversation to open on a
|
|
366
|
+
* user message still gets one. It can leave two messages of the same role
|
|
367
|
+
* adjacent, which the APIs accept and fold into a single turn.
|
|
368
|
+
*
|
|
369
|
+
* The caller decides what a message is worth — nothing here asks whether the
|
|
370
|
+
* message being removed is an agent's answer or the prompt that drew it, because
|
|
371
|
+
* a person undoing a turn wants both gone and clicks twice.
|
|
372
|
+
*
|
|
373
|
+
* @returns True when a message was removed, false when only framing was left
|
|
374
|
+
*/
|
|
375
|
+
deleteLastMessage() {
|
|
376
|
+
if (this.history.length <= this.systemMessageCount()) {
|
|
377
|
+
return false;
|
|
378
|
+
}
|
|
379
|
+
this.history.pop();
|
|
380
|
+
// The pin is an index into history, and history just got shorter. Clamped
|
|
381
|
+
// rather than left alone: pinnedMessageCount drops a pin past the end
|
|
382
|
+
// outright, which would quietly stop protecting a task still running.
|
|
383
|
+
if (this.historyPin !== undefined) {
|
|
384
|
+
this.historyPin = Math.min(this.historyPin, this.history.length);
|
|
385
|
+
}
|
|
386
|
+
this.save();
|
|
387
|
+
return true;
|
|
388
|
+
}
|
|
336
389
|
/**
|
|
337
390
|
* Trims conversation history to keep only the last N messages if maxHistoryMessages is set
|
|
338
391
|
* Preserves system messages (role: 'developer') at the start of history
|
|
@@ -346,19 +399,7 @@ class Agent {
|
|
|
346
399
|
trimHistoryIfNeeded(threshold = 0) {
|
|
347
400
|
if (!this.maxHistoryMessages)
|
|
348
401
|
return;
|
|
349
|
-
|
|
350
|
-
let systemMessageCount = 0;
|
|
351
|
-
for (let i = 0; i < this.history.length; i++) {
|
|
352
|
-
if (this.history[i].role === 'developer') {
|
|
353
|
-
systemMessageCount++;
|
|
354
|
-
}
|
|
355
|
-
else if (this.history[i].content.includes('[CONVERSATION HISTORY SUMMARY]')) {
|
|
356
|
-
systemMessageCount++;
|
|
357
|
-
}
|
|
358
|
-
else {
|
|
359
|
-
break;
|
|
360
|
-
}
|
|
361
|
-
}
|
|
402
|
+
const systemMessageCount = this.systemMessageCount();
|
|
362
403
|
// Keep system messages + last N conversation messages, or everything since
|
|
363
404
|
// the pin when the task in flight is longer than the window.
|
|
364
405
|
const keep = Math.max(this.maxHistoryMessages, this.pinnedMessageCount());
|
|
@@ -124,6 +124,9 @@ let UserServiceFactory = class UserServiceFactory {
|
|
|
124
124
|
const storyService = new story_service_1.StoryService(storyStore, agentStore, roomStore, this.storyProgressService, this.storyMessageService, userPaths, agentFactory, roomFactory, illustration);
|
|
125
125
|
// 10. Create AppService with all dependencies
|
|
126
126
|
const appService = new app_service_1.AppService(this.aiFactoryService, agentStore, this.agentMessageService, roomStore, this.roomMessageService, userPaths, attachedFileService, artifactService, storyStore, storyService, this.publishedAgentsService, this.publishedRoomsService, balanceService, this.balanceMessageService, transactionService, agentFactory, roomFactory, toolStore, toolExecution, packService, illustration);
|
|
127
|
+
// `helpers.documents` attaches through the AppService, which does not exist
|
|
128
|
+
// until now — so the tool execution service is handed its store late.
|
|
129
|
+
toolExecution.setAgentDocumentStore(appService.agentDocumentStore());
|
|
127
130
|
// Built after the AppService it drives, and handed back through it, because
|
|
128
131
|
// instantiating a pack's room goes through the same createRoom and
|
|
129
132
|
// createRoomAgent paths the API uses rather than around them.
|
|
@@ -4,7 +4,7 @@ import { Observable } from 'rxjs';
|
|
|
4
4
|
import { UserServiceManager } from './app/user-service-manager';
|
|
5
5
|
import { PublishedAgentsService } from './ai/published-agents.service';
|
|
6
6
|
import { PublishedRoomsService } from './room/published-rooms.service';
|
|
7
|
-
import { AgentInfo, CreateAgentRequest, CreateAgentResponse, CreateRoomAgentRequest, UpdateAgentRequest, RoomInfo, RoomDetails, CreateRoomResponse, SendMessageResult, AgentMessagesResponse, RoomMessagesResponse, FileList, PromptFileContent, PromptFoldersResponse, PromptFilesResponse, PromptFolderDefaultsResponse, PromptScope, CreatePromptFolderRequest, CreatePromptFileRequest, UpdatePromptFileRequest, ProcessTextResponse, PreparedPromptResponse, AttachDocumentResponse, StoryInfo, StoryState, Character, ModelInfo, ImageModelOption, StoryModelDefaults, ChapterInfo, StoryIdea, ToolDefinition, ToolsResponse, ToolRunResult, ToolTestRequest, PackSummary, PacksResponse, PackDetails, SetPackEnabledRequest, CreatePackRequest, InstantiatePackRoomRequest, InstantiatePackRoomResponse, InstantiatePackAgentRequest, InstantiatePackAgentResponse, RpgModelOption, RpgCampaignInfo, RpgCampaignDetails, CreateRpgCampaignRequest, CreateRpgCampaignResponse } from '../../shared/types/app.types';
|
|
7
|
+
import { AgentInfo, CreateAgentRequest, CreateAgentResponse, CreateRoomAgentRequest, UpdateAgentRequest, RoomInfo, RoomDetails, CreateRoomResponse, SendMessageResult, AgentMessagesResponse, RoomMessagesResponse, FileList, PromptFileContent, PromptFoldersResponse, PromptFilesResponse, PromptFolderDefaultsResponse, PromptScope, CreatePromptFolderRequest, CreatePromptFileRequest, UpdatePromptFileRequest, ProcessTextResponse, PreparedPromptResponse, AttachDocumentResponse, StoryInfo, StoryState, Character, ModelInfo, ImageModelOption, StoryModelDefaults, ChapterInfo, StoryIdea, ToolDefinition, ToolsResponse, ToolRunResult, ToolTestRequest, PackSummary, PacksResponse, PackDetails, SetPackEnabledRequest, CreatePackRequest, InstantiatePackRoomRequest, InstantiatePackRoomResponse, InstantiatePackAgentRequest, InstantiatePackAgentResponse, RpgModelOption, RpgPackOption, RpgCampaignInfo, RpgCampaignDetails, CreateRpgCampaignRequest, CreateRpgCampaignResponse } from '../../shared/types/app.types';
|
|
8
8
|
import { RoomMessage } from './room/message';
|
|
9
9
|
export declare class AppController {
|
|
10
10
|
private readonly userServiceManager;
|
|
@@ -53,6 +53,7 @@ export declare class AppController {
|
|
|
53
53
|
deletePack(req: ExpressRequest, packName: string): void;
|
|
54
54
|
instantiatePackRoom(req: ExpressRequest, packName: string, roomKey: string, body: InstantiatePackRoomRequest): Promise<InstantiatePackRoomResponse>;
|
|
55
55
|
instantiatePackAgent(req: ExpressRequest, packName: string, agentKey: string, body: InstantiatePackAgentRequest): Promise<InstantiatePackAgentResponse>;
|
|
56
|
+
listRpgPacks(req: ExpressRequest): RpgPackOption[];
|
|
56
57
|
listRpgModels(req: ExpressRequest): RpgModelOption[];
|
|
57
58
|
listRpgCampaigns(req: ExpressRequest): Promise<RpgCampaignInfo[]>;
|
|
58
59
|
getRpgCampaign(req: ExpressRequest, campaignId: string): Promise<RpgCampaignDetails>;
|
|
@@ -190,6 +191,11 @@ export declare class AppController {
|
|
|
190
191
|
updateAgent(req: ExpressRequest, agentId: string, updateData: UpdateAgentRequest): Promise<void>;
|
|
191
192
|
deleteAttachedFile(req: ExpressRequest, agentId: string, documentId: string): Promise<void>;
|
|
192
193
|
reloadAgent(req: ExpressRequest, agentId: string): Promise<void>;
|
|
194
|
+
/**
|
|
195
|
+
* Removes the newest message from an agent's conversation, so a person can undo a
|
|
196
|
+
* turn — or several, a click at a time — instead of resetting the whole thing.
|
|
197
|
+
*/
|
|
198
|
+
deleteLastAgentMessage(req: ExpressRequest, agentId: string): Promise<AgentMessagesResponse>;
|
|
193
199
|
compactAgentConversation(req: ExpressRequest, agentId: string): Promise<void>;
|
|
194
200
|
resetRoom(req: ExpressRequest, roomId: string): Promise<void>;
|
|
195
201
|
publishRoom(req: ExpressRequest, templateId: string, body: {
|
|
@@ -687,6 +687,15 @@ let AppController = AppController_1 = class AppController {
|
|
|
687
687
|
// A campaign is an ordinary room, so everything but creating and reading one goes
|
|
688
688
|
// through the room routes: DELETE rooms/:roomId removes a campaign and cascades to
|
|
689
689
|
// its published instance, and the party plays through the published-room routes.
|
|
690
|
+
listRpgPacks(req) {
|
|
691
|
+
try {
|
|
692
|
+
return this.getAppService(req).rpg.listPacks();
|
|
693
|
+
}
|
|
694
|
+
catch (error) {
|
|
695
|
+
logger_1.logger.error(`[${req.user?.sub}] Error listing RPG packs:`, error);
|
|
696
|
+
return [];
|
|
697
|
+
}
|
|
698
|
+
}
|
|
690
699
|
listRpgModels(req) {
|
|
691
700
|
try {
|
|
692
701
|
return this.getAppService(req).rpg.listModels();
|
|
@@ -1414,6 +1423,35 @@ let AppController = AppController_1 = class AppController {
|
|
|
1414
1423
|
throw new common_1.HttpException('Failed to reload agent', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
|
|
1415
1424
|
}
|
|
1416
1425
|
}
|
|
1426
|
+
/**
|
|
1427
|
+
* Removes the newest message from an agent's conversation, so a person can undo a
|
|
1428
|
+
* turn — or several, a click at a time — instead of resetting the whole thing.
|
|
1429
|
+
*/
|
|
1430
|
+
async deleteLastAgentMessage(req, agentId) {
|
|
1431
|
+
if (!agentId) {
|
|
1432
|
+
throw new common_1.BadRequestException('Agent ID is required');
|
|
1433
|
+
}
|
|
1434
|
+
try {
|
|
1435
|
+
const appService = this.getAppService(req, agentId);
|
|
1436
|
+
if (req.user.type === 'agent-access') {
|
|
1437
|
+
const agentDetails = await appService.getAgentDetails(agentId);
|
|
1438
|
+
if (!agentDetails || !agentDetails.isPublished) {
|
|
1439
|
+
throw new common_1.ForbiddenException('Agent is not published');
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
return await appService.deleteLastAgentMessage(agentId);
|
|
1443
|
+
}
|
|
1444
|
+
catch (error) {
|
|
1445
|
+
if (error instanceof common_1.ForbiddenException) {
|
|
1446
|
+
throw error;
|
|
1447
|
+
}
|
|
1448
|
+
if (error instanceof errors_1.NotFoundError) {
|
|
1449
|
+
throw new common_1.NotFoundException(error.message);
|
|
1450
|
+
}
|
|
1451
|
+
logger_1.logger.error(`[${req.user?.sub}] Error deleting the last message for ${agentId}:`, error);
|
|
1452
|
+
throw new common_1.HttpException(error.message || 'Failed to delete the last message', common_1.HttpStatus.INTERNAL_SERVER_ERROR);
|
|
1453
|
+
}
|
|
1454
|
+
}
|
|
1417
1455
|
async compactAgentConversation(req, agentId) {
|
|
1418
1456
|
if (!agentId) {
|
|
1419
1457
|
throw new common_1.BadRequestException('Agent ID is required');
|
|
@@ -2804,6 +2842,14 @@ __decorate([
|
|
|
2804
2842
|
__metadata("design:paramtypes", [Object, String, String, Object]),
|
|
2805
2843
|
__metadata("design:returntype", Promise)
|
|
2806
2844
|
], AppController.prototype, "instantiatePackAgent", null);
|
|
2845
|
+
__decorate([
|
|
2846
|
+
(0, owner_only_decorator_1.OwnerOnly)(),
|
|
2847
|
+
(0, common_1.Get)('rpg/packs'),
|
|
2848
|
+
__param(0, (0, common_1.Request)()),
|
|
2849
|
+
__metadata("design:type", Function),
|
|
2850
|
+
__metadata("design:paramtypes", [Object]),
|
|
2851
|
+
__metadata("design:returntype", Array)
|
|
2852
|
+
], AppController.prototype, "listRpgPacks", null);
|
|
2807
2853
|
__decorate([
|
|
2808
2854
|
(0, owner_only_decorator_1.OwnerOnly)(),
|
|
2809
2855
|
(0, common_1.Get)('rpg/models'),
|
|
@@ -3177,6 +3223,15 @@ __decorate([
|
|
|
3177
3223
|
__metadata("design:paramtypes", [Object, String]),
|
|
3178
3224
|
__metadata("design:returntype", Promise)
|
|
3179
3225
|
], AppController.prototype, "reloadAgent", null);
|
|
3226
|
+
__decorate([
|
|
3227
|
+
(0, agent_access_decorator_1.AgentAccess)(),
|
|
3228
|
+
(0, common_1.Delete)('agents/:agentId/messages/last'),
|
|
3229
|
+
__param(0, (0, common_1.Request)()),
|
|
3230
|
+
__param(1, (0, common_1.Param)('agentId')),
|
|
3231
|
+
__metadata("design:type", Function),
|
|
3232
|
+
__metadata("design:paramtypes", [Object, String]),
|
|
3233
|
+
__metadata("design:returntype", Promise)
|
|
3234
|
+
], AppController.prototype, "deleteLastAgentMessage", null);
|
|
3180
3235
|
__decorate([
|
|
3181
3236
|
(0, agent_access_decorator_1.AgentAccess)(),
|
|
3182
3237
|
(0, common_1.Post)('agents/:agentId/compact'),
|
|
@@ -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
|
|
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.
|