briyah 2.0.17 → 2.0.19
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/dist-sdk/server/src/ai/agent-config.d.ts +4 -0
- package/dist-sdk/server/src/ai/agent-store.service.js +4 -0
- package/dist-sdk/server/src/ai/agent.d.ts +7 -0
- package/dist-sdk/server/src/ai/agent.js +7 -0
- package/dist-sdk/server/src/app/balance.service.js +1 -1
- package/dist-sdk/server/src/app/usage-context.d.ts +19 -1
- package/dist-sdk/server/src/app/usage-context.js +21 -4
- package/dist-sdk/server/src/app.service.d.ts +2 -0
- package/dist-sdk/server/src/app.service.js +2 -0
- package/dist-sdk/server/src/data/query-validation.d.ts +9 -1
- package/dist-sdk/server/src/data/query-validation.js +9 -5
- package/dist-sdk/server/src/data/run-query.d.ts +14 -0
- package/dist-sdk/server/src/data/run-query.js +39 -0
- package/dist-sdk/server/src/documents/document-conversion.d.ts +27 -9
- package/dist-sdk/server/src/documents/document-conversion.js +131 -10
- package/dist-sdk/server/src/documents/html-data.d.ts +49 -0
- package/dist-sdk/server/src/documents/html-data.js +120 -0
- package/dist-sdk/server/src/documents/html-template.d.ts +108 -0
- package/dist-sdk/server/src/documents/html-template.js +332 -0
- package/dist-sdk/server/src/documents/library/document.types.d.ts +64 -0
- package/dist-sdk/server/src/documents/library/document.types.js +6 -0
- package/dist-sdk/server/src/documents/library/html-template-guide.builder.d.ts +13 -0
- package/dist-sdk/server/src/documents/library/html-template-guide.builder.js +185 -0
- package/dist-sdk/server/src/documents/template-mapping.d.ts +203 -0
- package/dist-sdk/server/src/documents/template-mapping.js +452 -0
- package/dist-sdk/server/src/room/room.d.ts +2 -1
- package/dist-sdk/server/src/room/room.js +7 -3
- package/dist-sdk/server/src/sdk/index.d.ts +12 -3
- package/dist-sdk/server/src/sdk/index.js +28 -2
- package/dist-sdk/server/src/tools/core/document.tools.d.ts +22 -0
- package/dist-sdk/server/src/tools/core/document.tools.js +20 -6
- package/dist-sdk/server/src/tools/core/html-template.tools.d.ts +31 -0
- package/dist-sdk/server/src/tools/core/html-template.tools.js +494 -0
- package/dist-sdk/server/src/tools/core/index.js +2 -0
- package/package.json +1 -1
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isRowsChange = isRowsChange;
|
|
4
|
+
exports.isQueryValueChange = isQueryValueChange;
|
|
5
|
+
exports.isQueryBacked = isQueryBacked;
|
|
6
|
+
exports.resolveParams = resolveParams;
|
|
7
|
+
exports.paramNames = paramNames;
|
|
8
|
+
exports.parameterizeQuery = parameterizeQuery;
|
|
9
|
+
exports.parameterize = parameterize;
|
|
10
|
+
exports.materializeChange = materializeChange;
|
|
11
|
+
exports.isRecipeChange = isRecipeChange;
|
|
12
|
+
exports.buildRecipe = buildRecipe;
|
|
13
|
+
exports.wildcardPath = wildcardPath;
|
|
14
|
+
exports.expandWrittenPath = expandWrittenPath;
|
|
15
|
+
exports.coversPath = coversPath;
|
|
16
|
+
const html_data_1 = require("./html-data");
|
|
17
|
+
const html_template_1 = require("./html-template");
|
|
18
|
+
function isRowsChange(change) {
|
|
19
|
+
return !!change && typeof change === 'object' && 'rows' in change && 'each' in change;
|
|
20
|
+
}
|
|
21
|
+
function isQueryValueChange(change) {
|
|
22
|
+
return !!change && typeof change === 'object' && 'query' in change && 'take' in change;
|
|
23
|
+
}
|
|
24
|
+
/** Whether a change comes from a query rather than holding its value. */
|
|
25
|
+
function isQueryBacked(change) {
|
|
26
|
+
return isRowsChange(change) || isQueryValueChange(change);
|
|
27
|
+
}
|
|
28
|
+
function isParam(value) {
|
|
29
|
+
return !!value && typeof value === 'object' && !Array.isArray(value) && typeof value.$param === 'string' &&
|
|
30
|
+
Object.keys(value).length === 1;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* A copy with every `{"$param": name}` replaced by its value.
|
|
34
|
+
*
|
|
35
|
+
* @throws {TemplateError} Naming a parameter that was not given
|
|
36
|
+
*/
|
|
37
|
+
function resolveParams(value, parameters) {
|
|
38
|
+
if (isParam(value)) {
|
|
39
|
+
if (!(value.$param in parameters)) {
|
|
40
|
+
const given = Object.keys(parameters);
|
|
41
|
+
throw new html_template_1.TemplateError(`The parameter "${value.$param}" has no value. Pass it in parameters${given.length ? ` (given: ${given.join(', ')})` : ''}.`);
|
|
42
|
+
}
|
|
43
|
+
return parameters[value.$param];
|
|
44
|
+
}
|
|
45
|
+
if (Array.isArray(value))
|
|
46
|
+
return value.map((item) => resolveParams(item, parameters));
|
|
47
|
+
if (value && typeof value === 'object') {
|
|
48
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, resolveParams(item, parameters)]));
|
|
49
|
+
}
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
/** The names of every `$param` a value uses. */
|
|
53
|
+
function paramNames(value, into = new Set()) {
|
|
54
|
+
if (isParam(value))
|
|
55
|
+
into.add(value.$param);
|
|
56
|
+
else if (Array.isArray(value))
|
|
57
|
+
value.forEach((item) => paramNames(item, into));
|
|
58
|
+
else if (value && typeof value === 'object')
|
|
59
|
+
Object.values(value).forEach((item) => paramNames(item, into));
|
|
60
|
+
return into;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* A query with the values of the given parameters written back as `$param`s
|
|
64
|
+
* wherever they appear as a filter value — so a query made for one customer
|
|
65
|
+
* becomes one for any.
|
|
66
|
+
*/
|
|
67
|
+
function parameterizeQuery(spec, parameters) {
|
|
68
|
+
const entries = Object.entries(parameters).filter(([, value]) => typeof value === 'string' && value !== '');
|
|
69
|
+
if (!entries.length || !Array.isArray(spec?.filters))
|
|
70
|
+
return spec;
|
|
71
|
+
const asParam = (value) => {
|
|
72
|
+
if (typeof value === 'string') {
|
|
73
|
+
const match = entries.find(([, given]) => given === value);
|
|
74
|
+
return match ? { $param: match[0] } : value;
|
|
75
|
+
}
|
|
76
|
+
return Array.isArray(value) ? value.map(asParam) : value;
|
|
77
|
+
};
|
|
78
|
+
return {
|
|
79
|
+
...spec,
|
|
80
|
+
filters: spec.filters.map((filter) => (filter && typeof filter === 'object' ? { ...filter, value: asParam(filter.value) } : filter)),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** The change with its queries' parameter values written back as `$param`s (see {@link parameterizeQuery}). */
|
|
84
|
+
function parameterize(change, parameters) {
|
|
85
|
+
const query = (spec) => parameterizeQuery(spec, parameters);
|
|
86
|
+
const each = (spec) => Object.fromEntries(Object.entries(spec).map(([key, value]) => [
|
|
87
|
+
key,
|
|
88
|
+
value && typeof value === 'object' && 'rows' in value
|
|
89
|
+
? { ...value, rows: query(value.rows), ...(value.joins ? { joins: value.joins.map((join) => ({ ...join, rows: query(join.rows) })) } : {}), each: each(value.each) }
|
|
90
|
+
: value,
|
|
91
|
+
]));
|
|
92
|
+
if (isRowsChange(change)) {
|
|
93
|
+
return {
|
|
94
|
+
...change,
|
|
95
|
+
rows: query(change.rows),
|
|
96
|
+
...(change.joins ? { joins: change.joins.map((join) => ({ ...join, rows: query(join.rows) })) } : {}),
|
|
97
|
+
each: each(change.each),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
if (isQueryValueChange(change))
|
|
101
|
+
return { ...change, query: query(change.query) };
|
|
102
|
+
return change;
|
|
103
|
+
}
|
|
104
|
+
// ---------------------------------------------------------------------------
|
|
105
|
+
// Building values
|
|
106
|
+
// ---------------------------------------------------------------------------
|
|
107
|
+
function isEmpty(value) {
|
|
108
|
+
return value === null || value === undefined || value === '';
|
|
109
|
+
}
|
|
110
|
+
/** A key for matching two values: dates by their day, text case-insensitively. */
|
|
111
|
+
function matchKey(value) {
|
|
112
|
+
if (value instanceof Date)
|
|
113
|
+
return value.toISOString().slice(0, 10);
|
|
114
|
+
const text = String(value ?? '').trim();
|
|
115
|
+
return /^\d{4}-\d{2}-\d{2}/.test(text) ? text.slice(0, 10) : text.toLowerCase();
|
|
116
|
+
}
|
|
117
|
+
function formatDate(value, format) {
|
|
118
|
+
if (isEmpty(value))
|
|
119
|
+
return value;
|
|
120
|
+
let year, month, day;
|
|
121
|
+
if (value instanceof Date) {
|
|
122
|
+
[year, month, day] = [value.getUTCFullYear(), value.getUTCMonth() + 1, value.getUTCDate()];
|
|
123
|
+
}
|
|
124
|
+
else {
|
|
125
|
+
const text = String(value).trim();
|
|
126
|
+
const iso = text.match(/^(\d{4})-(\d{2})-(\d{2})/);
|
|
127
|
+
const us = text.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})/);
|
|
128
|
+
if (iso)
|
|
129
|
+
[year, month, day] = [Number(iso[1]), Number(iso[2]), Number(iso[3])];
|
|
130
|
+
else if (us)
|
|
131
|
+
[year, month, day] = [Number(us[3]), Number(us[1]), Number(us[2])];
|
|
132
|
+
else {
|
|
133
|
+
const parsed = new Date(text);
|
|
134
|
+
if (Number.isNaN(parsed.getTime()))
|
|
135
|
+
return value;
|
|
136
|
+
[year, month, day] = [parsed.getUTCFullYear(), parsed.getUTCMonth() + 1, parsed.getUTCDate()];
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
140
|
+
switch (format) {
|
|
141
|
+
case 'MM/DD/YYYY':
|
|
142
|
+
return `${pad(month)}/${pad(day)}/${year}`;
|
|
143
|
+
case 'YYYY-MM-DD':
|
|
144
|
+
return `${year}-${pad(month)}-${pad(day)}`;
|
|
145
|
+
case 'YYYY':
|
|
146
|
+
return year;
|
|
147
|
+
default:
|
|
148
|
+
throw new html_template_1.TemplateError(`"${format}" is not a date format this can write. Use MM/DD/YYYY, YYYY-MM-DD or YYYY.`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
/** Fills `{name}` in a pattern from the record, the row and the index. */
|
|
152
|
+
function fillPattern(pattern, lookup, index) {
|
|
153
|
+
return pattern.replace(/\{([^{}]+)\}/g, (_match, name) => {
|
|
154
|
+
const key = name.trim();
|
|
155
|
+
if (key === 'index')
|
|
156
|
+
return String(index);
|
|
157
|
+
const value = lookup(key);
|
|
158
|
+
return value === null || value === undefined ? '' : value instanceof Date ? value.toISOString().slice(0, 10) : String(value);
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/** One key's value for one row. */
|
|
162
|
+
function mapValue(key, spec, row, index, lookup, data, nested, tally) {
|
|
163
|
+
if (typeof spec === 'string')
|
|
164
|
+
return row[spec] ?? null;
|
|
165
|
+
if ('rows' in spec && 'each' in spec) {
|
|
166
|
+
const nestedSpec = spec;
|
|
167
|
+
const all = nested.get(nestedSpec) ?? [];
|
|
168
|
+
const subset = nestedSpec.where
|
|
169
|
+
? all.filter((child) => matchKey(child[nestedSpec.where[0]]) === matchKey(fillPattern(nestedSpec.where[1], lookup, index)))
|
|
170
|
+
: all;
|
|
171
|
+
return subset.map((child, childIndex) => mapRecord(nestedSpec.each, child, childIndex, data, nested, tally));
|
|
172
|
+
}
|
|
173
|
+
const ops = spec;
|
|
174
|
+
if (ops.object && typeof ops.object === 'object') {
|
|
175
|
+
return mapRecord(ops.object, row, index, data, nested, tally);
|
|
176
|
+
}
|
|
177
|
+
let value;
|
|
178
|
+
if (ops.ratio) {
|
|
179
|
+
if (!Array.isArray(ops.ratio) || ops.ratio.length !== 2) {
|
|
180
|
+
throw new html_template_1.TemplateError(`"ratio" for "${key}" needs two field names: [numerator, denominator].`);
|
|
181
|
+
}
|
|
182
|
+
const denominator = Number(row[ops.ratio[1]]);
|
|
183
|
+
value = denominator ? Number(row[ops.ratio[0]] ?? 0) / denominator : null;
|
|
184
|
+
}
|
|
185
|
+
else if ('const' in ops)
|
|
186
|
+
value = ops.const;
|
|
187
|
+
else if (ops.text !== undefined)
|
|
188
|
+
value = fillPattern(ops.text, lookup, index);
|
|
189
|
+
else if (ops.field !== undefined)
|
|
190
|
+
value = row[ops.field];
|
|
191
|
+
else
|
|
192
|
+
throw new html_template_1.TemplateError(`The mapping for "${key}" needs "field", "text", "const", "ratio" or "object".`);
|
|
193
|
+
if (isEmpty(value) && 'default' in ops)
|
|
194
|
+
return ops.default;
|
|
195
|
+
if (isEmpty(value))
|
|
196
|
+
return value ?? null;
|
|
197
|
+
if (ops.date)
|
|
198
|
+
value = formatDate(value, ops.date);
|
|
199
|
+
if (ops.map) {
|
|
200
|
+
const wanted = String(value).toLowerCase();
|
|
201
|
+
const found = Object.entries(ops.map).find(([from]) => from.toLowerCase() === wanted);
|
|
202
|
+
if (found)
|
|
203
|
+
value = found[1];
|
|
204
|
+
}
|
|
205
|
+
if ('equals' in ops) {
|
|
206
|
+
const target = ops.equals;
|
|
207
|
+
value = typeof value === 'string' && typeof target === 'string' ? value.toLowerCase() === target.toLowerCase() : value === target;
|
|
208
|
+
}
|
|
209
|
+
if (ops.percent) {
|
|
210
|
+
const number = Number(value);
|
|
211
|
+
if (!Number.isFinite(number))
|
|
212
|
+
return 'default' in ops ? ops.default : null;
|
|
213
|
+
const factor = 10 ** (ops.round ?? 0);
|
|
214
|
+
const rounded = Math.round(number * (ops.scale ?? 1) * 100 * factor) / factor;
|
|
215
|
+
return `${rounded === 0 ? 0 : rounded}%`;
|
|
216
|
+
}
|
|
217
|
+
if (ops.scale !== undefined || ops.round !== undefined) {
|
|
218
|
+
const number = Number(value);
|
|
219
|
+
if (Number.isFinite(number)) {
|
|
220
|
+
const scaled = number * (ops.scale ?? 1);
|
|
221
|
+
const places = ops.round ?? 6;
|
|
222
|
+
const factor = 10 ** places;
|
|
223
|
+
const rounded = Math.round(scaled * factor) / factor;
|
|
224
|
+
value = rounded === 0 ? 0 : rounded; // never -0
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (ops.indexIn) {
|
|
228
|
+
const listPath = fillPattern(ops.indexIn, lookup, index);
|
|
229
|
+
const list = (0, html_template_1.valueAtPath)(data, listPath);
|
|
230
|
+
if (!Array.isArray(list)) {
|
|
231
|
+
throw new html_template_1.TemplateError(`"${listPath}" is not a list, so "${key}" cannot be a position in it.`);
|
|
232
|
+
}
|
|
233
|
+
const wanted = matchKey(value);
|
|
234
|
+
const position = list.findIndex((item) => matchKey(ops.by ? item?.[ops.by] : item) === wanted);
|
|
235
|
+
if (position < 0) {
|
|
236
|
+
tally.misses.set(key, (tally.misses.get(key) ?? 0) + 1);
|
|
237
|
+
return 'default' in ops ? ops.default : null;
|
|
238
|
+
}
|
|
239
|
+
value = position;
|
|
240
|
+
}
|
|
241
|
+
return value;
|
|
242
|
+
}
|
|
243
|
+
function mapRecord(each, row, index, data, nested, tally) {
|
|
244
|
+
// Keys are mapped in the order they depend on each other, not the order they
|
|
245
|
+
// are stored in: a pattern naming another key (`{title}`) maps that key first.
|
|
246
|
+
// Storage need not keep key order — Postgres jsonb sorts keys — and a recipe
|
|
247
|
+
// read back from it once mapped every line's terms before the line's title.
|
|
248
|
+
const record = {};
|
|
249
|
+
const mapping = new Set();
|
|
250
|
+
const lookup = (name) => {
|
|
251
|
+
if (!Object.prototype.hasOwnProperty.call(each, name))
|
|
252
|
+
return row[name];
|
|
253
|
+
if (Object.prototype.hasOwnProperty.call(record, name))
|
|
254
|
+
return record[name];
|
|
255
|
+
if (mapping.has(name)) {
|
|
256
|
+
throw new html_template_1.TemplateError(`The mapping for "${name}" depends on itself through {${name}}.`);
|
|
257
|
+
}
|
|
258
|
+
mapping.add(name);
|
|
259
|
+
record[name] = mapValue(name, each[name], row, index, lookup, data, nested, tally);
|
|
260
|
+
mapping.delete(name);
|
|
261
|
+
return record[name];
|
|
262
|
+
};
|
|
263
|
+
for (const key of Object.keys(each))
|
|
264
|
+
lookup(key);
|
|
265
|
+
return Object.fromEntries(Object.keys(each).map((key) => [key, record[key]]));
|
|
266
|
+
}
|
|
267
|
+
// ---------------------------------------------------------------------------
|
|
268
|
+
// Running the queries
|
|
269
|
+
// ---------------------------------------------------------------------------
|
|
270
|
+
async function fetchRows(spec, run, parameters, where) {
|
|
271
|
+
const result = await run(resolveParams(spec, parameters));
|
|
272
|
+
if ('error' in result) {
|
|
273
|
+
throw new html_template_1.TemplateError(`The query for ${where} was refused: ${result.error}${result.available?.length ? ` ${result.available.join(', ')}` : ''}`);
|
|
274
|
+
}
|
|
275
|
+
return result.rows;
|
|
276
|
+
}
|
|
277
|
+
/** Each row with every join's fields added as `name.field`. */
|
|
278
|
+
async function joined(rows, joins, run, parameters, where) {
|
|
279
|
+
let result = rows;
|
|
280
|
+
for (const join of joins ?? []) {
|
|
281
|
+
if (!join?.name || !Array.isArray(join.on) || join.on.length !== 2) {
|
|
282
|
+
throw new html_template_1.TemplateError(`Each join for ${where} needs a "name", "rows" and "on": [rowField, joinedField].`);
|
|
283
|
+
}
|
|
284
|
+
const lookup = new Map();
|
|
285
|
+
for (const other of await fetchRows(join.rows, run, parameters, `${where} join "${join.name}"`)) {
|
|
286
|
+
const key = matchKey(other[join.on[1]]);
|
|
287
|
+
if (!lookup.has(key))
|
|
288
|
+
lookup.set(key, other);
|
|
289
|
+
}
|
|
290
|
+
result = result.map((row) => {
|
|
291
|
+
const match = lookup.get(matchKey(row[join.on[0]]));
|
|
292
|
+
if (!match)
|
|
293
|
+
return row;
|
|
294
|
+
const added = Object.fromEntries(Object.entries(match).map(([field, value]) => [`${join.name}.${field}`, value]));
|
|
295
|
+
return { ...row, ...added };
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
return result;
|
|
299
|
+
}
|
|
300
|
+
/** Runs every nested list's query once, before the records are built. */
|
|
301
|
+
async function fetchNested(each, run, parameters, where, into) {
|
|
302
|
+
for (const [key, spec] of Object.entries(each)) {
|
|
303
|
+
if (spec && typeof spec === 'object' && 'object' in spec && spec.object) {
|
|
304
|
+
await fetchNested(spec.object, run, parameters, `${where}.${key}`, into);
|
|
305
|
+
}
|
|
306
|
+
else if (spec && typeof spec === 'object' && 'rows' in spec && 'each' in spec) {
|
|
307
|
+
const nested = spec;
|
|
308
|
+
const rows = await fetchRows(nested.rows, run, parameters, `${where}.${key}`);
|
|
309
|
+
into.set(nested, await joined(rows, nested.joins, run, parameters, `${where}.${key}`));
|
|
310
|
+
await fetchNested(nested.each, run, parameters, `${where}.${key}`, into);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/** Keys that came out empty in every record, which usually means a wrong field name. */
|
|
315
|
+
function emptyKeys(records, each) {
|
|
316
|
+
if (!records.length)
|
|
317
|
+
return [];
|
|
318
|
+
return Object.keys(each).filter((key) => records.every((record) => isEmpty(record[key])));
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* The plain change a query-backed one stands for: its queries run, its records built
|
|
322
|
+
* against the data as changed so far.
|
|
323
|
+
*
|
|
324
|
+
* @param maxRows The ceiling a query was run with, to warn when one may have been cut
|
|
325
|
+
* @throws {TemplateError} For a refused query, a malformed mapping, or a missing parameter
|
|
326
|
+
*/
|
|
327
|
+
async function materializeChange(change, data, run, parameters, maxRows) {
|
|
328
|
+
const where = `"${change.path}"`;
|
|
329
|
+
const tally = { misses: new Map() };
|
|
330
|
+
const warnings = [];
|
|
331
|
+
if (isQueryValueChange(change)) {
|
|
332
|
+
const rows = await fetchRows(change.query, run, parameters, where);
|
|
333
|
+
const take = change.take;
|
|
334
|
+
const ops = { ...change };
|
|
335
|
+
for (const key of ['path', 'query', 'take', 'keep'])
|
|
336
|
+
delete ops[key];
|
|
337
|
+
if (!rows.length)
|
|
338
|
+
warnings.push(`The query for ${where} returned no rows, so it was set to ${'default' in ops ? 'its default' : 'null'}.`);
|
|
339
|
+
const value = rows.length
|
|
340
|
+
? mapValue(change.path, { ...ops, field: take }, rows[0], 0, (name) => rows[0][name], data, new Map(), tally)
|
|
341
|
+
: ('default' in ops ? ops.default : null);
|
|
342
|
+
if (rows.length && !(take in rows[0]))
|
|
343
|
+
warnings.push(`The query for ${where} has no column "${take}"; its columns are ${Object.keys(rows[0]).join(', ')}.`);
|
|
344
|
+
return { change: { path: change.path, value }, report: { path: change.path, rows: rows.length, records: 1, sample: [value] }, warnings };
|
|
345
|
+
}
|
|
346
|
+
if (!change.each || typeof change.each !== 'object') {
|
|
347
|
+
throw new html_template_1.TemplateError(`The change to ${where} needs "each": how a row becomes a record.`);
|
|
348
|
+
}
|
|
349
|
+
const rows = await joined(await fetchRows(change.rows, run, parameters, where), change.joins, run, parameters, where);
|
|
350
|
+
if (rows.length >= maxRows) {
|
|
351
|
+
warnings.push(`The query for ${where} returned ${maxRows} rows, the most a fill takes; there may be more. Narrow it.`);
|
|
352
|
+
}
|
|
353
|
+
const nested = new Map();
|
|
354
|
+
await fetchNested(change.each, run, parameters, where, nested);
|
|
355
|
+
const records = rows.map((row, index) => mapRecord(change.each, row, index, data, nested, tally));
|
|
356
|
+
const empty = emptyKeys(records, change.each);
|
|
357
|
+
if (empty.length) {
|
|
358
|
+
warnings.push(`In ${where}, ${empty.map((key) => `"${key}"`).join(', ')} came out empty in every record; check the field names.`);
|
|
359
|
+
}
|
|
360
|
+
for (const [key, count] of tally.misses) {
|
|
361
|
+
warnings.push(`In ${where}, "${key}" found no match in its list for ${count} record(s); those are null.`);
|
|
362
|
+
}
|
|
363
|
+
return {
|
|
364
|
+
change: { path: change.path, value: records },
|
|
365
|
+
report: { path: change.path, rows: rows.length, records: records.length, sample: records.slice(0, 2) },
|
|
366
|
+
warnings,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
function usesParam(change) {
|
|
370
|
+
return paramNames(change).size > 0;
|
|
371
|
+
}
|
|
372
|
+
/** Whether a change is replayed by a recipe rather than written afresh. */
|
|
373
|
+
function isRecipeChange(change) {
|
|
374
|
+
return isQueryBacked(change) || !!change.keep || usesParam(change);
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* The recipe a fill amounts to: query-backed changes, fixed ones (`keep`) and
|
|
378
|
+
* ones that use a `$param` are replayed, with the given parameters written back
|
|
379
|
+
* as `$param`s; every other plain change is a written part, kept as its path and
|
|
380
|
+
* note.
|
|
381
|
+
*/
|
|
382
|
+
function buildRecipe(input) {
|
|
383
|
+
const replayed = input.changes.filter(isRecipeChange).map((change) => parameterize(change, input.parameters));
|
|
384
|
+
const builtLists = input.changes.filter(isRowsChange).map((change) => (0, html_template_1.formatPath)((0, html_template_1.parseTemplatePath)(change.path)));
|
|
385
|
+
const written = [];
|
|
386
|
+
for (const change of input.changes.filter((entry) => !isRecipeChange(entry))) {
|
|
387
|
+
const path = wildcardPath(change.path, builtLists);
|
|
388
|
+
const note = change.note;
|
|
389
|
+
const known = written.find((part) => part.path === path);
|
|
390
|
+
if (!known)
|
|
391
|
+
written.push({ path, ...(note ? { note } : {}) });
|
|
392
|
+
else if (!known.note && note)
|
|
393
|
+
known.note = note;
|
|
394
|
+
}
|
|
395
|
+
const facts = (input.facts ?? []).map((fact) => ({ name: fact.name, query: parameterizeQuery(fact.query, input.parameters) }));
|
|
396
|
+
const names = new Set(Object.keys(input.parameters));
|
|
397
|
+
paramNames(replayed, names);
|
|
398
|
+
paramNames(facts, names);
|
|
399
|
+
return {
|
|
400
|
+
version: 1,
|
|
401
|
+
block: input.block,
|
|
402
|
+
shape: (0, html_data_1.describeShape)(input.templateValue),
|
|
403
|
+
parameters: [...names],
|
|
404
|
+
changes: replayed,
|
|
405
|
+
written,
|
|
406
|
+
facts,
|
|
407
|
+
...(input.notes ? { notes: input.notes } : {}),
|
|
408
|
+
savedAt: new Date().toISOString(),
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* A path with an index into a list the fill built from a query written as `[*]`:
|
|
413
|
+
* that list will have other items for the next client, so a part written for one
|
|
414
|
+
* of them is a part written for each.
|
|
415
|
+
*/
|
|
416
|
+
function wildcardPath(path, builtLists) {
|
|
417
|
+
const steps = (0, html_template_1.parseTemplatePath)(path);
|
|
418
|
+
const parts = [];
|
|
419
|
+
steps.forEach((step, index) => {
|
|
420
|
+
const prefix = (0, html_template_1.formatPath)(steps.slice(0, index));
|
|
421
|
+
const wild = typeof step === 'number' && builtLists.includes(prefix);
|
|
422
|
+
parts.push(wild ? '[*]' : (0, html_template_1.formatPath)([step]).replace(/^(?=[^[])/, index ? '.' : ''));
|
|
423
|
+
});
|
|
424
|
+
return parts.join('');
|
|
425
|
+
}
|
|
426
|
+
/**
|
|
427
|
+
* The concrete paths a written part stands for in the data as filled: `lines[*].title`
|
|
428
|
+
* is `lines[0].title` … for every line there is. A path without `[*]` stands for itself.
|
|
429
|
+
*/
|
|
430
|
+
function expandWrittenPath(path, data) {
|
|
431
|
+
const at = path.indexOf('[*]');
|
|
432
|
+
if (at < 0)
|
|
433
|
+
return [path];
|
|
434
|
+
const listPath = path.slice(0, at);
|
|
435
|
+
const rest = path.slice(at + 3);
|
|
436
|
+
let list;
|
|
437
|
+
try {
|
|
438
|
+
list = (0, html_template_1.valueAtPath)(data, listPath);
|
|
439
|
+
}
|
|
440
|
+
catch {
|
|
441
|
+
return [];
|
|
442
|
+
}
|
|
443
|
+
if (!Array.isArray(list))
|
|
444
|
+
return [];
|
|
445
|
+
return list.flatMap((_item, index) => expandWrittenPath(`${listPath}[${index}]${rest}`, data));
|
|
446
|
+
}
|
|
447
|
+
/** Whether a change sets this path or something containing it. */
|
|
448
|
+
function coversPath(changePath, wantedPath) {
|
|
449
|
+
const change = (0, html_template_1.parseTemplatePath)(changePath);
|
|
450
|
+
const wanted = (0, html_template_1.parseTemplatePath)(wantedPath);
|
|
451
|
+
return change.length <= wanted.length && change.every((step, index) => step === wanted[index]);
|
|
452
|
+
}
|
|
@@ -32,7 +32,8 @@ export declare class Room {
|
|
|
32
32
|
* limit, and hitting it is expensive in its own right — the turn is re-prompted,
|
|
33
33
|
* the work is often redone, and a person has to notice and say "carry on".
|
|
34
34
|
*
|
|
35
|
-
*
|
|
35
|
+
* An agent's own `maxToolIterations` wins, for an agent whose one job is long.
|
|
36
|
+
* Otherwise raise it with `ROOM_MAX_TOOL_ITERATIONS`. Read per turn so it can be retuned on
|
|
36
37
|
* a running server, and floored at 1 so a nonsense value cannot stop every agent
|
|
37
38
|
* from acting.
|
|
38
39
|
*
|
|
@@ -36,13 +36,17 @@ class Room {
|
|
|
36
36
|
* limit, and hitting it is expensive in its own right — the turn is re-prompted,
|
|
37
37
|
* the work is often redone, and a person has to notice and say "carry on".
|
|
38
38
|
*
|
|
39
|
-
*
|
|
39
|
+
* An agent's own `maxToolIterations` wins, for an agent whose one job is long.
|
|
40
|
+
* Otherwise raise it with `ROOM_MAX_TOOL_ITERATIONS`. Read per turn so it can be retuned on
|
|
40
41
|
* a running server, and floored at 1 so a nonsense value cannot stop every agent
|
|
41
42
|
* from acting.
|
|
42
43
|
*
|
|
43
44
|
* @returns The number of tool calls an agent may chain in one turn
|
|
44
45
|
*/
|
|
45
|
-
static maxToolIterations() {
|
|
46
|
+
static maxToolIterations(agent) {
|
|
47
|
+
const own = Number(agent?.maxToolIterations);
|
|
48
|
+
if (Number.isFinite(own) && own > 0)
|
|
49
|
+
return Math.floor(own);
|
|
46
50
|
const configured = Number(process.env.ROOM_MAX_TOOL_ITERATIONS);
|
|
47
51
|
return Number.isFinite(configured) && configured > 0 ? Math.floor(configured) : 30;
|
|
48
52
|
}
|
|
@@ -1443,7 +1447,7 @@ class Room {
|
|
|
1443
1447
|
this.imagesThisTurn.delete(agent.agentNickname);
|
|
1444
1448
|
const variables = await this.buildPerceiveVariables(agent);
|
|
1445
1449
|
let response = await this.promptAgentOnce(agent, this.buildTransientPrompt(agent, heardMessage), variables);
|
|
1446
|
-
const maxIterations = Room.maxToolIterations();
|
|
1450
|
+
const maxIterations = Room.maxToolIterations(agent);
|
|
1447
1451
|
let emptyReplyReturned = false;
|
|
1448
1452
|
for (let i = 0; i < maxIterations; i++) {
|
|
1449
1453
|
if (this.isPaused || this.isAdjourned)
|
|
@@ -2,14 +2,23 @@ export { Briyah } from './briyah';
|
|
|
2
2
|
export { BriyahConfigService, BriyahConfigOptions } from './briyah-config';
|
|
3
3
|
export type { AppService, AgentCreationOptions, PdfMarkdownOptions, PdfMarkdownResult, DocumentMarkdownOptions, DocumentMarkdownResult, } from '../app.service';
|
|
4
4
|
export { detectDocumentType, convertLocalDocument, UnsupportedDocumentError, } from '../documents/document-conversion';
|
|
5
|
-
export type { DocumentFileType, DocumentTypeDetection, DocumentPage as ConvertedDocumentPage, LocalDocumentConversion, LocalConversionOptions, } from '../documents/document-conversion';
|
|
5
|
+
export type { DocumentFileType, DocumentTypeDetection, DocumentPage as ConvertedDocumentPage, LocalDocumentConversion, LocalConversionOptions, HtmlDataBlockInfo, } from '../documents/document-conversion';
|
|
6
|
+
export { findDataBlocks, describeShape, readableJson } from '../documents/html-data';
|
|
7
|
+
export type { HtmlDataBlock } from '../documents/html-data';
|
|
8
|
+
export { applyTemplateChanges, readTemplateData, scriptSafeJson, TemplateError, } from '../documents/html-template';
|
|
9
|
+
export type { TemplateChange, TemplateFill, TemplateFillResult } from '../documents/html-template';
|
|
10
|
+
export { buildRecipe, materializeChange, resolveParams, parameterizeQuery } from '../documents/template-mapping';
|
|
11
|
+
export type { TemplateRecipe, FillChange, RowsChange, QueryValueChange, PlainChange, ValueSpec, JoinSpec, NestedSpec, RecipeFact, WrittenPart, ChangeReport, } from '../documents/template-mapping';
|
|
12
|
+
export { runDataQuery } from '../data/run-query';
|
|
13
|
+
export type { RunQueryResult } from '../data/run-query';
|
|
14
|
+
export { buildHtmlTemplateGuideMarkdown } from '../documents/library/html-template-guide.builder';
|
|
6
15
|
export { detectAttachmentMimeType, isAttachmentImage, ATTACHMENT_IMAGE_TYPES, MAX_ATTACHED_IMAGE_BYTES, } from '../ai/LLM/attachment-type';
|
|
7
16
|
export type { AttachmentImageType } from '../ai/LLM/attachment-type';
|
|
8
|
-
export { runWithUsageTags, currentUsageTags } from '../app/usage-context';
|
|
17
|
+
export { runWithUsageTags, currentUsageTags, updateUsageTags } from '../app/usage-context';
|
|
9
18
|
export type { UsageTags } from '../app/usage-context';
|
|
10
19
|
export { InsufficientBalanceError, setInsufficientBalanceMessage, insufficientBalanceMessage, } from '../common/errors';
|
|
11
20
|
export type { AllowanceState, CreditSummary, UsageEntry, UsageReport, UsageTotal, UsageSource, } from '../app/balance.service';
|
|
12
|
-
export type { DocumentSource, DocumentSummary, DocumentSearchRequest, DocumentHit, DocumentPages, DocumentPage, DocumentText, PageRange, } from '../documents/library/document.types';
|
|
21
|
+
export type { DocumentSource, DocumentSummary, DocumentSearchRequest, DocumentHit, DocumentPages, DocumentPage, DocumentText, PageRange, DocumentOriginal, NewDocument, CreatedDocument, } from '../documents/library/document.types';
|
|
13
22
|
export { registerDocumentSource, unregisterDocumentSource, listDocumentSources, } from '../documents/library/document-registry';
|
|
14
23
|
export { buildDocumentGuideMarkdown } from '../documents/library/document-guide.builder';
|
|
15
24
|
export { chunkPages, embeddingInput, DEFAULT_CHUNK_MAX_CHARS, DEFAULT_CHUNK_OVERLAP_CHARS, } from '../documents/library/chunking';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.
|
|
4
|
-
exports.RoomMessage = exports.Room = exports.Agent = exports.PackInstantiationService = exports.PackService = void 0;
|
|
3
|
+
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.insufficientBalanceMessage = exports.setInsufficientBalanceMessage = exports.InsufficientBalanceError = exports.updateUsageTags = exports.currentUsageTags = exports.runWithUsageTags = exports.MAX_ATTACHED_IMAGE_BYTES = exports.ATTACHMENT_IMAGE_TYPES = exports.isAttachmentImage = exports.detectAttachmentMimeType = exports.buildHtmlTemplateGuideMarkdown = exports.runDataQuery = exports.parameterizeQuery = exports.resolveParams = exports.materializeChange = exports.buildRecipe = exports.TemplateError = exports.scriptSafeJson = exports.readTemplateData = exports.applyTemplateChanges = exports.readableJson = exports.describeShape = exports.findDataBlocks = exports.UnsupportedDocumentError = exports.convertLocalDocument = exports.detectDocumentType = exports.BriyahConfigService = exports.Briyah = void 0;
|
|
4
|
+
exports.RoomMessage = exports.Room = exports.Agent = exports.PackInstantiationService = exports.PackService = exports.formatChartValue = exports.renderChartSvg = exports.validateChart = exports.CHART_TYPES = exports.CHART_BLOCK_LANGUAGE = exports.queryRows = exports.buildDataGuideMarkdown = exports.listDatasets = exports.listDataSources = exports.unregisterDataSource = exports.registerDataSource = exports.MAX_ROW_LIMIT = exports.DEFAULT_ROW_LIMIT = exports.NativeToolRegistry = void 0;
|
|
5
5
|
// Main SDK exports
|
|
6
6
|
var briyah_1 = require("./briyah");
|
|
7
7
|
Object.defineProperty(exports, "Briyah", { enumerable: true, get: function () { return briyah_1.Briyah; } });
|
|
@@ -14,6 +14,31 @@ var document_conversion_1 = require("../documents/document-conversion");
|
|
|
14
14
|
Object.defineProperty(exports, "detectDocumentType", { enumerable: true, get: function () { return document_conversion_1.detectDocumentType; } });
|
|
15
15
|
Object.defineProperty(exports, "convertLocalDocument", { enumerable: true, get: function () { return document_conversion_1.convertLocalDocument; } });
|
|
16
16
|
Object.defineProperty(exports, "UnsupportedDocumentError", { enumerable: true, get: function () { return document_conversion_1.UnsupportedDocumentError; } });
|
|
17
|
+
// HTML templates: pages whose scripts draw everything from an embedded JSON data
|
|
18
|
+
// block. A source that implements `original` and `create` lets agents fill them
|
|
19
|
+
// with inspect_html_template / fill_html_template; these are for a host that wants
|
|
20
|
+
// to do the same itself.
|
|
21
|
+
var html_data_1 = require("../documents/html-data");
|
|
22
|
+
Object.defineProperty(exports, "findDataBlocks", { enumerable: true, get: function () { return html_data_1.findDataBlocks; } });
|
|
23
|
+
Object.defineProperty(exports, "describeShape", { enumerable: true, get: function () { return html_data_1.describeShape; } });
|
|
24
|
+
Object.defineProperty(exports, "readableJson", { enumerable: true, get: function () { return html_data_1.readableJson; } });
|
|
25
|
+
var html_template_1 = require("../documents/html-template");
|
|
26
|
+
Object.defineProperty(exports, "applyTemplateChanges", { enumerable: true, get: function () { return html_template_1.applyTemplateChanges; } });
|
|
27
|
+
Object.defineProperty(exports, "readTemplateData", { enumerable: true, get: function () { return html_template_1.readTemplateData; } });
|
|
28
|
+
Object.defineProperty(exports, "scriptSafeJson", { enumerable: true, get: function () { return html_template_1.scriptSafeJson; } });
|
|
29
|
+
Object.defineProperty(exports, "TemplateError", { enumerable: true, get: function () { return html_template_1.TemplateError; } });
|
|
30
|
+
// Query-backed fills and recipes: a change built from query rows, and how a
|
|
31
|
+
// template is filled for anyone, kept by a source that implements saveRecipe/recipe.
|
|
32
|
+
var template_mapping_1 = require("../documents/template-mapping");
|
|
33
|
+
Object.defineProperty(exports, "buildRecipe", { enumerable: true, get: function () { return template_mapping_1.buildRecipe; } });
|
|
34
|
+
Object.defineProperty(exports, "materializeChange", { enumerable: true, get: function () { return template_mapping_1.materializeChange; } });
|
|
35
|
+
Object.defineProperty(exports, "resolveParams", { enumerable: true, get: function () { return template_mapping_1.resolveParams; } });
|
|
36
|
+
Object.defineProperty(exports, "parameterizeQuery", { enumerable: true, get: function () { return template_mapping_1.parameterizeQuery; } });
|
|
37
|
+
// Validate and run one agent-written query with a host context, as query_data does.
|
|
38
|
+
var run_query_1 = require("../data/run-query");
|
|
39
|
+
Object.defineProperty(exports, "runDataQuery", { enumerable: true, get: function () { return run_query_1.runDataQuery; } });
|
|
40
|
+
var html_template_guide_builder_1 = require("../documents/library/html-template-guide.builder");
|
|
41
|
+
Object.defineProperty(exports, "buildHtmlTemplateGuideMarkdown", { enumerable: true, get: function () { return html_template_guide_builder_1.buildHtmlTemplateGuideMarkdown; } });
|
|
17
42
|
// What agent.attachDocument() will send a file as (a PDF, an image or text), for a
|
|
18
43
|
// host that wants to check an upload, or shrink a photo, before attaching it.
|
|
19
44
|
var attachment_type_1 = require("../ai/LLM/attachment-type");
|
|
@@ -26,6 +51,7 @@ Object.defineProperty(exports, "MAX_ATTACHED_IMAGE_BYTES", { enumerable: true, g
|
|
|
26
51
|
var usage_context_1 = require("../app/usage-context");
|
|
27
52
|
Object.defineProperty(exports, "runWithUsageTags", { enumerable: true, get: function () { return usage_context_1.runWithUsageTags; } });
|
|
28
53
|
Object.defineProperty(exports, "currentUsageTags", { enumerable: true, get: function () { return usage_context_1.currentUsageTags; } });
|
|
54
|
+
Object.defineProperty(exports, "updateUsageTags", { enumerable: true, get: function () { return usage_context_1.updateUsageTags; } });
|
|
29
55
|
// What an AI call throws once the credit is gone. Its message is the host's when
|
|
30
56
|
// one is set, so the host's wording (and where to buy more) is what users read.
|
|
31
57
|
var errors_1 = require("../common/errors");
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
* host lists for this call's context — never passed through on trust.
|
|
19
19
|
*/
|
|
20
20
|
import { NativeToolDefinition } from '../native-tool.types';
|
|
21
|
+
import { DocumentSource, DocumentSummary } from '../../documents/library/document.types';
|
|
21
22
|
/**
|
|
22
23
|
* The file name a held library document is attached under.
|
|
23
24
|
*
|
|
@@ -30,6 +31,27 @@ export declare function libraryAttachmentName(documentId: string, name: string):
|
|
|
30
31
|
export declare function isLibraryAttachment(fileName: string): boolean;
|
|
31
32
|
/** The library document id an attachment holds, or undefined for any other attachment. */
|
|
32
33
|
export declare function libraryDocumentIdOf(fileName: string): string | undefined;
|
|
34
|
+
export declare const unavailable: {
|
|
35
|
+
ok: boolean;
|
|
36
|
+
summary: string;
|
|
37
|
+
error: string;
|
|
38
|
+
};
|
|
39
|
+
/** Every document in scope, each paired with the source that owns it. */
|
|
40
|
+
export declare function inScope(context: unknown): Promise<{
|
|
41
|
+
source: DocumentSource;
|
|
42
|
+
document: DocumentSummary;
|
|
43
|
+
}[]>;
|
|
44
|
+
export declare function unknownDocument(documentId: string, scope: {
|
|
45
|
+
document: DocumentSummary;
|
|
46
|
+
}[]): {
|
|
47
|
+
available?: {
|
|
48
|
+
documentId: string;
|
|
49
|
+
name: string;
|
|
50
|
+
}[];
|
|
51
|
+
ok: boolean;
|
|
52
|
+
summary: string;
|
|
53
|
+
error: string;
|
|
54
|
+
};
|
|
33
55
|
export declare const listDocumentsTool: NativeToolDefinition;
|
|
34
56
|
export declare const findInDocumentsTool: NativeToolDefinition;
|
|
35
57
|
export declare const readDocumentTool: NativeToolDefinition;
|