briyah 2.0.5 → 2.0.6
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/data/common/prompts/moderate.json +34 -0
- package/data/common/prompts/moderate.prompt +136 -0
- 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 +6 -0
- package/dist-sdk/server/src/ai/agent.js +10 -0
- 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/room/room.d.ts +7 -5
- package/dist-sdk/server/src/room/room.js +37 -6
- package/dist-sdk/server/src/sdk/index.d.ts +4 -0
- package/dist-sdk/server/src/sdk/index.js +11 -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/index.js +2 -1
- package/package.json +1 -1
|
@@ -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.
|
|
@@ -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');
|
|
@@ -235,6 +235,12 @@ export declare class Agent {
|
|
|
235
235
|
* this agent run that turn" is then no, which is what a caller wants to hear.
|
|
236
236
|
*/
|
|
237
237
|
hasPrompt(name: string): boolean;
|
|
238
|
+
/**
|
|
239
|
+
* Whether this agent's own prompt folder supplies `<name>.prompt`, rather
|
|
240
|
+
* than inheriting it from the shared roots. See
|
|
241
|
+
* {@link BaseAiService.hasOwnPromptFile} for why both questions exist.
|
|
242
|
+
*/
|
|
243
|
+
hasOwnPrompt(name: string): boolean;
|
|
238
244
|
instructedPrompt(prompt: string, instructionFileName: string, variables: any, saveResponse?: boolean, cacheMessage?: boolean, maxOutputChars?: number): Promise<any>;
|
|
239
245
|
preparedPrompt(promptFileName: string, variables: any, saveResponse?: boolean, cacheMessage?: boolean): Promise<any>;
|
|
240
246
|
withSmallModel<T>(fn: () => Promise<T>): Promise<T>;
|
|
@@ -385,6 +385,16 @@ class Agent {
|
|
|
385
385
|
return false;
|
|
386
386
|
return this.aiService.hasPromptFile(this, name);
|
|
387
387
|
}
|
|
388
|
+
/**
|
|
389
|
+
* Whether this agent's own prompt folder supplies `<name>.prompt`, rather
|
|
390
|
+
* than inheriting it from the shared roots. See
|
|
391
|
+
* {@link BaseAiService.hasOwnPromptFile} for why both questions exist.
|
|
392
|
+
*/
|
|
393
|
+
hasOwnPrompt(name) {
|
|
394
|
+
if (!this.aiService || !this.userPaths)
|
|
395
|
+
return false;
|
|
396
|
+
return this.aiService.hasOwnPromptFile(this, name);
|
|
397
|
+
}
|
|
388
398
|
async instructedPrompt(prompt, instructionFileName, variables, saveResponse = true, cacheMessage = false, maxOutputChars = 0) {
|
|
389
399
|
return await this.aiService.instructedPrompt(this, prompt, instructionFileName, variables, saveResponse, this.aiService.getCacheConfig(this, cacheMessage), maxOutputChars);
|
|
390
400
|
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The shape of a host's queryable data, and of the questions an agent may ask
|
|
3
|
+
* about it.
|
|
4
|
+
*
|
|
5
|
+
* Briyah owns the protocol and the safety properties; the host owns the data. A
|
|
6
|
+
* host describes its datasets and supplies one {@link DataSource.execute}, and
|
|
7
|
+
* gets a validated, bounded, read-only query capability without writing a tool,
|
|
8
|
+
* a validator, a prompt schema or a result envelope.
|
|
9
|
+
*
|
|
10
|
+
* The safety model is *construction*, not inspection. An agent never writes a
|
|
11
|
+
* query language — it fills in {@link DataQuery}, whose every field name is
|
|
12
|
+
* looked up in the dataset's declared {@link DataField} list before the host
|
|
13
|
+
* sees it. A name that was not declared cannot reach the host, so a host's
|
|
14
|
+
* executor can treat a validated query as trusted input and never has to parse
|
|
15
|
+
* or sanitize anything a model wrote. That is what makes it safe to run against
|
|
16
|
+
* a database with no read-only role behind it.
|
|
17
|
+
*/
|
|
18
|
+
/** What kind of value a field holds, and therefore how it may be compared. */
|
|
19
|
+
export type DataFieldType = 'string' | 'number' | 'boolean' | 'date' | 'enum';
|
|
20
|
+
/** The aggregate functions a query may ask for. */
|
|
21
|
+
export type DataAggregateFn = 'count' | 'sum' | 'avg' | 'min' | 'max';
|
|
22
|
+
/**
|
|
23
|
+
* How a filter compares a field to a value.
|
|
24
|
+
*
|
|
25
|
+
* Deliberately small: everything here maps onto something every store can do,
|
|
26
|
+
* and nothing here can express a subquery, a join the host did not declare, or
|
|
27
|
+
* a raw expression.
|
|
28
|
+
*/
|
|
29
|
+
export type DataFilterOp = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'in' | 'contains' | 'between' | 'isNull' | 'notNull';
|
|
30
|
+
/**
|
|
31
|
+
* One queryable field.
|
|
32
|
+
*
|
|
33
|
+
* A field is not required to be a stored column. A host may declare a *derived*
|
|
34
|
+
* field — an age computed from a date of birth, a total computed from five
|
|
35
|
+
* columns — and translate it in its executor. Declaring it here is what keeps
|
|
36
|
+
* the arithmetic out of the model, which is the difference between an answer
|
|
37
|
+
* that is right and one that is plausible.
|
|
38
|
+
*/
|
|
39
|
+
export interface DataField {
|
|
40
|
+
/** The name an agent uses. Stable; it appears in prompts and saved queries. */
|
|
41
|
+
name: string;
|
|
42
|
+
type: DataFieldType;
|
|
43
|
+
/** Human-facing name for the schema guide. Falls back to `name`. */
|
|
44
|
+
label?: string;
|
|
45
|
+
/** What the field means, and anything an agent would otherwise assume wrongly. */
|
|
46
|
+
description?: string;
|
|
47
|
+
/** For `enum`, the values it may hold. Rendered into the guide and enforced. */
|
|
48
|
+
enumValues?: string[];
|
|
49
|
+
/** May appear in `filters`. Default true. */
|
|
50
|
+
filterable?: boolean;
|
|
51
|
+
/** May appear in `groupBy` or be selected as a dimension. Default true. */
|
|
52
|
+
groupable?: boolean;
|
|
53
|
+
/**
|
|
54
|
+
* The aggregate functions allowed on this field. Omit for none — a field
|
|
55
|
+
* nothing can be summed over, like a name.
|
|
56
|
+
*/
|
|
57
|
+
aggregates?: DataAggregateFn[];
|
|
58
|
+
}
|
|
59
|
+
/** One queryable collection of records. */
|
|
60
|
+
export interface DataSet {
|
|
61
|
+
/** The name an agent uses. */
|
|
62
|
+
name: string;
|
|
63
|
+
/** Human-facing name for the schema guide. Falls back to `name`. */
|
|
64
|
+
label?: string;
|
|
65
|
+
/** One or two sentences: what one row is, and what the set covers. */
|
|
66
|
+
description: string;
|
|
67
|
+
fields: DataField[];
|
|
68
|
+
/**
|
|
69
|
+
* Things an agent must know to read an answer correctly, rendered verbatim
|
|
70
|
+
* into the schema guide. This is the place to say what a set silently
|
|
71
|
+
* excludes, which of two plausible definitions a metric uses, and — just as
|
|
72
|
+
* importantly — what it is *not* related to, so an agent refuses a question
|
|
73
|
+
* instead of inventing a way to answer it.
|
|
74
|
+
*/
|
|
75
|
+
notes?: string[];
|
|
76
|
+
/** Rows returned when a query names no limit. Defaults to {@link DEFAULT_ROW_LIMIT}. */
|
|
77
|
+
defaultLimit?: number;
|
|
78
|
+
/** The most rows this set will ever return, whatever a query asks for. */
|
|
79
|
+
maxLimit?: number;
|
|
80
|
+
}
|
|
81
|
+
/** One comparison in a query. */
|
|
82
|
+
export interface DataFilter {
|
|
83
|
+
field: string;
|
|
84
|
+
op: DataFilterOp;
|
|
85
|
+
/** Omitted for `isNull`/`notNull`; an array for `in` and `between`. */
|
|
86
|
+
value?: any;
|
|
87
|
+
}
|
|
88
|
+
/** One aggregate in a query. */
|
|
89
|
+
export interface DataMetric {
|
|
90
|
+
fn: DataAggregateFn;
|
|
91
|
+
/** Omitted only for `count`, which counts rows. */
|
|
92
|
+
field?: string;
|
|
93
|
+
/** The name this metric has in the result rows. Defaults to `fn_field`. */
|
|
94
|
+
as?: string;
|
|
95
|
+
}
|
|
96
|
+
/** How to order a result. */
|
|
97
|
+
export interface DataOrder {
|
|
98
|
+
/** A grouped field's name, or a metric's `as` name. */
|
|
99
|
+
by: string;
|
|
100
|
+
dir?: 'asc' | 'desc';
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* A question, as an agent asks it.
|
|
104
|
+
*
|
|
105
|
+
* With no `groupBy` and no `metrics` this is a plain listing of rows. With
|
|
106
|
+
* either, it is an aggregate: `groupBy` names the dimensions and `metrics` the
|
|
107
|
+
* numbers, exactly as a pivot table would.
|
|
108
|
+
*/
|
|
109
|
+
export interface DataQuery {
|
|
110
|
+
dataset: string;
|
|
111
|
+
filters?: DataFilter[];
|
|
112
|
+
groupBy?: string[];
|
|
113
|
+
metrics?: DataMetric[];
|
|
114
|
+
/** Fields to return when this is a listing rather than an aggregate. */
|
|
115
|
+
select?: string[];
|
|
116
|
+
orderBy?: DataOrder[];
|
|
117
|
+
limit?: number;
|
|
118
|
+
}
|
|
119
|
+
/** One row of a result. Keys are field names, metric `as` names, or both. */
|
|
120
|
+
export type DataRow = Record<string, any>;
|
|
121
|
+
/** What a host's executor hands back. */
|
|
122
|
+
export interface DataResult {
|
|
123
|
+
rows: DataRow[];
|
|
124
|
+
/**
|
|
125
|
+
* Total rows the query matched, when the host can say cheaply. Lets an
|
|
126
|
+
* answer say "the top 10 of 240" rather than implying it saw everything.
|
|
127
|
+
*/
|
|
128
|
+
totalRows?: number;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* A host's queryable data.
|
|
132
|
+
*
|
|
133
|
+
* `execute` is only ever called with a query that has already been validated
|
|
134
|
+
* against the named dataset: every field exists, every operator is allowed on
|
|
135
|
+
* it, every enum value is one of the declared ones, and the limit is within the
|
|
136
|
+
* set's cap. A host does not need to re-check any of that, and must not accept
|
|
137
|
+
* a query from anywhere else.
|
|
138
|
+
*/
|
|
139
|
+
export interface DataSource {
|
|
140
|
+
/** Identifies the source in logs and in the schema guide's title. */
|
|
141
|
+
name: string;
|
|
142
|
+
/** Shown at the top of the schema guide. */
|
|
143
|
+
description?: string;
|
|
144
|
+
datasets: DataSet[];
|
|
145
|
+
/**
|
|
146
|
+
* Runs one validated query.
|
|
147
|
+
* @param query The validated query
|
|
148
|
+
* @param context The host's opaque per-invocation context, threaded from
|
|
149
|
+
* `sendRoomMessage` — where the tenant scoping lives. Never anything the
|
|
150
|
+
* model supplied.
|
|
151
|
+
* @returns The rows, and the total when it is cheap to know
|
|
152
|
+
*/
|
|
153
|
+
execute(query: DataQuery, context: unknown): Promise<DataResult>;
|
|
154
|
+
}
|
|
155
|
+
/** Rows returned when neither the query nor the dataset names a limit. */
|
|
156
|
+
export declare const DEFAULT_ROW_LIMIT = 50;
|
|
157
|
+
/** The ceiling no dataset's `maxLimit` may exceed. */
|
|
158
|
+
export declare const MAX_ROW_LIMIT = 1000;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* The shape of a host's queryable data, and of the questions an agent may ask
|
|
4
|
+
* about it.
|
|
5
|
+
*
|
|
6
|
+
* Briyah owns the protocol and the safety properties; the host owns the data. A
|
|
7
|
+
* host describes its datasets and supplies one {@link DataSource.execute}, and
|
|
8
|
+
* gets a validated, bounded, read-only query capability without writing a tool,
|
|
9
|
+
* a validator, a prompt schema or a result envelope.
|
|
10
|
+
*
|
|
11
|
+
* The safety model is *construction*, not inspection. An agent never writes a
|
|
12
|
+
* query language — it fills in {@link DataQuery}, whose every field name is
|
|
13
|
+
* looked up in the dataset's declared {@link DataField} list before the host
|
|
14
|
+
* sees it. A name that was not declared cannot reach the host, so a host's
|
|
15
|
+
* executor can treat a validated query as trusted input and never has to parse
|
|
16
|
+
* or sanitize anything a model wrote. That is what makes it safe to run against
|
|
17
|
+
* a database with no read-only role behind it.
|
|
18
|
+
*/
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.MAX_ROW_LIMIT = exports.DEFAULT_ROW_LIMIT = void 0;
|
|
21
|
+
/** Rows returned when neither the query nor the dataset names a limit. */
|
|
22
|
+
exports.DEFAULT_ROW_LIMIT = 50;
|
|
23
|
+
/** The ceiling no dataset's `maxLimit` may exceed. */
|
|
24
|
+
exports.MAX_ROW_LIMIT = 1_000;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turns whatever a model produced into a query a host can trust, or into an
|
|
3
|
+
* error the model can act on.
|
|
4
|
+
*
|
|
5
|
+
* Two rules shape everything here.
|
|
6
|
+
*
|
|
7
|
+
* **Nothing undeclared survives.** Every dataset, field, operator, enum value
|
|
8
|
+
* and aggregate is checked against the host's {@link DataSet} before the query
|
|
9
|
+
* is handed on. A host's executor therefore never sees a name it did not
|
|
10
|
+
* declare, which is what lets it build a statement without sanitizing anything.
|
|
11
|
+
*
|
|
12
|
+
* **A rejection names the alternatives.** "Unknown field" teaches a model
|
|
13
|
+
* nothing and it guesses again; "unknown field X — this set has A, B, C" is
|
|
14
|
+
* repaired on the next turn. This mirrors how the rest of Briyah answers a bad
|
|
15
|
+
* argument, and it is why these return strings rather than throwing.
|
|
16
|
+
*/
|
|
17
|
+
import { DataAggregateFn, DataQuery, DataSet } from './data.types';
|
|
18
|
+
/**
|
|
19
|
+
* A validated query, or the reason it was refused.
|
|
20
|
+
*
|
|
21
|
+
* One shape with optional halves rather than a discriminated union: this
|
|
22
|
+
* package compiles with `strictNullChecks` off, where narrowing on a boolean
|
|
23
|
+
* discriminant does not hold, so a union would force a cast at every use.
|
|
24
|
+
*/
|
|
25
|
+
export interface ValidationResult {
|
|
26
|
+
ok: boolean;
|
|
27
|
+
/** The normalized query. Present when `ok`. */
|
|
28
|
+
query?: DataQuery;
|
|
29
|
+
/** The dataset it names. Present when `ok`. */
|
|
30
|
+
dataset?: DataSet;
|
|
31
|
+
/** Why it was refused. Present when not `ok`. */
|
|
32
|
+
error?: string;
|
|
33
|
+
/** What could have been used instead, when naming them helps. */
|
|
34
|
+
available?: string[];
|
|
35
|
+
}
|
|
36
|
+
/** The name a metric carries in the result rows. */
|
|
37
|
+
export declare function metricName(fn: DataAggregateFn, field?: string, as?: string): string;
|
|
38
|
+
/**
|
|
39
|
+
* Checks a raw query against a dataset and fills in its defaults.
|
|
40
|
+
*
|
|
41
|
+
* @param raw The query as the model produced it
|
|
42
|
+
* @param sets Every dataset the source declares
|
|
43
|
+
* @returns The validated query, or a refusal naming what was allowed instead
|
|
44
|
+
*/
|
|
45
|
+
export declare function validateQuery(raw: any, sets: DataSet[]): ValidationResult;
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.metricName = metricName;
|
|
4
|
+
exports.validateQuery = validateQuery;
|
|
5
|
+
/**
|
|
6
|
+
* Turns whatever a model produced into a query a host can trust, or into an
|
|
7
|
+
* error the model can act on.
|
|
8
|
+
*
|
|
9
|
+
* Two rules shape everything here.
|
|
10
|
+
*
|
|
11
|
+
* **Nothing undeclared survives.** Every dataset, field, operator, enum value
|
|
12
|
+
* and aggregate is checked against the host's {@link DataSet} before the query
|
|
13
|
+
* is handed on. A host's executor therefore never sees a name it did not
|
|
14
|
+
* declare, which is what lets it build a statement without sanitizing anything.
|
|
15
|
+
*
|
|
16
|
+
* **A rejection names the alternatives.** "Unknown field" teaches a model
|
|
17
|
+
* nothing and it guesses again; "unknown field X — this set has A, B, C" is
|
|
18
|
+
* repaired on the next turn. This mirrors how the rest of Briyah answers a bad
|
|
19
|
+
* argument, and it is why these return strings rather than throwing.
|
|
20
|
+
*/
|
|
21
|
+
const data_types_1 = require("./data.types");
|
|
22
|
+
/** Operators that make sense per field type. */
|
|
23
|
+
const OPS_BY_TYPE = {
|
|
24
|
+
number: ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'in', 'between', 'isNull', 'notNull'],
|
|
25
|
+
date: ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'in', 'between', 'isNull', 'notNull'],
|
|
26
|
+
string: ['eq', 'ne', 'in', 'contains', 'isNull', 'notNull'],
|
|
27
|
+
enum: ['eq', 'ne', 'in', 'isNull', 'notNull'],
|
|
28
|
+
boolean: ['eq', 'ne', 'isNull', 'notNull'],
|
|
29
|
+
};
|
|
30
|
+
/** Operators that take no value at all. */
|
|
31
|
+
const VALUELESS_OPS = ['isNull', 'notNull'];
|
|
32
|
+
/** Aggregates that need a numeric or date field to mean anything. */
|
|
33
|
+
const NUMERIC_AGGREGATES = ['sum', 'avg'];
|
|
34
|
+
function fail(error, available) {
|
|
35
|
+
return available ? { ok: false, error, available } : { ok: false, error };
|
|
36
|
+
}
|
|
37
|
+
function fieldNames(set) {
|
|
38
|
+
return set.fields.map((field) => field.name);
|
|
39
|
+
}
|
|
40
|
+
function findField(set, name) {
|
|
41
|
+
return set.fields.find((field) => field.name === name);
|
|
42
|
+
}
|
|
43
|
+
/** The name a metric carries in the result rows. */
|
|
44
|
+
function metricName(fn, field, as) {
|
|
45
|
+
if (as) {
|
|
46
|
+
return as;
|
|
47
|
+
}
|
|
48
|
+
return field ? `${fn}_${field}` : fn;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Checks a raw query against a dataset and fills in its defaults.
|
|
52
|
+
*
|
|
53
|
+
* @param raw The query as the model produced it
|
|
54
|
+
* @param sets Every dataset the source declares
|
|
55
|
+
* @returns The validated query, or a refusal naming what was allowed instead
|
|
56
|
+
*/
|
|
57
|
+
function validateQuery(raw, sets) {
|
|
58
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
59
|
+
return fail('The query must be a JSON object.');
|
|
60
|
+
}
|
|
61
|
+
const set = sets.find((candidate) => candidate.name === raw.dataset);
|
|
62
|
+
if (!set) {
|
|
63
|
+
return fail(`Unknown dataset "${raw.dataset}". Available datasets:`, sets.map((candidate) => candidate.name));
|
|
64
|
+
}
|
|
65
|
+
const filters = [];
|
|
66
|
+
for (const rawFilter of asArray(raw.filters)) {
|
|
67
|
+
const checked = validateFilter(rawFilter, set);
|
|
68
|
+
if ('error' in checked) {
|
|
69
|
+
return checked.error;
|
|
70
|
+
}
|
|
71
|
+
filters.push(checked.filter);
|
|
72
|
+
}
|
|
73
|
+
const groupBy = [];
|
|
74
|
+
for (const name of asArray(raw.groupBy)) {
|
|
75
|
+
const field = findField(set, String(name));
|
|
76
|
+
if (!field) {
|
|
77
|
+
return fail(`Cannot group by "${name}" — no such field in "${set.name}". Fields:`, fieldNames(set));
|
|
78
|
+
}
|
|
79
|
+
if (field.groupable === false) {
|
|
80
|
+
return fail(`Cannot group by "${name}". Groupable fields:`, set.fields.filter((f) => f.groupable !== false).map((f) => f.name));
|
|
81
|
+
}
|
|
82
|
+
groupBy.push(field.name);
|
|
83
|
+
}
|
|
84
|
+
const metrics = [];
|
|
85
|
+
for (const rawMetric of asArray(raw.metrics)) {
|
|
86
|
+
const checked = validateMetric(rawMetric, set);
|
|
87
|
+
if ('error' in checked) {
|
|
88
|
+
return checked.error;
|
|
89
|
+
}
|
|
90
|
+
metrics.push(checked.metric);
|
|
91
|
+
}
|
|
92
|
+
const select = [];
|
|
93
|
+
for (const name of asArray(raw.select)) {
|
|
94
|
+
const field = findField(set, String(name));
|
|
95
|
+
if (!field) {
|
|
96
|
+
return fail(`Cannot select "${name}" — no such field in "${set.name}". Fields:`, fieldNames(set));
|
|
97
|
+
}
|
|
98
|
+
select.push(field.name);
|
|
99
|
+
}
|
|
100
|
+
// An aggregate answers with its dimensions and its numbers; anything else
|
|
101
|
+
// asked for has no row to come from.
|
|
102
|
+
const isAggregate = groupBy.length > 0 || metrics.length > 0;
|
|
103
|
+
const orderable = isAggregate
|
|
104
|
+
? [...groupBy, ...metrics.map((m) => m.as)]
|
|
105
|
+
: [...fieldNames(set)];
|
|
106
|
+
const orderBy = [];
|
|
107
|
+
for (const rawOrder of asArray(raw.orderBy)) {
|
|
108
|
+
const by = String(rawOrder?.by ?? '');
|
|
109
|
+
if (!orderable.includes(by)) {
|
|
110
|
+
return fail(`Cannot order by "${by}". ${isAggregate ? 'An aggregate can be ordered by a grouped field or a metric:' : 'Orderable fields:'}`, orderable);
|
|
111
|
+
}
|
|
112
|
+
const dir = String(rawOrder?.dir ?? 'asc').toLowerCase();
|
|
113
|
+
if (dir !== 'asc' && dir !== 'desc') {
|
|
114
|
+
return fail(`Order direction must be "asc" or "desc", not "${rawOrder?.dir}".`);
|
|
115
|
+
}
|
|
116
|
+
orderBy.push({ by, dir: dir });
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
ok: true,
|
|
120
|
+
dataset: set,
|
|
121
|
+
query: {
|
|
122
|
+
dataset: set.name,
|
|
123
|
+
filters,
|
|
124
|
+
groupBy,
|
|
125
|
+
metrics,
|
|
126
|
+
select,
|
|
127
|
+
orderBy,
|
|
128
|
+
limit: resolveLimit(raw.limit, set),
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
/** Clamps a requested row count into the dataset's and the engine's bounds. */
|
|
133
|
+
function resolveLimit(requested, set) {
|
|
134
|
+
const ceiling = Math.min(set.maxLimit ?? data_types_1.MAX_ROW_LIMIT, data_types_1.MAX_ROW_LIMIT);
|
|
135
|
+
const asked = Number(requested);
|
|
136
|
+
if (!Number.isFinite(asked) || asked <= 0) {
|
|
137
|
+
return Math.min(set.defaultLimit ?? data_types_1.DEFAULT_ROW_LIMIT, ceiling);
|
|
138
|
+
}
|
|
139
|
+
return Math.min(Math.floor(asked), ceiling);
|
|
140
|
+
}
|
|
141
|
+
function asArray(value) {
|
|
142
|
+
if (value === undefined || value === null) {
|
|
143
|
+
return [];
|
|
144
|
+
}
|
|
145
|
+
return Array.isArray(value) ? value : [value];
|
|
146
|
+
}
|
|
147
|
+
function validateFilter(raw, set) {
|
|
148
|
+
if (!raw || typeof raw !== 'object') {
|
|
149
|
+
return { error: fail('Each filter must be an object of {field, op, value}.') };
|
|
150
|
+
}
|
|
151
|
+
const field = findField(set, String(raw.field ?? ''));
|
|
152
|
+
if (!field) {
|
|
153
|
+
return {
|
|
154
|
+
error: fail(`Cannot filter on "${raw.field}" — no such field in "${set.name}". Fields:`, fieldNames(set)),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
if (field.filterable === false) {
|
|
158
|
+
return {
|
|
159
|
+
error: fail(`Cannot filter on "${field.name}". Filterable fields:`, set.fields.filter((f) => f.filterable !== false).map((f) => f.name)),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
const op = String(raw.op ?? '');
|
|
163
|
+
const allowed = OPS_BY_TYPE[field.type] || [];
|
|
164
|
+
if (!allowed.includes(op)) {
|
|
165
|
+
return {
|
|
166
|
+
error: fail(`Operator "${raw.op}" does not apply to ${field.type} field "${field.name}". Allowed:`, allowed),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
if (VALUELESS_OPS.includes(op)) {
|
|
170
|
+
return { filter: { field: field.name, op } };
|
|
171
|
+
}
|
|
172
|
+
if (raw.value === undefined || raw.value === null) {
|
|
173
|
+
return { error: fail(`Filter on "${field.name}" with "${op}" needs a value.`) };
|
|
174
|
+
}
|
|
175
|
+
if (op === 'in') {
|
|
176
|
+
const values = asArray(raw.value);
|
|
177
|
+
if (values.length === 0) {
|
|
178
|
+
return { error: fail(`Filter on "${field.name}" with "in" needs a non-empty list of values.`) };
|
|
179
|
+
}
|
|
180
|
+
const bad = enumViolation(field, values);
|
|
181
|
+
if (bad) {
|
|
182
|
+
return { error: bad };
|
|
183
|
+
}
|
|
184
|
+
return { filter: { field: field.name, op, value: values } };
|
|
185
|
+
}
|
|
186
|
+
if (op === 'between') {
|
|
187
|
+
const values = asArray(raw.value);
|
|
188
|
+
if (values.length !== 2) {
|
|
189
|
+
return {
|
|
190
|
+
error: fail(`Filter on "${field.name}" with "between" needs exactly two values: [low, high].`),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
return { filter: { field: field.name, op, value: values } };
|
|
194
|
+
}
|
|
195
|
+
const bad = enumViolation(field, [raw.value]);
|
|
196
|
+
if (bad) {
|
|
197
|
+
return { error: bad };
|
|
198
|
+
}
|
|
199
|
+
return { filter: { field: field.name, op, value: raw.value } };
|
|
200
|
+
}
|
|
201
|
+
/** Enum fields accept only what they declared, so a typo is caught here. */
|
|
202
|
+
function enumViolation(field, values) {
|
|
203
|
+
if (field.type !== 'enum' || !field.enumValues?.length) {
|
|
204
|
+
return null;
|
|
205
|
+
}
|
|
206
|
+
for (const value of values) {
|
|
207
|
+
if (!field.enumValues.includes(String(value))) {
|
|
208
|
+
return fail(`"${value}" is not a value of "${field.name}". Allowed:`, field.enumValues);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
function validateMetric(raw, set) {
|
|
214
|
+
if (!raw || typeof raw !== 'object') {
|
|
215
|
+
return { error: fail('Each metric must be an object of {fn, field}.') };
|
|
216
|
+
}
|
|
217
|
+
const fn = String(raw.fn ?? '');
|
|
218
|
+
if (!['count', 'sum', 'avg', 'min', 'max'].includes(fn)) {
|
|
219
|
+
return {
|
|
220
|
+
error: fail(`Unknown aggregate "${raw.fn}". Available:`, ['count', 'sum', 'avg', 'min', 'max']),
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
// `count` alone counts rows, which needs no field and is always allowed.
|
|
224
|
+
if (fn === 'count' && (raw.field === undefined || raw.field === null || raw.field === '')) {
|
|
225
|
+
return { metric: { fn, as: metricName(fn, undefined, raw.as) } };
|
|
226
|
+
}
|
|
227
|
+
const field = findField(set, String(raw.field ?? ''));
|
|
228
|
+
if (!field) {
|
|
229
|
+
return {
|
|
230
|
+
error: fail(`Cannot ${fn} "${raw.field}" — no such field in "${set.name}". Fields:`, fieldNames(set)),
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
if (!field.aggregates?.includes(fn)) {
|
|
234
|
+
const capable = set.fields.filter((f) => f.aggregates?.includes(fn)).map((f) => f.name);
|
|
235
|
+
return {
|
|
236
|
+
error: fail(capable.length
|
|
237
|
+
? `Cannot ${fn} "${field.name}". Fields that support ${fn}:`
|
|
238
|
+
: `Cannot ${fn} "${field.name}", and no field in "${set.name}" supports ${fn}.`, capable.length ? capable : undefined),
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
if (NUMERIC_AGGREGATES.includes(fn) && field.type !== 'number') {
|
|
242
|
+
return { error: fail(`Cannot ${fn} "${field.name}" — it is a ${field.type}, not a number.`) };
|
|
243
|
+
}
|
|
244
|
+
return { metric: { fn, field: field.name, as: metricName(fn, field.name, raw.as) } };
|
|
245
|
+
}
|
|
@@ -980,11 +980,13 @@ export declare class Room {
|
|
|
980
980
|
* other room the first agent is whoever happened to be added first and has no
|
|
981
981
|
* `moderate.prompt` at all. Name one explicitly.
|
|
982
982
|
*
|
|
983
|
-
* The fallback prefers an agent
|
|
984
|
-
*
|
|
985
|
-
*
|
|
986
|
-
*
|
|
987
|
-
*
|
|
983
|
+
* The fallback prefers an agent whose own folder carries a `moderate.prompt`,
|
|
984
|
+
* because a folder that ships one was written to route for its domain and its
|
|
985
|
+
* examples are drawn from it. It has to ask for the folder's *own* file:
|
|
986
|
+
* `common/prompts/moderate.prompt` is the shared fallback, so every agent can
|
|
987
|
+
* moderate and asking whether one merely resolves the prompt would pick out
|
|
988
|
+
* nobody. Arrival order is consulted only when no folder is purpose-built,
|
|
989
|
+
* which is the ordinary case in a room assembled from generic agents.
|
|
988
990
|
* @returns The moderator agent or undefined if the room is empty
|
|
989
991
|
*/
|
|
990
992
|
getModeratorAgent(): Agent | undefined;
|
|
@@ -1731,6 +1731,17 @@ class Room {
|
|
|
1731
1731
|
// being asked again: without one it cannot tell a continuation from being
|
|
1732
1732
|
// handed back something it has already answered.
|
|
1733
1733
|
if (opts.continuing) {
|
|
1734
|
+
// A person is never "continuing": in a broadcast room every agent is a
|
|
1735
|
+
// responder, so the sender of a human's own message is the human agent
|
|
1736
|
+
// and this branch would hand their turn to the model. It answered as
|
|
1737
|
+
// them — inventing follow-up questions in their name and echoing their
|
|
1738
|
+
// last message back into the transcript — because this returns before
|
|
1739
|
+
// the isControlledByHuman gate below. Decline the turn instead, which
|
|
1740
|
+
// is what `hear` would have done with their own message anyway.
|
|
1741
|
+
if (agent.isControlledByHuman) {
|
|
1742
|
+
onResponse(null);
|
|
1743
|
+
return;
|
|
1744
|
+
}
|
|
1734
1745
|
agent.addToConversationHistory(Room.CONTINUE_NOTE, false);
|
|
1735
1746
|
agent.save();
|
|
1736
1747
|
this.getAgentAiResponse(agent, message, onResponse);
|
|
@@ -2244,11 +2255,13 @@ Recent Message: ${message.getContent()}
|
|
|
2244
2255
|
* other room the first agent is whoever happened to be added first and has no
|
|
2245
2256
|
* `moderate.prompt` at all. Name one explicitly.
|
|
2246
2257
|
*
|
|
2247
|
-
* The fallback prefers an agent
|
|
2248
|
-
*
|
|
2249
|
-
*
|
|
2250
|
-
*
|
|
2251
|
-
*
|
|
2258
|
+
* The fallback prefers an agent whose own folder carries a `moderate.prompt`,
|
|
2259
|
+
* because a folder that ships one was written to route for its domain and its
|
|
2260
|
+
* examples are drawn from it. It has to ask for the folder's *own* file:
|
|
2261
|
+
* `common/prompts/moderate.prompt` is the shared fallback, so every agent can
|
|
2262
|
+
* moderate and asking whether one merely resolves the prompt would pick out
|
|
2263
|
+
* nobody. Arrival order is consulted only when no folder is purpose-built,
|
|
2264
|
+
* which is the ordinary case in a room assembled from generic agents.
|
|
2252
2265
|
* @returns The moderator agent or undefined if the room is empty
|
|
2253
2266
|
*/
|
|
2254
2267
|
getModeratorAgent() {
|
|
@@ -2263,7 +2276,7 @@ Recent Message: ${message.getContent()}
|
|
|
2263
2276
|
// table this was unlikely to bite; with several, the odds that the first
|
|
2264
2277
|
// agent is one of them are much better.
|
|
2265
2278
|
const candidates = this.agents.filter((a) => !a.isControlledByHuman);
|
|
2266
|
-
return candidates.find((a) => a.
|
|
2279
|
+
return candidates.find((a) => a.hasOwnPrompt('moderate')) ?? candidates[0];
|
|
2267
2280
|
}
|
|
2268
2281
|
/**
|
|
2269
2282
|
* Gets the current story situation
|
|
@@ -2988,6 +3001,24 @@ Recent Message: ${message.getContent()}
|
|
|
2988
3001
|
this.endTurn('release');
|
|
2989
3002
|
return;
|
|
2990
3003
|
}
|
|
3004
|
+
// A moderator that cannot be prompted is not a moderator. A folder
|
|
3005
|
+
// carrying no `moderate.prompt` threw inside the dispatch below, where
|
|
3006
|
+
// the catch could only log it: the turn ended with nothing said, so the
|
|
3007
|
+
// person waiting saw the room go quiet — no answer, no error, no clue
|
|
3008
|
+
// that their agent had addressed somebody who was not there.
|
|
3009
|
+
//
|
|
3010
|
+
// `common/prompts/moderate.prompt` now answers for every folder that
|
|
3011
|
+
// does not have its own, so reaching this means the shared file is gone
|
|
3012
|
+
// from the prompts root — a host that pruned it, or a data directory
|
|
3013
|
+
// that predates it and never took the refresh. Rare, and still worth
|
|
3014
|
+
// saying out loud rather than going quiet again.
|
|
3015
|
+
if (!moderator.hasPrompt('moderate')) {
|
|
3016
|
+
const first = moderateMessages[0];
|
|
3017
|
+
logger_1.logger.warn(`Room ${this.name}: ${moderator.agentNickname} has no moderate.prompt, so ${first.getSender()}'s message cannot be routed`);
|
|
3018
|
+
this.addRoomMessage(new message_1.RoomMessage('System', app_types_1.MessageAction.SYSTEM, `${first.getSender()} sent a message this room could not route, and there is no moderator able to place it.`, [], null, null));
|
|
3019
|
+
this.endTurn('release', { drain: true });
|
|
3020
|
+
return;
|
|
3021
|
+
}
|
|
2991
3022
|
// Take the first moderate message
|
|
2992
3023
|
const originalMessage = moderateMessages[0];
|
|
2993
3024
|
// Put any remaining moderate messages back in the queue
|
|
@@ -9,6 +9,10 @@ export type { NativeToolDefinition, ToolHelpers, ToolContext, ToolCaller, ToolAr
|
|
|
9
9
|
export { dnd5eTools } from '../tools/packs/dnd5e';
|
|
10
10
|
export { installToolPacks, registerToolPacks, availableToolPacks } from '../tools/packs';
|
|
11
11
|
export { NativeToolRegistry } from '../tools/native-tool-registry.service';
|
|
12
|
+
export type { DataSource, DataSet, DataField, DataFieldType, DataAggregateFn, DataFilter, DataFilterOp, DataMetric, DataOrder, DataQuery, DataRow, DataResult, } from '../data/data.types';
|
|
13
|
+
export { DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT } from '../data/data.types';
|
|
14
|
+
export { registerDataSource, unregisterDataSource, listDataSources, listDatasets, } from '../data/data-registry';
|
|
15
|
+
export { buildDataGuideMarkdown } from '../data/data-guide.builder';
|
|
12
16
|
export { PackService } from '../packs/pack.service';
|
|
13
17
|
export type { PackView } from '../packs/pack.service';
|
|
14
18
|
export { PackInstantiationService } from '../packs/pack-instantiation.service';
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.RoomMessage = exports.Room = exports.Agent = exports.PackInstantiationService = exports.PackService = exports.NativeToolRegistry = exports.availableToolPacks = exports.registerToolPacks = exports.installToolPacks = exports.dnd5eTools = exports.buildMarkdown = exports.pageMarker = exports.stripWrappingFence = exports.splitMarkdownIntoPages = exports.BriyahConfigService = exports.Briyah = void 0;
|
|
3
|
+
exports.RoomMessage = exports.Room = exports.Agent = exports.PackInstantiationService = exports.PackService = exports.buildDataGuideMarkdown = exports.listDatasets = exports.listDataSources = exports.unregisterDataSource = exports.registerDataSource = exports.MAX_ROW_LIMIT = exports.DEFAULT_ROW_LIMIT = exports.NativeToolRegistry = exports.availableToolPacks = exports.registerToolPacks = exports.installToolPacks = exports.dnd5eTools = exports.buildMarkdown = exports.pageMarker = exports.stripWrappingFence = exports.splitMarkdownIntoPages = exports.BriyahConfigService = exports.Briyah = void 0;
|
|
4
4
|
// Main SDK exports
|
|
5
5
|
var briyah_1 = require("./briyah");
|
|
6
6
|
Object.defineProperty(exports, "Briyah", { enumerable: true, get: function () { return briyah_1.Briyah; } });
|
|
@@ -33,6 +33,16 @@ Object.defineProperty(exports, "registerToolPacks", { enumerable: true, get: fun
|
|
|
33
33
|
Object.defineProperty(exports, "availableToolPacks", { enumerable: true, get: function () { return packs_1.availableToolPacks; } });
|
|
34
34
|
var native_tool_registry_service_1 = require("../tools/native-tool-registry.service");
|
|
35
35
|
Object.defineProperty(exports, "NativeToolRegistry", { enumerable: true, get: function () { return native_tool_registry_service_1.NativeToolRegistry; } });
|
|
36
|
+
var data_types_1 = require("../data/data.types");
|
|
37
|
+
Object.defineProperty(exports, "DEFAULT_ROW_LIMIT", { enumerable: true, get: function () { return data_types_1.DEFAULT_ROW_LIMIT; } });
|
|
38
|
+
Object.defineProperty(exports, "MAX_ROW_LIMIT", { enumerable: true, get: function () { return data_types_1.MAX_ROW_LIMIT; } });
|
|
39
|
+
var data_registry_1 = require("../data/data-registry");
|
|
40
|
+
Object.defineProperty(exports, "registerDataSource", { enumerable: true, get: function () { return data_registry_1.registerDataSource; } });
|
|
41
|
+
Object.defineProperty(exports, "unregisterDataSource", { enumerable: true, get: function () { return data_registry_1.unregisterDataSource; } });
|
|
42
|
+
Object.defineProperty(exports, "listDataSources", { enumerable: true, get: function () { return data_registry_1.listDataSources; } });
|
|
43
|
+
Object.defineProperty(exports, "listDatasets", { enumerable: true, get: function () { return data_registry_1.listDatasets; } });
|
|
44
|
+
var data_guide_builder_1 = require("../data/data-guide.builder");
|
|
45
|
+
Object.defineProperty(exports, "buildDataGuideMarkdown", { enumerable: true, get: function () { return data_guide_builder_1.buildDataGuideMarkdown; } });
|
|
36
46
|
// Packs: a domain's prompt folders, documents, tools and templates, installed for
|
|
37
47
|
// everyone and enabled per user.
|
|
38
48
|
//
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reading a host's data, without the model ever writing a query language.
|
|
3
|
+
*
|
|
4
|
+
* `query_data` takes a JSON description of a question — dataset, filters,
|
|
5
|
+
* groupings, metrics — validates every name in it against what the host
|
|
6
|
+
* declared, and hands the result to the host's executor. A field the host did
|
|
7
|
+
* not declare cannot reach the executor, so the host builds its statement from
|
|
8
|
+
* names it chose rather than from anything a model produced. That is the whole
|
|
9
|
+
* safety argument, and it holds without a read-only database role behind it.
|
|
10
|
+
*
|
|
11
|
+
* The DSL arrives as one string parameter because {@link ToolParameter} cannot
|
|
12
|
+
* express nesting. Models reproduce a shown example far more reliably than they
|
|
13
|
+
* invent a shape, so the description carries two worked ones.
|
|
14
|
+
*/
|
|
15
|
+
import { NativeToolDefinition } from '../native-tool.types';
|
|
16
|
+
export declare const describeDataTool: NativeToolDefinition;
|
|
17
|
+
export declare const queryDataTool: NativeToolDefinition;
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.queryDataTool = exports.describeDataTool = void 0;
|
|
4
|
+
const coerce_1 = require("../shared/coerce");
|
|
5
|
+
const data_registry_1 = require("../../data/data-registry");
|
|
6
|
+
const query_validation_1 = require("../../data/query-validation");
|
|
7
|
+
/** Serialized characters a query result may occupy. Under the tool's own budget. */
|
|
8
|
+
const RESULT_BUDGET = 20_000;
|
|
9
|
+
const QUERY_EXAMPLE = '{"dataset": "claims", "filters": [{"field": "year", "op": "gte", "value": 2022}], ' +
|
|
10
|
+
'"groupBy": ["customer"], "metrics": [{"fn": "sum", "field": "incurred"}], ' +
|
|
11
|
+
'"orderBy": [{"by": "sum_incurred", "dir": "desc"}], "limit": 10}';
|
|
12
|
+
const LIST_EXAMPLE = '{"dataset": "drivers", "filters": [{"field": "age", "op": "lt", "value": 30}, ' +
|
|
13
|
+
'{"field": "active", "op": "eq", "value": true}], "select": ["firstName", "lastName", "age"]}';
|
|
14
|
+
/** Names every dataset, for an error that teaches rather than just refuses. */
|
|
15
|
+
function datasetNames() {
|
|
16
|
+
return (0, data_registry_1.listDatasets)().map((set) => set.name);
|
|
17
|
+
}
|
|
18
|
+
exports.describeDataTool = {
|
|
19
|
+
name: 'describe_data',
|
|
20
|
+
description: 'Lists the datasets you can query, or the fields of one dataset. Your attached ' +
|
|
21
|
+
'data guide already describes these — use this when you need to confirm a field ' +
|
|
22
|
+
'exists, or when the guide and a query result disagree.',
|
|
23
|
+
parameters: [
|
|
24
|
+
{
|
|
25
|
+
name: 'dataset',
|
|
26
|
+
type: 'string',
|
|
27
|
+
description: 'The dataset to describe. Omit to list every dataset.',
|
|
28
|
+
required: false,
|
|
29
|
+
},
|
|
30
|
+
],
|
|
31
|
+
handler: async (args) => {
|
|
32
|
+
if (!(0, data_registry_1.hasDataSources)()) {
|
|
33
|
+
return {
|
|
34
|
+
ok: false,
|
|
35
|
+
summary: 'No data is available to query',
|
|
36
|
+
error: 'This application has not made any data available to query.',
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
const wanted = args.dataset === undefined || args.dataset === null || args.dataset === ''
|
|
40
|
+
? ''
|
|
41
|
+
: (0, coerce_1.str)(args.dataset, 'dataset');
|
|
42
|
+
if (!wanted) {
|
|
43
|
+
const sets = (0, data_registry_1.listDatasets)();
|
|
44
|
+
return {
|
|
45
|
+
ok: true,
|
|
46
|
+
summary: `Listed ${sets.length} dataset(s)`,
|
|
47
|
+
datasets: sets.map((set) => ({
|
|
48
|
+
name: set.name,
|
|
49
|
+
label: set.label || set.name,
|
|
50
|
+
description: set.description,
|
|
51
|
+
})),
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
const set = (0, data_registry_1.listDatasets)().find((candidate) => candidate.name === wanted);
|
|
55
|
+
if (!set) {
|
|
56
|
+
return {
|
|
57
|
+
ok: false,
|
|
58
|
+
summary: `No dataset called "${wanted}"`,
|
|
59
|
+
error: `Unknown dataset "${wanted}". Available datasets:`,
|
|
60
|
+
available: datasetNames(),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
return {
|
|
64
|
+
ok: true,
|
|
65
|
+
summary: `Described the "${set.name}" dataset`,
|
|
66
|
+
dataset: set.name,
|
|
67
|
+
label: set.label || set.name,
|
|
68
|
+
description: set.description,
|
|
69
|
+
notes: set.notes || [],
|
|
70
|
+
fields: set.fields,
|
|
71
|
+
};
|
|
72
|
+
},
|
|
73
|
+
timeoutMs: 5_000,
|
|
74
|
+
};
|
|
75
|
+
exports.queryDataTool = {
|
|
76
|
+
name: 'query_data',
|
|
77
|
+
description: 'Answers a question about the application\'s data. Pass a JSON query naming a ' +
|
|
78
|
+
'dataset from your data guide, with optional filters, groupBy, metrics, orderBy ' +
|
|
79
|
+
'and limit. Aggregate example: ' +
|
|
80
|
+
QUERY_EXAMPLE +
|
|
81
|
+
' — listing example: ' +
|
|
82
|
+
LIST_EXAMPLE +
|
|
83
|
+
' Only the datasets and fields in your data guide exist; if a question needs ' +
|
|
84
|
+
'something that is not there, say so rather than substituting a field that looks close.',
|
|
85
|
+
parameters: [
|
|
86
|
+
{
|
|
87
|
+
name: 'query',
|
|
88
|
+
type: 'string',
|
|
89
|
+
description: 'The query as a JSON object. Example: ' + QUERY_EXAMPLE,
|
|
90
|
+
required: true,
|
|
91
|
+
},
|
|
92
|
+
],
|
|
93
|
+
handler: async (args, _helpers, context) => {
|
|
94
|
+
if (!(0, data_registry_1.hasDataSources)()) {
|
|
95
|
+
return {
|
|
96
|
+
ok: false,
|
|
97
|
+
summary: 'No data is available to query',
|
|
98
|
+
error: 'This application has not made any data available to query.',
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
const raw = (0, coerce_1.jsonObject)(args.query, 'query', QUERY_EXAMPLE);
|
|
102
|
+
const checked = (0, query_validation_1.validateQuery)(raw, (0, data_registry_1.listDatasets)());
|
|
103
|
+
if (!checked.ok) {
|
|
104
|
+
// A refusal, not a malfunction: it names what was allowed instead so
|
|
105
|
+
// the next turn can be right rather than another guess.
|
|
106
|
+
return {
|
|
107
|
+
ok: false,
|
|
108
|
+
summary: 'Query refused',
|
|
109
|
+
error: checked.error,
|
|
110
|
+
...(checked.available ? { available: checked.available } : {}),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
const source = (0, data_registry_1.sourceForDataset)(checked.query.dataset);
|
|
114
|
+
if (!source) {
|
|
115
|
+
return {
|
|
116
|
+
ok: false,
|
|
117
|
+
summary: `No source offers "${checked.query.dataset}"`,
|
|
118
|
+
error: `Unknown dataset "${checked.query.dataset}". Available datasets:`,
|
|
119
|
+
available: datasetNames(),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
const result = await source.execute(checked.query, context);
|
|
123
|
+
const rows = Array.isArray(result?.rows) ? result.rows : [];
|
|
124
|
+
const fitted = fitRows(rows);
|
|
125
|
+
return {
|
|
126
|
+
ok: true,
|
|
127
|
+
summary: summarize(checked.query.dataset, fitted.rows.length, result?.totalRows),
|
|
128
|
+
dataset: checked.query.dataset,
|
|
129
|
+
// Echoed so an answer can state the question it actually asked, and
|
|
130
|
+
// so a wrong answer can be traced to a wrong query.
|
|
131
|
+
query: checked.query,
|
|
132
|
+
rowCount: fitted.rows.length,
|
|
133
|
+
...(typeof result?.totalRows === 'number' ? { totalRows: result.totalRows } : {}),
|
|
134
|
+
...(fitted.dropped > 0
|
|
135
|
+
? {
|
|
136
|
+
truncated: true,
|
|
137
|
+
note: `${fitted.dropped} more row(s) were dropped to fit the result size. ` +
|
|
138
|
+
'Add filters, group the data, or lower the limit.',
|
|
139
|
+
}
|
|
140
|
+
: {}),
|
|
141
|
+
rows: fitted.rows,
|
|
142
|
+
};
|
|
143
|
+
},
|
|
144
|
+
// Rows are the payload, and a grouped answer is worth reading whole. Still
|
|
145
|
+
// modest: every result is appended to the calling agent's history.
|
|
146
|
+
maxResultChars: 24_000,
|
|
147
|
+
timeoutMs: 30_000,
|
|
148
|
+
};
|
|
149
|
+
/** Drops trailing rows until the payload fits, reporting how many went. */
|
|
150
|
+
function fitRows(rows) {
|
|
151
|
+
let kept = rows;
|
|
152
|
+
while (kept.length > 0 && JSON.stringify(kept).length > RESULT_BUDGET) {
|
|
153
|
+
kept = kept.slice(0, Math.max(1, Math.floor(kept.length / 2)));
|
|
154
|
+
if (kept.length === 1 && JSON.stringify(kept).length > RESULT_BUDGET) {
|
|
155
|
+
return { rows: [], dropped: rows.length };
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return { rows: kept, dropped: rows.length - kept.length };
|
|
159
|
+
}
|
|
160
|
+
function summarize(dataset, returned, total) {
|
|
161
|
+
if (typeof total === 'number' && total > returned) {
|
|
162
|
+
return `Queried ${dataset}: ${returned} of ${total} rows`;
|
|
163
|
+
}
|
|
164
|
+
return `Queried ${dataset}: ${returned} row(s)`;
|
|
165
|
+
}
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
exports.CORE_TOOL_GROUP = void 0;
|
|
18
18
|
exports.coreTools = coreTools;
|
|
19
|
+
const data_tools_1 = require("./data.tools");
|
|
19
20
|
const illustrate_tool_1 = require("./illustrate.tool");
|
|
20
21
|
const rename_tool_1 = require("./rename.tool");
|
|
21
22
|
/** The name the UI groups these under, in place of a pack name. */
|
|
@@ -28,5 +29,5 @@ exports.CORE_TOOL_GROUP = 'core';
|
|
|
28
29
|
* @returns The tool definitions
|
|
29
30
|
*/
|
|
30
31
|
function coreTools() {
|
|
31
|
-
return [rename_tool_1.renameAgentTool, illustrate_tool_1.illustrateTool];
|
|
32
|
+
return [rename_tool_1.renameAgentTool, illustrate_tool_1.illustrateTool, data_tools_1.describeDataTool, data_tools_1.queryDataTool];
|
|
32
33
|
}
|
package/package.json
CHANGED