briyah 2.0.8 → 2.0.10
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 +30 -0
- package/data/common/config/model_prices.annotations.json +12 -0
- package/data/common/config/model_prices.json +65900 -33740
- package/dist-sdk/server/src/ai/LLM/anthropic.service.d.ts +7 -0
- package/dist-sdk/server/src/ai/LLM/anthropic.service.js +26 -23
- package/dist-sdk/server/src/ai/LLM/attachment-type.d.ts +21 -0
- package/dist-sdk/server/src/ai/LLM/attachment-type.js +76 -0
- package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +24 -0
- package/dist-sdk/server/src/ai/LLM/base-ai.service.js +57 -19
- package/dist-sdk/server/src/ai/LLM/openai.service.d.ts +7 -1
- package/dist-sdk/server/src/ai/LLM/openai.service.js +28 -10
- package/dist-sdk/server/src/ai/model_prices.d.ts +3 -2
- package/dist-sdk/server/src/ai/model_prices.js +53 -3
- package/dist-sdk/server/src/data/data-guide.builder.js +18 -1
- package/dist-sdk/server/src/data/data.types.d.ts +52 -7
- package/dist-sdk/server/src/data/query-validation.js +85 -12
- package/dist-sdk/server/src/data/row-executor.d.ts +35 -0
- package/dist-sdk/server/src/data/row-executor.js +274 -0
- package/dist-sdk/server/src/room/room.d.ts +8 -0
- package/dist-sdk/server/src/room/room.js +35 -0
- package/dist-sdk/server/src/sdk/briyah.js +6 -0
- package/dist-sdk/server/src/sdk/index.d.ts +4 -1
- package/dist-sdk/server/src/sdk/index.js +15 -1
- package/dist-sdk/server/src/tools/core/data.tools.js +2 -0
- package/package.json +1 -1
|
@@ -15,10 +15,24 @@
|
|
|
15
15
|
* or sanitize anything a model wrote. That is what makes it safe to run against
|
|
16
16
|
* a database with no read-only role behind it.
|
|
17
17
|
*/
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
/**
|
|
19
|
+
* What kind of value a field holds, and therefore how it may be compared.
|
|
20
|
+
*
|
|
21
|
+
* `list` is a set of strings on one row — the states a market is licensed in,
|
|
22
|
+
* the coverage lines it writes. It is filtered by membership (`has`, `hasAny`,
|
|
23
|
+
* `contains`, `isEmpty`, `notEmpty`) and can be neither grouped nor
|
|
24
|
+
* aggregated: grouping by a set has no single answer, and the set's members are
|
|
25
|
+
* better asked about as rows of their own dataset when they need counting.
|
|
26
|
+
*/
|
|
27
|
+
export type DataFieldType = 'string' | 'number' | 'boolean' | 'date' | 'enum' | 'list';
|
|
28
|
+
/**
|
|
29
|
+
* The aggregate functions a query may ask for.
|
|
30
|
+
*
|
|
31
|
+
* `count` with no field counts rows; with a field it counts the rows where that
|
|
32
|
+
* field is present. `countDistinct` counts the field's different values — "how
|
|
33
|
+
* many carriers", where one carrier appears on several rows.
|
|
34
|
+
*/
|
|
35
|
+
export type DataAggregateFn = 'count' | 'countDistinct' | 'sum' | 'avg' | 'min' | 'max';
|
|
22
36
|
/**
|
|
23
37
|
* How a filter compares a field to a value.
|
|
24
38
|
*
|
|
@@ -26,7 +40,15 @@ export type DataAggregateFn = 'count' | 'sum' | 'avg' | 'min' | 'max';
|
|
|
26
40
|
* and nothing here can express a subquery, a join the host did not declare, or
|
|
27
41
|
* a raw expression.
|
|
28
42
|
*/
|
|
29
|
-
export type DataFilterOp = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'in' | 'contains' | 'between' | 'isNull' | 'notNull'
|
|
43
|
+
export type DataFilterOp = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'in' | 'contains' | 'between' | 'isNull' | 'notNull'
|
|
44
|
+
/** A `list` field holds this value. */
|
|
45
|
+
| 'has'
|
|
46
|
+
/** A `list` field holds at least one of these values. */
|
|
47
|
+
| 'hasAny'
|
|
48
|
+
/** A `list` field holds nothing. */
|
|
49
|
+
| 'isEmpty'
|
|
50
|
+
/** A `list` field holds something. */
|
|
51
|
+
| 'notEmpty';
|
|
30
52
|
/**
|
|
31
53
|
* One queryable field.
|
|
32
54
|
*
|
|
@@ -44,7 +66,10 @@ export interface DataField {
|
|
|
44
66
|
label?: string;
|
|
45
67
|
/** What the field means, and anything an agent would otherwise assume wrongly. */
|
|
46
68
|
description?: string;
|
|
47
|
-
/**
|
|
69
|
+
/**
|
|
70
|
+
* For `enum`, the values it may hold; for `list`, the values its members may
|
|
71
|
+
* be. Rendered into the guide and enforced on every filter value.
|
|
72
|
+
*/
|
|
48
73
|
enumValues?: string[];
|
|
49
74
|
/** May appear in `filters`. Default true. */
|
|
50
75
|
filterable?: boolean;
|
|
@@ -82,9 +107,24 @@ export interface DataSet {
|
|
|
82
107
|
export interface DataFilter {
|
|
83
108
|
field: string;
|
|
84
109
|
op: DataFilterOp;
|
|
85
|
-
/**
|
|
110
|
+
/**
|
|
111
|
+
* Omitted for `isNull`/`notNull`/`isEmpty`/`notEmpty`; an array for `in`,
|
|
112
|
+
* `hasAny` and `between`.
|
|
113
|
+
*/
|
|
86
114
|
value?: any;
|
|
87
115
|
}
|
|
116
|
+
/**
|
|
117
|
+
* One comparison on an aggregate's result — SQL's HAVING. `field` names a
|
|
118
|
+
* metric by its `as` name: "MGAs with more than five markets" is markets
|
|
119
|
+
* grouped by MGA, counted, and kept where the count is over five.
|
|
120
|
+
*/
|
|
121
|
+
export interface DataHaving {
|
|
122
|
+
/** A metric's `as` name. */
|
|
123
|
+
field: string;
|
|
124
|
+
op: 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'between';
|
|
125
|
+
/** A number, or `[low, high]` for `between`. */
|
|
126
|
+
value: any;
|
|
127
|
+
}
|
|
88
128
|
/** One aggregate in a query. */
|
|
89
129
|
export interface DataMetric {
|
|
90
130
|
fn: DataAggregateFn;
|
|
@@ -111,6 +151,11 @@ export interface DataQuery {
|
|
|
111
151
|
filters?: DataFilter[];
|
|
112
152
|
groupBy?: string[];
|
|
113
153
|
metrics?: DataMetric[];
|
|
154
|
+
/**
|
|
155
|
+
* Conditions on the metrics, applied after grouping. Only on an aggregate,
|
|
156
|
+
* and only naming a metric of this query.
|
|
157
|
+
*/
|
|
158
|
+
having?: DataHaving[];
|
|
114
159
|
/** Fields to return when this is a listing rather than an aggregate. */
|
|
115
160
|
select?: string[];
|
|
116
161
|
orderBy?: DataOrder[];
|
|
@@ -26,11 +26,20 @@ const OPS_BY_TYPE = {
|
|
|
26
26
|
string: ['eq', 'ne', 'in', 'contains', 'isNull', 'notNull'],
|
|
27
27
|
enum: ['eq', 'ne', 'in', 'isNull', 'notNull'],
|
|
28
28
|
boolean: ['eq', 'ne', 'isNull', 'notNull'],
|
|
29
|
+
list: ['has', 'hasAny', 'contains', 'isEmpty', 'notEmpty'],
|
|
29
30
|
};
|
|
30
31
|
/** Operators that take no value at all. */
|
|
31
|
-
const VALUELESS_OPS = ['isNull', 'notNull'];
|
|
32
|
+
const VALUELESS_OPS = ['isNull', 'notNull', 'isEmpty', 'notEmpty'];
|
|
33
|
+
/** Operators that take a list of values. */
|
|
34
|
+
const LIST_VALUE_OPS = ['in', 'hasAny'];
|
|
35
|
+
/** Every aggregate, in the order a refusal lists them. */
|
|
36
|
+
const AGGREGATES = ['count', 'countDistinct', 'sum', 'avg', 'min', 'max'];
|
|
32
37
|
/** Aggregates that need a numeric or date field to mean anything. */
|
|
33
38
|
const NUMERIC_AGGREGATES = ['sum', 'avg'];
|
|
39
|
+
/** How a `having` may compare a metric. */
|
|
40
|
+
const HAVING_OPS = ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'between'];
|
|
41
|
+
/** Aggregates whose result is always a number, so a `having` on one needs a number. */
|
|
42
|
+
const NUMBER_RESULT_AGGREGATES = ['count', 'countDistinct', 'sum', 'avg'];
|
|
34
43
|
function fail(error, available) {
|
|
35
44
|
return available ? { ok: false, error, available } : { ok: false, error };
|
|
36
45
|
}
|
|
@@ -76,8 +85,12 @@ function validateQuery(raw, sets) {
|
|
|
76
85
|
if (!field) {
|
|
77
86
|
return fail(`Cannot group by "${name}" — no such field in "${set.name}". Fields:`, fieldNames(set));
|
|
78
87
|
}
|
|
79
|
-
|
|
80
|
-
|
|
88
|
+
// A list holds several values on one row, so grouping by it has no
|
|
89
|
+
// single answer; its members are filtered, not grouped.
|
|
90
|
+
if (field.groupable === false || field.type === 'list') {
|
|
91
|
+
return fail(field.type === 'list'
|
|
92
|
+
? `Cannot group by "${name}" — it is a list, so one row holds several values. Filter it with has or hasAny instead. Groupable fields:`
|
|
93
|
+
: `Cannot group by "${name}". Groupable fields:`, set.fields.filter((f) => f.groupable !== false && f.type !== 'list').map((f) => f.name));
|
|
81
94
|
}
|
|
82
95
|
groupBy.push(field.name);
|
|
83
96
|
}
|
|
@@ -115,6 +128,14 @@ function validateQuery(raw, sets) {
|
|
|
115
128
|
}
|
|
116
129
|
orderBy.push({ by, dir: dir });
|
|
117
130
|
}
|
|
131
|
+
const having = [];
|
|
132
|
+
for (const rawHaving of asArray(raw.having)) {
|
|
133
|
+
const checked = validateHaving(rawHaving, metrics, isAggregate);
|
|
134
|
+
if ('error' in checked) {
|
|
135
|
+
return checked.error;
|
|
136
|
+
}
|
|
137
|
+
having.push(checked.having);
|
|
138
|
+
}
|
|
118
139
|
return {
|
|
119
140
|
ok: true,
|
|
120
141
|
dataset: set,
|
|
@@ -123,6 +144,7 @@ function validateQuery(raw, sets) {
|
|
|
123
144
|
filters,
|
|
124
145
|
groupBy,
|
|
125
146
|
metrics,
|
|
147
|
+
having,
|
|
126
148
|
select,
|
|
127
149
|
orderBy,
|
|
128
150
|
limit: resolveLimit(raw.limit, set),
|
|
@@ -172,12 +194,12 @@ function validateFilter(raw, set) {
|
|
|
172
194
|
if (raw.value === undefined || raw.value === null) {
|
|
173
195
|
return { error: fail(`Filter on "${field.name}" with "${op}" needs a value.`) };
|
|
174
196
|
}
|
|
175
|
-
if (op
|
|
197
|
+
if (LIST_VALUE_OPS.includes(op)) {
|
|
176
198
|
const values = asArray(raw.value);
|
|
177
199
|
if (values.length === 0) {
|
|
178
|
-
return { error: fail(`Filter on "${field.name}" with "
|
|
200
|
+
return { error: fail(`Filter on "${field.name}" with "${op}" needs a non-empty list of values.`) };
|
|
179
201
|
}
|
|
180
|
-
const bad = enumViolation(field, values);
|
|
202
|
+
const bad = enumViolation(field, values, op);
|
|
181
203
|
if (bad) {
|
|
182
204
|
return { error: bad };
|
|
183
205
|
}
|
|
@@ -192,15 +214,19 @@ function validateFilter(raw, set) {
|
|
|
192
214
|
}
|
|
193
215
|
return { filter: { field: field.name, op, value: values } };
|
|
194
216
|
}
|
|
195
|
-
const bad = enumViolation(field, [raw.value]);
|
|
217
|
+
const bad = enumViolation(field, [raw.value], op);
|
|
196
218
|
if (bad) {
|
|
197
219
|
return { error: bad };
|
|
198
220
|
}
|
|
199
221
|
return { filter: { field: field.name, op, value: raw.value } };
|
|
200
222
|
}
|
|
201
|
-
/**
|
|
202
|
-
|
|
203
|
-
|
|
223
|
+
/**
|
|
224
|
+
* Enum fields — and list fields that declare their members — accept only what
|
|
225
|
+
* they declared, so a typo is caught here rather than matching nothing. A
|
|
226
|
+
* `contains` value is a fragment, not a member, so it is not checked.
|
|
227
|
+
*/
|
|
228
|
+
function enumViolation(field, values, op) {
|
|
229
|
+
if ((field.type !== 'enum' && field.type !== 'list') || !field.enumValues?.length || op === 'contains') {
|
|
204
230
|
return null;
|
|
205
231
|
}
|
|
206
232
|
for (const value of values) {
|
|
@@ -215,9 +241,9 @@ function validateMetric(raw, set) {
|
|
|
215
241
|
return { error: fail('Each metric must be an object of {fn, field}.') };
|
|
216
242
|
}
|
|
217
243
|
const fn = String(raw.fn ?? '');
|
|
218
|
-
if (!
|
|
244
|
+
if (!AGGREGATES.includes(fn)) {
|
|
219
245
|
return {
|
|
220
|
-
error: fail(`Unknown aggregate "${raw.fn}". Available:`,
|
|
246
|
+
error: fail(`Unknown aggregate "${raw.fn}". Available:`, AGGREGATES),
|
|
221
247
|
};
|
|
222
248
|
}
|
|
223
249
|
// `count` alone counts rows, which needs no field and is always allowed.
|
|
@@ -230,6 +256,11 @@ function validateMetric(raw, set) {
|
|
|
230
256
|
error: fail(`Cannot ${fn} "${raw.field}" — no such field in "${set.name}". Fields:`, fieldNames(set)),
|
|
231
257
|
};
|
|
232
258
|
}
|
|
259
|
+
if (field.type === 'list') {
|
|
260
|
+
return {
|
|
261
|
+
error: fail(`Cannot ${fn} "${field.name}" — it is a list. Filter it with has or hasAny, and count the rows that match.`),
|
|
262
|
+
};
|
|
263
|
+
}
|
|
233
264
|
if (!field.aggregates?.includes(fn)) {
|
|
234
265
|
const capable = set.fields.filter((f) => f.aggregates?.includes(fn)).map((f) => f.name);
|
|
235
266
|
return {
|
|
@@ -243,3 +274,45 @@ function validateMetric(raw, set) {
|
|
|
243
274
|
}
|
|
244
275
|
return { metric: { fn, field: field.name, as: metricName(fn, field.name, raw.as) } };
|
|
245
276
|
}
|
|
277
|
+
/**
|
|
278
|
+
* A condition on an aggregate's result. It names one of this query's own
|
|
279
|
+
* metrics, not a field, because it applies after grouping — to the numbers the
|
|
280
|
+
* grouping produced. A plain listing has no such numbers, and its condition
|
|
281
|
+
* belongs in `filters`.
|
|
282
|
+
*/
|
|
283
|
+
function validateHaving(raw, metrics, isAggregate) {
|
|
284
|
+
if (!isAggregate) {
|
|
285
|
+
return {
|
|
286
|
+
error: fail('"having" filters the result of an aggregate. Add the metric it compares (and usually a groupBy), or put the condition in "filters".'),
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
if (!raw || typeof raw !== 'object') {
|
|
290
|
+
return { error: fail('Each having must be an object of {field, op, value}, naming a metric by its "as".') };
|
|
291
|
+
}
|
|
292
|
+
const name = String(raw.field ?? '');
|
|
293
|
+
const metric = metrics.find((candidate) => candidate.as === name);
|
|
294
|
+
if (!metric) {
|
|
295
|
+
return {
|
|
296
|
+
error: metrics.length
|
|
297
|
+
? fail(`Cannot apply having to "${name}" — it must name one of this query's metrics:`, metrics.map((m) => m.as))
|
|
298
|
+
: fail(`Cannot apply having to "${name}" — this query has no metrics. Add one, e.g. {"fn": "count", "as": "count"}.`),
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
const op = String(raw.op ?? '');
|
|
302
|
+
if (!HAVING_OPS.includes(op)) {
|
|
303
|
+
return { error: fail(`Operator "${raw.op}" cannot compare a metric. Allowed:`, HAVING_OPS) };
|
|
304
|
+
}
|
|
305
|
+
const values = op === 'between' ? asArray(raw.value) : [raw.value];
|
|
306
|
+
if (op === 'between' && values.length !== 2) {
|
|
307
|
+
return { error: fail(`Having on "${name}" with "between" needs exactly two values: [low, high].`) };
|
|
308
|
+
}
|
|
309
|
+
if (values.some((value) => value === undefined || value === null || value === '')) {
|
|
310
|
+
return { error: fail(`Having on "${name}" with "${op}" needs a value.`) };
|
|
311
|
+
}
|
|
312
|
+
const numeric = NUMBER_RESULT_AGGREGATES.includes(metric.fn);
|
|
313
|
+
if (numeric && values.some((value) => !Number.isFinite(Number(value)))) {
|
|
314
|
+
return { error: fail(`Having on "${name}" compares a ${metric.fn}, so its value must be a number.`) };
|
|
315
|
+
}
|
|
316
|
+
const typed = numeric ? values.map(Number) : values;
|
|
317
|
+
return { having: { field: name, op, value: op === 'between' ? typed : typed[0] } };
|
|
318
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs a validated query over rows a host already holds.
|
|
3
|
+
*
|
|
4
|
+
* Most hosts answer {@link DataSource.execute} by building a statement for their
|
|
5
|
+
* database. Some datasets are better served from memory: data assembled from
|
|
6
|
+
* several tables, from a code registry, or from another service; per-row facts
|
|
7
|
+
* that are awkward in SQL (a count of related records, a list of names); or a
|
|
8
|
+
* set small enough that a statement is not worth writing. A host builds the rows
|
|
9
|
+
* — one plain object per record, keyed by the dataset's field names — and hands
|
|
10
|
+
* them here with the validated query. Every host then gets the same semantics
|
|
11
|
+
* for filters, grouping, metrics, `having`, ordering and limits, instead of each
|
|
12
|
+
* re-implementing them slightly differently.
|
|
13
|
+
*
|
|
14
|
+
* Semantics, chosen to match what a SQL executor would answer:
|
|
15
|
+
* - A missing value (`null`/`undefined`) fails every comparison, `ne` included;
|
|
16
|
+
* only `isNull` matches it. A host should store "nothing" as `null`, not `''`.
|
|
17
|
+
* - Text compares case-insensitively and ignores surrounding spaces, as a person
|
|
18
|
+
* asking "carriers named sentry" means.
|
|
19
|
+
* - A `list` field holds an array of strings; `null` reads as an empty list.
|
|
20
|
+
* - `count` with a field counts rows where it is present; `sum`/`avg`/`min`/`max`
|
|
21
|
+
* skip missing values and are `null` when nothing is left — SQL's answer.
|
|
22
|
+
* - Missing values sort last in either direction, so "top 10" is never ten blanks.
|
|
23
|
+
*
|
|
24
|
+
* The query must have come from `validateQuery`: nothing here re-checks names.
|
|
25
|
+
*/
|
|
26
|
+
import { DataQuery, DataResult, DataRow, DataSet } from './data.types';
|
|
27
|
+
/**
|
|
28
|
+
* @param query A query `validateQuery` accepted for this dataset
|
|
29
|
+
* @param set The dataset the query names
|
|
30
|
+
* @param rows Every row of the dataset the caller may see — already scoped to
|
|
31
|
+
* the tenant or user; this function applies the query and nothing else
|
|
32
|
+
* @returns The answer, with `totalRows` counting rows (a listing) or groups (an
|
|
33
|
+
* aggregate) before the limit
|
|
34
|
+
*/
|
|
35
|
+
export declare function queryRows(query: DataQuery, set: DataSet, rows: DataRow[]): DataResult;
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.queryRows = queryRows;
|
|
4
|
+
/**
|
|
5
|
+
* @param query A query `validateQuery` accepted for this dataset
|
|
6
|
+
* @param set The dataset the query names
|
|
7
|
+
* @param rows Every row of the dataset the caller may see — already scoped to
|
|
8
|
+
* the tenant or user; this function applies the query and nothing else
|
|
9
|
+
* @returns The answer, with `totalRows` counting rows (a listing) or groups (an
|
|
10
|
+
* aggregate) before the limit
|
|
11
|
+
*/
|
|
12
|
+
function queryRows(query, set, rows) {
|
|
13
|
+
const fields = new Map(set.fields.map((field) => [field.name, field]));
|
|
14
|
+
const filtered = rows.filter((row) => (query.filters || []).every((filter) => matchesFilter(row[filter.field], filter, fields.get(filter.field))));
|
|
15
|
+
const isAggregate = (query.groupBy?.length || 0) > 0 || (query.metrics?.length || 0) > 0;
|
|
16
|
+
if (!isAggregate) {
|
|
17
|
+
const wanted = query.select?.length ? query.select : set.fields.map((field) => field.name);
|
|
18
|
+
const ordered = sortRows(filtered, query, (name) => fields.get(name)?.type);
|
|
19
|
+
return {
|
|
20
|
+
rows: limitRows(ordered, query.limit).map((row) => project(row, wanted)),
|
|
21
|
+
totalRows: filtered.length,
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
const groupBy = query.groupBy || [];
|
|
25
|
+
const metrics = query.metrics || [];
|
|
26
|
+
const groups = new Map();
|
|
27
|
+
if (groupBy.length === 0) {
|
|
28
|
+
// No dimensions: one answer over everything, even when nothing matched —
|
|
29
|
+
// "how many" over zero rows is 0, not no answer.
|
|
30
|
+
groups.set('', filtered);
|
|
31
|
+
}
|
|
32
|
+
for (const row of groupBy.length ? filtered : []) {
|
|
33
|
+
const key = JSON.stringify(groupBy.map((name) => groupKey(row[name])));
|
|
34
|
+
const members = groups.get(key);
|
|
35
|
+
if (members) {
|
|
36
|
+
members.push(row);
|
|
37
|
+
}
|
|
38
|
+
else {
|
|
39
|
+
groups.set(key, [row]);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const outputs = [];
|
|
43
|
+
for (const members of groups.values()) {
|
|
44
|
+
const out = {};
|
|
45
|
+
for (const name of groupBy) {
|
|
46
|
+
out[name] = members[0]?.[name] ?? null;
|
|
47
|
+
}
|
|
48
|
+
for (const metric of metrics) {
|
|
49
|
+
out[metric.as] = aggregate(metric.fn, metric.field, members, metric.field ? fields.get(metric.field) : undefined);
|
|
50
|
+
}
|
|
51
|
+
outputs.push(out);
|
|
52
|
+
}
|
|
53
|
+
const metricTypes = new Map(metrics.map((metric) => [
|
|
54
|
+
metric.as,
|
|
55
|
+
metric.fn === 'min' || metric.fn === 'max' ? fields.get(metric.field)?.type : 'number',
|
|
56
|
+
]));
|
|
57
|
+
const kept = outputs.filter((out) => (query.having || []).every((having) => matchesHaving(out[having.field], having, metricTypes.get(having.field))));
|
|
58
|
+
const typeOf = (name) => metricTypes.get(name) ?? fields.get(name)?.type;
|
|
59
|
+
const ordered = sortRows(kept, query, typeOf);
|
|
60
|
+
return { rows: limitRows(ordered, query.limit), totalRows: kept.length };
|
|
61
|
+
}
|
|
62
|
+
// ---- filters ---------------------------------------------------------------
|
|
63
|
+
function isMissing(value) {
|
|
64
|
+
return value === null || value === undefined;
|
|
65
|
+
}
|
|
66
|
+
function text(value) {
|
|
67
|
+
return String(value).trim().toLowerCase();
|
|
68
|
+
}
|
|
69
|
+
function asList(value) {
|
|
70
|
+
if (isMissing(value)) {
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
return Array.isArray(value) ? value.filter((item) => !isMissing(item)) : [value];
|
|
74
|
+
}
|
|
75
|
+
function toBoolean(value) {
|
|
76
|
+
if (value === true || value === false) {
|
|
77
|
+
return value;
|
|
78
|
+
}
|
|
79
|
+
const lower = String(value).trim().toLowerCase();
|
|
80
|
+
if (['true', 'yes', '1'].includes(lower)) {
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
if (['false', 'no', '0'].includes(lower)) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
/** A date as epoch milliseconds, or NaN. */
|
|
89
|
+
function toTime(value) {
|
|
90
|
+
if (value instanceof Date) {
|
|
91
|
+
return value.getTime();
|
|
92
|
+
}
|
|
93
|
+
if (typeof value === 'number') {
|
|
94
|
+
return value;
|
|
95
|
+
}
|
|
96
|
+
return Date.parse(String(value));
|
|
97
|
+
}
|
|
98
|
+
/** A date's calendar day, for equality — a stored midnight equals "2024-05-01". */
|
|
99
|
+
function toDay(value) {
|
|
100
|
+
const time = toTime(value);
|
|
101
|
+
return Number.isNaN(time) ? '' : new Date(time).toISOString().slice(0, 10);
|
|
102
|
+
}
|
|
103
|
+
/** Orders two present values of a field type; negative when `a` comes first. */
|
|
104
|
+
function compareValues(a, b, type) {
|
|
105
|
+
if (type === 'number' || (typeof a === 'number' && typeof b === 'number')) {
|
|
106
|
+
return Number(a) - Number(b);
|
|
107
|
+
}
|
|
108
|
+
if (type === 'date') {
|
|
109
|
+
return toTime(a) - toTime(b);
|
|
110
|
+
}
|
|
111
|
+
if (type === 'boolean') {
|
|
112
|
+
return Number(toBoolean(a)) - Number(toBoolean(b));
|
|
113
|
+
}
|
|
114
|
+
return String(a).localeCompare(String(b), undefined, { sensitivity: 'base', numeric: true });
|
|
115
|
+
}
|
|
116
|
+
function equals(a, b, type) {
|
|
117
|
+
switch (type) {
|
|
118
|
+
case 'number':
|
|
119
|
+
return Number(a) === Number(b);
|
|
120
|
+
case 'date':
|
|
121
|
+
return toDay(a) !== '' && toDay(a) === toDay(b);
|
|
122
|
+
case 'boolean':
|
|
123
|
+
return toBoolean(a) !== null && toBoolean(a) === toBoolean(b);
|
|
124
|
+
default:
|
|
125
|
+
return text(a) === text(b);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function matchesFilter(value, filter, field) {
|
|
129
|
+
const type = field?.type;
|
|
130
|
+
if (type === 'list') {
|
|
131
|
+
const items = asList(value);
|
|
132
|
+
switch (filter.op) {
|
|
133
|
+
case 'has':
|
|
134
|
+
return items.some((item) => text(item) === text(filter.value));
|
|
135
|
+
case 'hasAny':
|
|
136
|
+
return filter.value.some((wanted) => items.some((item) => text(item) === text(wanted)));
|
|
137
|
+
case 'contains':
|
|
138
|
+
return items.some((item) => text(item).includes(text(filter.value)));
|
|
139
|
+
case 'isEmpty':
|
|
140
|
+
return items.length === 0;
|
|
141
|
+
case 'notEmpty':
|
|
142
|
+
return items.length > 0;
|
|
143
|
+
default:
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (filter.op === 'isNull') {
|
|
148
|
+
return isMissing(value);
|
|
149
|
+
}
|
|
150
|
+
if (filter.op === 'notNull') {
|
|
151
|
+
return !isMissing(value);
|
|
152
|
+
}
|
|
153
|
+
if (isMissing(value)) {
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
switch (filter.op) {
|
|
157
|
+
case 'eq':
|
|
158
|
+
return equals(value, filter.value, type);
|
|
159
|
+
case 'ne':
|
|
160
|
+
return !equals(value, filter.value, type);
|
|
161
|
+
case 'in':
|
|
162
|
+
return filter.value.some((wanted) => equals(value, wanted, type));
|
|
163
|
+
case 'contains':
|
|
164
|
+
return text(value).includes(text(filter.value));
|
|
165
|
+
case 'lt':
|
|
166
|
+
return compareValues(value, filter.value, type) < 0;
|
|
167
|
+
case 'lte':
|
|
168
|
+
return compareValues(value, filter.value, type) <= 0;
|
|
169
|
+
case 'gt':
|
|
170
|
+
return compareValues(value, filter.value, type) > 0;
|
|
171
|
+
case 'gte':
|
|
172
|
+
return compareValues(value, filter.value, type) >= 0;
|
|
173
|
+
case 'between': {
|
|
174
|
+
const [low, high] = filter.value;
|
|
175
|
+
return compareValues(value, low, type) >= 0 && compareValues(value, high, type) <= 0;
|
|
176
|
+
}
|
|
177
|
+
default:
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function matchesHaving(value, having, type) {
|
|
182
|
+
if (isMissing(value)) {
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
switch (having.op) {
|
|
186
|
+
case 'eq':
|
|
187
|
+
return compareValues(value, having.value, type) === 0;
|
|
188
|
+
case 'ne':
|
|
189
|
+
return compareValues(value, having.value, type) !== 0;
|
|
190
|
+
case 'lt':
|
|
191
|
+
return compareValues(value, having.value, type) < 0;
|
|
192
|
+
case 'lte':
|
|
193
|
+
return compareValues(value, having.value, type) <= 0;
|
|
194
|
+
case 'gt':
|
|
195
|
+
return compareValues(value, having.value, type) > 0;
|
|
196
|
+
case 'gte':
|
|
197
|
+
return compareValues(value, having.value, type) >= 0;
|
|
198
|
+
case 'between': {
|
|
199
|
+
const [low, high] = having.value;
|
|
200
|
+
return compareValues(value, low, type) >= 0 && compareValues(value, high, type) <= 0;
|
|
201
|
+
}
|
|
202
|
+
default:
|
|
203
|
+
return false;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
// ---- aggregation -----------------------------------------------------------
|
|
207
|
+
/** Groups by exact value, as SQL does; a Date by its instant. */
|
|
208
|
+
function groupKey(value) {
|
|
209
|
+
if (isMissing(value)) {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
return value instanceof Date ? value.toISOString() : value;
|
|
213
|
+
}
|
|
214
|
+
function aggregate(fn, name, rows, field) {
|
|
215
|
+
if (fn === 'count' && !name) {
|
|
216
|
+
return rows.length;
|
|
217
|
+
}
|
|
218
|
+
const present = rows.map((row) => row[name]).filter((value) => !isMissing(value));
|
|
219
|
+
switch (fn) {
|
|
220
|
+
case 'count':
|
|
221
|
+
return present.length;
|
|
222
|
+
case 'countDistinct':
|
|
223
|
+
return new Set(present.map((value) => JSON.stringify(groupKey(value)))).size;
|
|
224
|
+
case 'sum':
|
|
225
|
+
return present.length ? present.reduce((total, value) => total + Number(value), 0) : null;
|
|
226
|
+
case 'avg':
|
|
227
|
+
return present.length ? present.reduce((total, value) => total + Number(value), 0) / present.length : null;
|
|
228
|
+
case 'min':
|
|
229
|
+
case 'max': {
|
|
230
|
+
if (!present.length) {
|
|
231
|
+
return null;
|
|
232
|
+
}
|
|
233
|
+
const sign = fn === 'min' ? -1 : 1;
|
|
234
|
+
return present.reduce((best, value) => sign * compareValues(value, best, field?.type) > 0 ? value : best);
|
|
235
|
+
}
|
|
236
|
+
default:
|
|
237
|
+
return null;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
// ---- ordering and shaping --------------------------------------------------
|
|
241
|
+
function sortRows(rows, query, typeOf) {
|
|
242
|
+
const orders = query.orderBy || [];
|
|
243
|
+
if (orders.length === 0) {
|
|
244
|
+
return rows;
|
|
245
|
+
}
|
|
246
|
+
return [...rows].sort((a, b) => {
|
|
247
|
+
for (const order of orders) {
|
|
248
|
+
const left = a[order.by];
|
|
249
|
+
const right = b[order.by];
|
|
250
|
+
// Missing values last in either direction.
|
|
251
|
+
if (isMissing(left) || isMissing(right)) {
|
|
252
|
+
if (isMissing(left) && isMissing(right)) {
|
|
253
|
+
continue;
|
|
254
|
+
}
|
|
255
|
+
return isMissing(left) ? 1 : -1;
|
|
256
|
+
}
|
|
257
|
+
const cmp = compareValues(left, right, typeOf(order.by));
|
|
258
|
+
if (cmp !== 0) {
|
|
259
|
+
return order.dir === 'desc' ? -cmp : cmp;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
return 0;
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
function limitRows(rows, limit) {
|
|
266
|
+
return limit && limit > 0 ? rows.slice(0, limit) : rows;
|
|
267
|
+
}
|
|
268
|
+
function project(row, names) {
|
|
269
|
+
const out = {};
|
|
270
|
+
for (const name of names) {
|
|
271
|
+
out[name] = row[name] ?? null;
|
|
272
|
+
}
|
|
273
|
+
return out;
|
|
274
|
+
}
|
|
@@ -662,6 +662,14 @@ export declare class Room {
|
|
|
662
662
|
* paused/adjourned mid-turn
|
|
663
663
|
*/
|
|
664
664
|
private runAgentTurn;
|
|
665
|
+
/**
|
|
666
|
+
* Whether a response that would end a turn carries no words. A thought may
|
|
667
|
+
* be empty — nobody hears it — and a tool call or a publish is not a reply;
|
|
668
|
+
* anything else with nothing in it would be delivered as silence.
|
|
669
|
+
* @param response The agent's parsed response
|
|
670
|
+
* @returns True when the reply would say nothing
|
|
671
|
+
*/
|
|
672
|
+
private static isEmptyReply;
|
|
665
673
|
/**
|
|
666
674
|
* Runs a tool for an agent's EXECUTE message and returns the feedback string
|
|
667
675
|
* to add to the agent's history. Also logs a TOOL notice to the room so
|
|
@@ -1411,6 +1411,7 @@ class Room {
|
|
|
1411
1411
|
const variables = await this.buildPerceiveVariables(agent);
|
|
1412
1412
|
let response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, heardMessage), variables);
|
|
1413
1413
|
const maxIterations = Room.maxToolIterations();
|
|
1414
|
+
let emptyReplyReturned = false;
|
|
1414
1415
|
for (let i = 0; i < maxIterations; i++) {
|
|
1415
1416
|
if (this.isPaused || this.isAdjourned)
|
|
1416
1417
|
return null;
|
|
@@ -1426,6 +1427,22 @@ class Room {
|
|
|
1426
1427
|
else if (opts.inCommission && response.action === app_types_1.MessageAction.COMMISSION) {
|
|
1427
1428
|
feedback = `From system: Nested commissions are not permitted. Complete your own task and respond with action "deliver".`;
|
|
1428
1429
|
}
|
|
1430
|
+
else if (!emptyReplyReturned && Room.isEmptyReply(response)) {
|
|
1431
|
+
// A reply with no words in it. Delivered, it reaches its listener as
|
|
1432
|
+
// nothing: a specialist whose two queries both came back empty sent
|
|
1433
|
+
// its room leader an empty whisper, the leader thought "still
|
|
1434
|
+
// waiting", and the person who asked watched "working" forever.
|
|
1435
|
+
// The moderator cannot help — it can route a message, not write one.
|
|
1436
|
+
// So it goes back to its author once, the way a tool result does,
|
|
1437
|
+
// and a second empty reply is let through as before rather than
|
|
1438
|
+
// looping.
|
|
1439
|
+
emptyReplyReturned = true;
|
|
1440
|
+
const to = heardMessage?.getSender();
|
|
1441
|
+
feedback =
|
|
1442
|
+
'From system: Your reply had no text, so nobody would hear anything. Respond now' +
|
|
1443
|
+
(to ? ` to ${to}` : '') +
|
|
1444
|
+
' with your answer. If what you found is nothing, say that plainly — "none" is an answer.';
|
|
1445
|
+
}
|
|
1429
1446
|
else {
|
|
1430
1447
|
if (!opts.inCommission && response.action === app_types_1.MessageAction.DELIVER) {
|
|
1431
1448
|
// Stray DELIVER outside a commission: degrade to a normal SPEAK
|
|
@@ -1476,6 +1493,24 @@ class Room {
|
|
|
1476
1493
|
}
|
|
1477
1494
|
return response;
|
|
1478
1495
|
}
|
|
1496
|
+
/**
|
|
1497
|
+
* Whether a response that would end a turn carries no words. A thought may
|
|
1498
|
+
* be empty — nobody hears it — and a tool call or a publish is not a reply;
|
|
1499
|
+
* anything else with nothing in it would be delivered as silence.
|
|
1500
|
+
* @param response The agent's parsed response
|
|
1501
|
+
* @returns True when the reply would say nothing
|
|
1502
|
+
*/
|
|
1503
|
+
static isEmptyReply(response) {
|
|
1504
|
+
const silentActions = [
|
|
1505
|
+
app_types_1.MessageAction.THINK,
|
|
1506
|
+
app_types_1.MessageAction.EXECUTE,
|
|
1507
|
+
app_types_1.MessageAction.PUBLISH,
|
|
1508
|
+
app_types_1.MessageAction.ADJOURN,
|
|
1509
|
+
];
|
|
1510
|
+
if (silentActions.includes(response.action))
|
|
1511
|
+
return false;
|
|
1512
|
+
return !response.content || !String(response.content).trim();
|
|
1513
|
+
}
|
|
1479
1514
|
/**
|
|
1480
1515
|
* Runs a tool for an agent's EXECUTE message and returns the feedback string
|
|
1481
1516
|
* to add to the agent's history. Also logs a TOOL notice to the room so
|
|
@@ -219,6 +219,12 @@ class Briyah {
|
|
|
219
219
|
*/
|
|
220
220
|
static ALWAYS_REFRESH_FILES = [
|
|
221
221
|
'config/model_prices.json',
|
|
222
|
+
// Our own capability facts about the models in that table, such as which
|
|
223
|
+
// ones accept the filtering web-search tool. Package-canonical for the same
|
|
224
|
+
// reason the table is -- they describe a provider API this version of the
|
|
225
|
+
// code calls, a host has model_prices.local.json for overrides, and a stale
|
|
226
|
+
// copy downgrades or breaks a request rather than announcing itself.
|
|
227
|
+
'config/model_prices.annotations.json',
|
|
222
228
|
// The curated image-model catalog. Model availability changes on the
|
|
223
229
|
// provider side (models get removed/renamed), so a stale copy points
|
|
224
230
|
// agents at dead models. Kept package-canonical; hosts needing a custom
|