briyah 2.0.8 → 2.0.9

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.
@@ -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
@@ -19,10 +19,11 @@ export type { NativeToolDefinition, ToolHelpers, ToolContext, ToolCaller, ToolAr
19
19
  export { dnd5eTools } from '../tools/packs/dnd5e';
20
20
  export { installToolPacks, registerToolPacks, availableToolPacks } from '../tools/packs';
21
21
  export { NativeToolRegistry } from '../tools/native-tool-registry.service';
22
- export type { DataSource, DataSet, DataField, DataFieldType, DataAggregateFn, DataFilter, DataFilterOp, DataMetric, DataOrder, DataQuery, DataRow, DataResult, } from '../data/data.types';
22
+ export type { DataSource, DataSet, DataField, DataFieldType, DataAggregateFn, DataFilter, DataFilterOp, DataHaving, DataMetric, DataOrder, DataQuery, DataRow, DataResult, } from '../data/data.types';
23
23
  export { DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT } from '../data/data.types';
24
24
  export { registerDataSource, unregisterDataSource, listDataSources, listDatasets, } from '../data/data-registry';
25
25
  export { buildDataGuideMarkdown } from '../data/data-guide.builder';
26
+ export { queryRows } from '../data/row-executor';
26
27
  export { PackService } from '../packs/pack.service';
27
28
  export type { PackView } from '../packs/pack.service';
28
29
  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.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.libraryDocumentIdOf = exports.isLibraryAttachment = exports.libraryAttachmentName = exports.DEFAULT_EMBEDDING_MODEL = exports.EMBEDDING_DIMENSIONS = exports.embedTexts = exports.DEFAULT_CHUNK_OVERLAP_CHARS = exports.DEFAULT_CHUNK_MAX_CHARS = exports.embeddingInput = exports.chunkPages = exports.buildDocumentGuideMarkdown = exports.listDocumentSources = exports.unregisterDocumentSource = exports.registerDocumentSource = exports.UnsupportedDocumentError = exports.convertLocalDocument = exports.detectDocumentType = exports.BriyahConfigService = exports.Briyah = void 0;
3
+ exports.RoomMessage = exports.Room = exports.Agent = exports.PackInstantiationService = exports.PackService = exports.queryRows = 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.libraryDocumentIdOf = exports.isLibraryAttachment = exports.libraryAttachmentName = exports.DEFAULT_EMBEDDING_MODEL = exports.EMBEDDING_DIMENSIONS = exports.embedTexts = exports.DEFAULT_CHUNK_OVERLAP_CHARS = exports.DEFAULT_CHUNK_MAX_CHARS = exports.embeddingInput = exports.chunkPages = exports.buildDocumentGuideMarkdown = exports.listDocumentSources = exports.unregisterDocumentSource = exports.registerDocumentSource = exports.UnsupportedDocumentError = exports.convertLocalDocument = exports.detectDocumentType = 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; } });
@@ -69,6 +69,13 @@ Object.defineProperty(exports, "listDataSources", { enumerable: true, get: funct
69
69
  Object.defineProperty(exports, "listDatasets", { enumerable: true, get: function () { return data_registry_1.listDatasets; } });
70
70
  var data_guide_builder_1 = require("../data/data-guide.builder");
71
71
  Object.defineProperty(exports, "buildDataGuideMarkdown", { enumerable: true, get: function () { return data_guide_builder_1.buildDataGuideMarkdown; } });
72
+ // For a dataset the host serves from rows it built itself — assembled from
73
+ // several tables, a code registry or another service, or small enough not to
74
+ // need a statement: the host's execute() builds the rows and returns
75
+ // queryRows(query, set, rows), getting the same filter, grouping, having and
76
+ // ordering semantics as every other host.
77
+ var row_executor_1 = require("../data/row-executor");
78
+ Object.defineProperty(exports, "queryRows", { enumerable: true, get: function () { return row_executor_1.queryRows; } });
72
79
  // Packs: a domain's prompt folders, documents, tools and templates, installed for
73
80
  // everyone and enabled per user.
74
81
  //
@@ -80,6 +80,8 @@ exports.queryDataTool = {
80
80
  QUERY_EXAMPLE +
81
81
  ' — listing example: ' +
82
82
  LIST_EXAMPLE +
83
+ ' To keep only some groups, add "having": conditions on the query\'s own metrics by ' +
84
+ 'their "as", e.g. "having": [{"field": "sum_incurred", "op": "gt", "value": 100000}].' +
83
85
  ' Only the datasets and fields in your data guide exist; if a question needs ' +
84
86
  'something that is not there, say so rather than substituting a field that looks close.',
85
87
  parameters: [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "briyah",
3
- "version": "2.0.8",
3
+ "version": "2.0.9",
4
4
  "description": "SDK for AI agents, multi-agent rooms, interactive stories, and role-playing games with per-user data isolation and cost tracking",
5
5
  "private": false,
6
6
  "license": "Apache-2.0",