briyah 2.0.5 → 2.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +105 -0
- package/data/common/prompts/moderate.json +34 -0
- package/data/common/prompts/moderate.prompt +136 -0
- package/data/packs/dnd5e/pack.json +7 -1
- package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +16 -0
- package/dist-sdk/server/src/ai/LLM/base-ai.service.js +23 -0
- package/dist-sdk/server/src/ai/agent.d.ts +33 -0
- package/dist-sdk/server/src/ai/agent.js +64 -13
- package/dist-sdk/server/src/app/user-service-factory.js +3 -0
- package/dist-sdk/server/src/app.controller.d.ts +7 -1
- package/dist-sdk/server/src/app.controller.js +55 -0
- package/dist-sdk/server/src/app.service.d.ts +114 -2
- package/dist-sdk/server/src/app.service.js +181 -4
- package/dist-sdk/server/src/data/data-guide.builder.d.ts +2 -0
- package/dist-sdk/server/src/data/data-guide.builder.js +90 -0
- package/dist-sdk/server/src/data/data-registry.d.ts +32 -0
- package/dist-sdk/server/src/data/data-registry.js +61 -0
- package/dist-sdk/server/src/data/data.types.d.ts +158 -0
- package/dist-sdk/server/src/data/data.types.js +24 -0
- package/dist-sdk/server/src/data/query-validation.d.ts +45 -0
- package/dist-sdk/server/src/data/query-validation.js +245 -0
- package/dist-sdk/server/src/documents/document-conversion.d.ts +70 -0
- package/dist-sdk/server/src/documents/document-conversion.js +341 -0
- package/dist-sdk/server/src/documents/library/chunking.d.ts +65 -0
- package/dist-sdk/server/src/documents/library/chunking.js +263 -0
- package/dist-sdk/server/src/documents/library/document-guide.builder.d.ts +2 -0
- package/dist-sdk/server/src/documents/library/document-guide.builder.js +58 -0
- package/dist-sdk/server/src/documents/library/document-registry.d.ts +22 -0
- package/dist-sdk/server/src/documents/library/document-registry.js +44 -0
- package/dist-sdk/server/src/documents/library/document.types.d.ts +108 -0
- package/dist-sdk/server/src/documents/library/document.types.js +20 -0
- package/dist-sdk/server/src/documents/library/embedding.d.ts +57 -0
- package/dist-sdk/server/src/documents/library/embedding.js +151 -0
- package/dist-sdk/server/src/packs/pack-manifest.d.ts +46 -0
- package/dist-sdk/server/src/packs/pack-manifest.js +46 -1
- package/dist-sdk/server/src/room/artifact-store.service.js +44 -11
- package/dist-sdk/server/src/room/artifact.d.ts +8 -0
- package/dist-sdk/server/src/room/room.d.ts +7 -5
- package/dist-sdk/server/src/room/room.js +44 -7
- package/dist-sdk/server/src/rpg/rpg-roster.d.ts +70 -29
- package/dist-sdk/server/src/rpg/rpg-roster.js +152 -41
- package/dist-sdk/server/src/rpg/rpg.service.d.ts +66 -29
- package/dist-sdk/server/src/rpg/rpg.service.js +140 -65
- package/dist-sdk/server/src/sdk/index.d.ts +16 -2
- package/dist-sdk/server/src/sdk/index.js +37 -1
- package/dist-sdk/server/src/tools/core/data.tools.d.ts +17 -0
- package/dist-sdk/server/src/tools/core/data.tools.js +165 -0
- package/dist-sdk/server/src/tools/core/document.tools.d.ts +39 -0
- package/dist-sdk/server/src/tools/core/document.tools.js +391 -0
- package/dist-sdk/server/src/tools/core/index.js +3 -1
- package/dist-sdk/server/src/tools/native-tool.types.d.ts +37 -0
- package/dist-sdk/server/src/tools/tool-execution.service.d.ts +23 -2
- package/dist-sdk/server/src/tools/tool-execution.service.js +30 -6
- package/dist-sdk/shared/types/app.types.d.ts +39 -5
- package/package.json +172 -167
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:
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "moderate",
|
|
3
|
+
"description": "Route a message to the agents that should receive and answer it",
|
|
4
|
+
"type": "object",
|
|
5
|
+
"properties": {
|
|
6
|
+
"action": {
|
|
7
|
+
"type": "string",
|
|
8
|
+
"enum": ["relay", "relay_silent"],
|
|
9
|
+
"description": "Use 'relay' to pass the message on and log it in the room transcript. Use 'relay_silent' for an internal handoff that should not appear in the transcript"
|
|
10
|
+
},
|
|
11
|
+
"content": {
|
|
12
|
+
"type": "string",
|
|
13
|
+
"description": "The word 'relay' to pass the message on unchanged, or the rewritten message"
|
|
14
|
+
},
|
|
15
|
+
"name": {
|
|
16
|
+
"type": "string",
|
|
17
|
+
"description": "The name of the one agent expected to answer next, or an empty string when it cannot be determined"
|
|
18
|
+
},
|
|
19
|
+
"targets": {
|
|
20
|
+
"type": "array",
|
|
21
|
+
"description": "The names of every agent that should receive the message",
|
|
22
|
+
"items": {
|
|
23
|
+
"type": "string"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"relayAs": {
|
|
27
|
+
"type": "string",
|
|
28
|
+
"enum": ["speak", "whisper", "shout"],
|
|
29
|
+
"description": "The action the relayed message carries in the room. Use 'whisper' when the targets are only some of the agents present, 'speak' when everyone present is a target, and 'shout' only when the message must reach the whole room."
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"required": ["action", "content", "name", "targets", "relayAs"],
|
|
33
|
+
"additionalProperties": false
|
|
34
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
# Moderator instructions
|
|
2
|
+
|
|
3
|
+
## Your Identity
|
|
4
|
+
- **Your Name**: {{agentNickname}}
|
|
5
|
+
- **Full Title**: {{agentName}}
|
|
6
|
+
- **Description**: {{agentDescription}}
|
|
7
|
+
|
|
8
|
+
Besides your own role, you are placing a message that this room could not route
|
|
9
|
+
on its own. Decide who should receive it and who should answer it.
|
|
10
|
+
|
|
11
|
+
## Room Context
|
|
12
|
+
|
|
13
|
+
### Goal
|
|
14
|
+
{{roomGoal}}
|
|
15
|
+
|
|
16
|
+
### Available Agents
|
|
17
|
+
{{#each otherAgents}}
|
|
18
|
+
- {{this.agentNickname}}: {{this.description}}
|
|
19
|
+
{{/each}}
|
|
20
|
+
|
|
21
|
+
### Room Leader
|
|
22
|
+
{{roomLeader}}
|
|
23
|
+
|
|
24
|
+
{{#if humanAgentList}}
|
|
25
|
+
### People
|
|
26
|
+
{{humanAgentList}}
|
|
27
|
+
|
|
28
|
+
These are human participants. Name one as the responder only when the message
|
|
29
|
+
genuinely needs a person — an answer only they have, or a decision only they can
|
|
30
|
+
make. A person cannot be prompted, so the room waits until they type.
|
|
31
|
+
{{/if}}
|
|
32
|
+
|
|
33
|
+
## Your Task
|
|
34
|
+
Read the Sender and the Recent Message below, then decide:
|
|
35
|
+
1. Which agents should receive the message.
|
|
36
|
+
2. Which single agent should answer it next.
|
|
37
|
+
|
|
38
|
+
Work from what each agent's description says it does. The usual reason a message
|
|
39
|
+
reaches you is that its sender addressed a name that is not in the Available
|
|
40
|
+
Agents list — a colleague it assumed was here, or a role it invented. When that
|
|
41
|
+
happens, do not guess at a near match: hand the message to the room leader, who
|
|
42
|
+
can answer it or redirect the sender.
|
|
43
|
+
|
|
44
|
+
## How to respond
|
|
45
|
+
1. **action**: "relay" to log the message in the room's transcript, or
|
|
46
|
+
"relay_silent" to pass it along without logging. Prefer "relay" — the
|
|
47
|
+
transcript is what a person reads to follow the room. Use "relay_silent" for
|
|
48
|
+
internal handoffs a reader would find noise, such as a request routed to a
|
|
49
|
+
specialist whose own reply will be the visible answer.
|
|
50
|
+
2. **content**: The literal word "relay" to pass the message on unchanged, which
|
|
51
|
+
is almost always right. Only write something else to genuinely rewrite it.
|
|
52
|
+
3. **name**: The one agent expected to answer next. It must be a name from the
|
|
53
|
+
Available Agents list. Leave it empty ("") when you cannot tell, and the room
|
|
54
|
+
leader will take the turn.
|
|
55
|
+
4. **targets**: Every agent that should receive the message, including the one
|
|
56
|
+
named in "name". Include the room leader ({{roomLeader}}) whenever they are
|
|
57
|
+
not the sender, unless you are deliberately keeping this exchange private —
|
|
58
|
+
the leader directs what happens next and can only do that from what it has
|
|
59
|
+
been told. Do not include a name that is not in the Available Agents list.
|
|
60
|
+
5. **relayAs**: The action the message carries in the room.
|
|
61
|
+
- "whisper" when the targets are only some of the agents present.
|
|
62
|
+
- "speak" when every agent present is a target.
|
|
63
|
+
- "shout" only when the message must reach the whole room regardless.
|
|
64
|
+
Getting this wrong misreports the conversation: a "speak" that only two of
|
|
65
|
+
six agents heard is logged as though the whole room heard it.
|
|
66
|
+
|
|
67
|
+
## Response Format
|
|
68
|
+
Respond with a valid JSON object and nothing else:
|
|
69
|
+
{
|
|
70
|
+
"action": "relay",
|
|
71
|
+
"content": "relay",
|
|
72
|
+
"name": "AgentName",
|
|
73
|
+
"targets": ["AgentName", "AnotherAgent"],
|
|
74
|
+
"relayAs": "speak"
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
## Rules
|
|
78
|
+
- Never name the sender as the responder. An agent asked to answer its own
|
|
79
|
+
message talks to itself and the room stalls.
|
|
80
|
+
- Route a request for an action to the one agent whose description covers that
|
|
81
|
+
action, rather than to everyone who might have an opinion about it.
|
|
82
|
+
- Leave out any agent that would not realistically be aware of the message. An
|
|
83
|
+
agent that hears everything cannot hold anything in confidence.
|
|
84
|
+
- When no agent is a good fit, name the room leader rather than picking one at
|
|
85
|
+
random. A wrong specialist answers confidently from the wrong role.
|
|
86
|
+
|
|
87
|
+
## Examples
|
|
88
|
+
|
|
89
|
+
Assume these Available Agents: Analyst (answers questions about the data),
|
|
90
|
+
Navigator (finds pages and explains where things are), and a room leader named
|
|
91
|
+
Lisa.
|
|
92
|
+
|
|
93
|
+
### Example 1: A request only one agent can serve
|
|
94
|
+
Sender: Lisa
|
|
95
|
+
Recent Message: How many drivers were active last month?
|
|
96
|
+
Correct response:
|
|
97
|
+
{
|
|
98
|
+
"action": "relay",
|
|
99
|
+
"content": "relay",
|
|
100
|
+
"name": "Analyst",
|
|
101
|
+
"targets": ["Analyst", "Lisa"],
|
|
102
|
+
"relayAs": "speak"
|
|
103
|
+
}
|
|
104
|
+
- The description of Analyst covers questions about the data.
|
|
105
|
+
- Lisa is the room leader and is the sender, so she is in the targets as the
|
|
106
|
+
agent directing the work.
|
|
107
|
+
|
|
108
|
+
### Example 2: The sender addressed somebody who is not here
|
|
109
|
+
Sender: Lisa
|
|
110
|
+
Recent Message: Reporter, can you put together a summary of last quarter?
|
|
111
|
+
Correct response:
|
|
112
|
+
{
|
|
113
|
+
"action": "relay",
|
|
114
|
+
"content": "relay",
|
|
115
|
+
"name": "",
|
|
116
|
+
"targets": [],
|
|
117
|
+
"relayAs": "whisper"
|
|
118
|
+
}
|
|
119
|
+
- There is no agent named Reporter in the Available Agents list.
|
|
120
|
+
- Leave "name" empty and the targets empty. The message goes to the room leader,
|
|
121
|
+
who can answer it or tell the sender that no such agent is here.
|
|
122
|
+
|
|
123
|
+
### Example 3: Information the whole room should have
|
|
124
|
+
Sender: Analyst
|
|
125
|
+
Recent Message: The figures for last month are final now.
|
|
126
|
+
Correct response:
|
|
127
|
+
{
|
|
128
|
+
"action": "relay",
|
|
129
|
+
"content": "relay",
|
|
130
|
+
"name": "Lisa",
|
|
131
|
+
"targets": ["Lisa", "Navigator"],
|
|
132
|
+
"relayAs": "speak"
|
|
133
|
+
}
|
|
134
|
+
- This is information rather than a request, so everyone present is a target.
|
|
135
|
+
- Nobody was addressed, so the room leader takes the turn and decides what
|
|
136
|
+
happens next.
|
|
@@ -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
|
}
|
|
@@ -63,6 +63,22 @@ export declare class BaseAiService {
|
|
|
63
63
|
* @param extension The file extension, defaulting to `.prompt`
|
|
64
64
|
*/
|
|
65
65
|
hasPromptFile(agent: Agent, fileName: string, extension?: string): boolean;
|
|
66
|
+
/**
|
|
67
|
+
* Whether the agent's own prompt folder supplies this file, rather than the
|
|
68
|
+
* shared roots every lookup ends at.
|
|
69
|
+
*
|
|
70
|
+
* {@link hasPromptFile} answers "could this agent run that turn", which a
|
|
71
|
+
* shared fallback makes true for everybody. This answers the narrower "was
|
|
72
|
+
* this folder written to run that turn", which is what picking between
|
|
73
|
+
* agents needs: with `moderate.prompt` in `common/prompts/` any agent can
|
|
74
|
+
* moderate, so preferring one that actually set out to is the only way a
|
|
75
|
+
* purpose-built moderator still wins.
|
|
76
|
+
*
|
|
77
|
+
* @param agent The agent whose prompt folder is searched
|
|
78
|
+
* @param fileName The prompt file name without extension
|
|
79
|
+
* @param extension The file extension, defaulting to `.prompt`
|
|
80
|
+
*/
|
|
81
|
+
hasOwnPromptFile(agent: Agent, fileName: string, extension?: string): boolean;
|
|
66
82
|
getPreparedPrompt(agent: Agent, promptFileName: string, variables: any): string;
|
|
67
83
|
/**
|
|
68
84
|
* The agent's system instruction, resolved from its prompt folder per call.
|
|
@@ -143,6 +143,29 @@ let BaseAiService = class BaseAiService {
|
|
|
143
143
|
hasPromptFile(agent, fileName, extension = '.prompt') {
|
|
144
144
|
return this.findPromptFile(agent, fileName, extension) !== null;
|
|
145
145
|
}
|
|
146
|
+
/**
|
|
147
|
+
* Whether the agent's own prompt folder supplies this file, rather than the
|
|
148
|
+
* shared roots every lookup ends at.
|
|
149
|
+
*
|
|
150
|
+
* {@link hasPromptFile} answers "could this agent run that turn", which a
|
|
151
|
+
* shared fallback makes true for everybody. This answers the narrower "was
|
|
152
|
+
* this folder written to run that turn", which is what picking between
|
|
153
|
+
* agents needs: with `moderate.prompt` in `common/prompts/` any agent can
|
|
154
|
+
* moderate, so preferring one that actually set out to is the only way a
|
|
155
|
+
* purpose-built moderator still wins.
|
|
156
|
+
*
|
|
157
|
+
* @param agent The agent whose prompt folder is searched
|
|
158
|
+
* @param fileName The prompt file name without extension
|
|
159
|
+
* @param extension The file extension, defaulting to `.prompt`
|
|
160
|
+
*/
|
|
161
|
+
hasOwnPromptFile(agent, fileName, extension = '.prompt') {
|
|
162
|
+
const userPaths = agent.userPaths;
|
|
163
|
+
if (!userPaths)
|
|
164
|
+
return false;
|
|
165
|
+
return ((0, prompt_resolver_1.resolvePromptFile)(userPaths, agent.promptFolder, fileName, extension, {
|
|
166
|
+
enabledPacks: agent.enabledPacks,
|
|
167
|
+
})?.folderScoped === true);
|
|
168
|
+
}
|
|
146
169
|
getPreparedPrompt(agent, promptFileName, variables) {
|
|
147
170
|
// Use 4-level fallback to find the prompt file
|
|
148
171
|
const preparedFile = this.findPromptFile(agent, promptFileName, '.prompt');
|
|
@@ -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
|
|
@@ -235,6 +262,12 @@ export declare class Agent {
|
|
|
235
262
|
* this agent run that turn" is then no, which is what a caller wants to hear.
|
|
236
263
|
*/
|
|
237
264
|
hasPrompt(name: string): boolean;
|
|
265
|
+
/**
|
|
266
|
+
* Whether this agent's own prompt folder supplies `<name>.prompt`, rather
|
|
267
|
+
* than inheriting it from the shared roots. See
|
|
268
|
+
* {@link BaseAiService.hasOwnPromptFile} for why both questions exist.
|
|
269
|
+
*/
|
|
270
|
+
hasOwnPrompt(name: string): boolean;
|
|
238
271
|
instructedPrompt(prompt: string, instructionFileName: string, variables: any, saveResponse?: boolean, cacheMessage?: boolean, maxOutputChars?: number): Promise<any>;
|
|
239
272
|
preparedPrompt(promptFileName: string, variables: any, saveResponse?: boolean, cacheMessage?: boolean): Promise<any>;
|
|
240
273
|
withSmallModel<T>(fn: () => Promise<T>): Promise<T>;
|
|
@@ -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());
|
|
@@ -385,6 +426,16 @@ class Agent {
|
|
|
385
426
|
return false;
|
|
386
427
|
return this.aiService.hasPromptFile(this, name);
|
|
387
428
|
}
|
|
429
|
+
/**
|
|
430
|
+
* Whether this agent's own prompt folder supplies `<name>.prompt`, rather
|
|
431
|
+
* than inheriting it from the shared roots. See
|
|
432
|
+
* {@link BaseAiService.hasOwnPromptFile} for why both questions exist.
|
|
433
|
+
*/
|
|
434
|
+
hasOwnPrompt(name) {
|
|
435
|
+
if (!this.aiService || !this.userPaths)
|
|
436
|
+
return false;
|
|
437
|
+
return this.aiService.hasOwnPromptFile(this, name);
|
|
438
|
+
}
|
|
388
439
|
async instructedPrompt(prompt, instructionFileName, variables, saveResponse = true, cacheMessage = false, maxOutputChars = 0) {
|
|
389
440
|
return await this.aiService.instructedPrompt(this, prompt, instructionFileName, variables, saveResponse, this.aiService.getCacheConfig(this, cacheMessage), maxOutputChars);
|
|
390
441
|
}
|
|
@@ -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'),
|