briyah 2.0.5 → 2.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/README.md +105 -0
  2. package/data/common/prompts/moderate.json +34 -0
  3. package/data/common/prompts/moderate.prompt +136 -0
  4. package/data/packs/dnd5e/pack.json +7 -1
  5. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +16 -0
  6. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +23 -0
  7. package/dist-sdk/server/src/ai/agent.d.ts +33 -0
  8. package/dist-sdk/server/src/ai/agent.js +64 -13
  9. package/dist-sdk/server/src/app/user-service-factory.js +3 -0
  10. package/dist-sdk/server/src/app.controller.d.ts +7 -1
  11. package/dist-sdk/server/src/app.controller.js +55 -0
  12. package/dist-sdk/server/src/app.service.d.ts +114 -2
  13. package/dist-sdk/server/src/app.service.js +181 -4
  14. package/dist-sdk/server/src/data/data-guide.builder.d.ts +2 -0
  15. package/dist-sdk/server/src/data/data-guide.builder.js +90 -0
  16. package/dist-sdk/server/src/data/data-registry.d.ts +32 -0
  17. package/dist-sdk/server/src/data/data-registry.js +61 -0
  18. package/dist-sdk/server/src/data/data.types.d.ts +158 -0
  19. package/dist-sdk/server/src/data/data.types.js +24 -0
  20. package/dist-sdk/server/src/data/query-validation.d.ts +45 -0
  21. package/dist-sdk/server/src/data/query-validation.js +245 -0
  22. package/dist-sdk/server/src/documents/document-conversion.d.ts +70 -0
  23. package/dist-sdk/server/src/documents/document-conversion.js +341 -0
  24. package/dist-sdk/server/src/documents/library/chunking.d.ts +65 -0
  25. package/dist-sdk/server/src/documents/library/chunking.js +263 -0
  26. package/dist-sdk/server/src/documents/library/document-guide.builder.d.ts +2 -0
  27. package/dist-sdk/server/src/documents/library/document-guide.builder.js +58 -0
  28. package/dist-sdk/server/src/documents/library/document-registry.d.ts +22 -0
  29. package/dist-sdk/server/src/documents/library/document-registry.js +44 -0
  30. package/dist-sdk/server/src/documents/library/document.types.d.ts +108 -0
  31. package/dist-sdk/server/src/documents/library/document.types.js +20 -0
  32. package/dist-sdk/server/src/documents/library/embedding.d.ts +57 -0
  33. package/dist-sdk/server/src/documents/library/embedding.js +151 -0
  34. package/dist-sdk/server/src/packs/pack-manifest.d.ts +46 -0
  35. package/dist-sdk/server/src/packs/pack-manifest.js +46 -1
  36. package/dist-sdk/server/src/room/artifact-store.service.js +44 -11
  37. package/dist-sdk/server/src/room/artifact.d.ts +8 -0
  38. package/dist-sdk/server/src/room/room.d.ts +7 -5
  39. package/dist-sdk/server/src/room/room.js +44 -7
  40. package/dist-sdk/server/src/rpg/rpg-roster.d.ts +70 -29
  41. package/dist-sdk/server/src/rpg/rpg-roster.js +152 -41
  42. package/dist-sdk/server/src/rpg/rpg.service.d.ts +66 -29
  43. package/dist-sdk/server/src/rpg/rpg.service.js +140 -65
  44. package/dist-sdk/server/src/sdk/index.d.ts +16 -2
  45. package/dist-sdk/server/src/sdk/index.js +37 -1
  46. package/dist-sdk/server/src/tools/core/data.tools.d.ts +17 -0
  47. package/dist-sdk/server/src/tools/core/data.tools.js +165 -0
  48. package/dist-sdk/server/src/tools/core/document.tools.d.ts +39 -0
  49. package/dist-sdk/server/src/tools/core/document.tools.js +391 -0
  50. package/dist-sdk/server/src/tools/core/index.js +3 -1
  51. package/dist-sdk/server/src/tools/native-tool.types.d.ts +37 -0
  52. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +23 -2
  53. package/dist-sdk/server/src/tools/tool-execution.service.js +30 -6
  54. package/dist-sdk/shared/types/app.types.d.ts +39 -5
  55. package/package.json +172 -167
@@ -0,0 +1,158 @@
1
+ /**
2
+ * The shape of a host's queryable data, and of the questions an agent may ask
3
+ * about it.
4
+ *
5
+ * Briyah owns the protocol and the safety properties; the host owns the data. A
6
+ * host describes its datasets and supplies one {@link DataSource.execute}, and
7
+ * gets a validated, bounded, read-only query capability without writing a tool,
8
+ * a validator, a prompt schema or a result envelope.
9
+ *
10
+ * The safety model is *construction*, not inspection. An agent never writes a
11
+ * query language — it fills in {@link DataQuery}, whose every field name is
12
+ * looked up in the dataset's declared {@link DataField} list before the host
13
+ * sees it. A name that was not declared cannot reach the host, so a host's
14
+ * executor can treat a validated query as trusted input and never has to parse
15
+ * or sanitize anything a model wrote. That is what makes it safe to run against
16
+ * a database with no read-only role behind it.
17
+ */
18
+ /** What kind of value a field holds, and therefore how it may be compared. */
19
+ export type DataFieldType = 'string' | 'number' | 'boolean' | 'date' | 'enum';
20
+ /** The aggregate functions a query may ask for. */
21
+ export type DataAggregateFn = 'count' | 'sum' | 'avg' | 'min' | 'max';
22
+ /**
23
+ * How a filter compares a field to a value.
24
+ *
25
+ * Deliberately small: everything here maps onto something every store can do,
26
+ * and nothing here can express a subquery, a join the host did not declare, or
27
+ * a raw expression.
28
+ */
29
+ export type DataFilterOp = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'in' | 'contains' | 'between' | 'isNull' | 'notNull';
30
+ /**
31
+ * One queryable field.
32
+ *
33
+ * A field is not required to be a stored column. A host may declare a *derived*
34
+ * field — an age computed from a date of birth, a total computed from five
35
+ * columns — and translate it in its executor. Declaring it here is what keeps
36
+ * the arithmetic out of the model, which is the difference between an answer
37
+ * that is right and one that is plausible.
38
+ */
39
+ export interface DataField {
40
+ /** The name an agent uses. Stable; it appears in prompts and saved queries. */
41
+ name: string;
42
+ type: DataFieldType;
43
+ /** Human-facing name for the schema guide. Falls back to `name`. */
44
+ label?: string;
45
+ /** What the field means, and anything an agent would otherwise assume wrongly. */
46
+ description?: string;
47
+ /** For `enum`, the values it may hold. Rendered into the guide and enforced. */
48
+ enumValues?: string[];
49
+ /** May appear in `filters`. Default true. */
50
+ filterable?: boolean;
51
+ /** May appear in `groupBy` or be selected as a dimension. Default true. */
52
+ groupable?: boolean;
53
+ /**
54
+ * The aggregate functions allowed on this field. Omit for none — a field
55
+ * nothing can be summed over, like a name.
56
+ */
57
+ aggregates?: DataAggregateFn[];
58
+ }
59
+ /** One queryable collection of records. */
60
+ export interface DataSet {
61
+ /** The name an agent uses. */
62
+ name: string;
63
+ /** Human-facing name for the schema guide. Falls back to `name`. */
64
+ label?: string;
65
+ /** One or two sentences: what one row is, and what the set covers. */
66
+ description: string;
67
+ fields: DataField[];
68
+ /**
69
+ * Things an agent must know to read an answer correctly, rendered verbatim
70
+ * into the schema guide. This is the place to say what a set silently
71
+ * excludes, which of two plausible definitions a metric uses, and — just as
72
+ * importantly — what it is *not* related to, so an agent refuses a question
73
+ * instead of inventing a way to answer it.
74
+ */
75
+ notes?: string[];
76
+ /** Rows returned when a query names no limit. Defaults to {@link DEFAULT_ROW_LIMIT}. */
77
+ defaultLimit?: number;
78
+ /** The most rows this set will ever return, whatever a query asks for. */
79
+ maxLimit?: number;
80
+ }
81
+ /** One comparison in a query. */
82
+ export interface DataFilter {
83
+ field: string;
84
+ op: DataFilterOp;
85
+ /** Omitted for `isNull`/`notNull`; an array for `in` and `between`. */
86
+ value?: any;
87
+ }
88
+ /** One aggregate in a query. */
89
+ export interface DataMetric {
90
+ fn: DataAggregateFn;
91
+ /** Omitted only for `count`, which counts rows. */
92
+ field?: string;
93
+ /** The name this metric has in the result rows. Defaults to `fn_field`. */
94
+ as?: string;
95
+ }
96
+ /** How to order a result. */
97
+ export interface DataOrder {
98
+ /** A grouped field's name, or a metric's `as` name. */
99
+ by: string;
100
+ dir?: 'asc' | 'desc';
101
+ }
102
+ /**
103
+ * A question, as an agent asks it.
104
+ *
105
+ * With no `groupBy` and no `metrics` this is a plain listing of rows. With
106
+ * either, it is an aggregate: `groupBy` names the dimensions and `metrics` the
107
+ * numbers, exactly as a pivot table would.
108
+ */
109
+ export interface DataQuery {
110
+ dataset: string;
111
+ filters?: DataFilter[];
112
+ groupBy?: string[];
113
+ metrics?: DataMetric[];
114
+ /** Fields to return when this is a listing rather than an aggregate. */
115
+ select?: string[];
116
+ orderBy?: DataOrder[];
117
+ limit?: number;
118
+ }
119
+ /** One row of a result. Keys are field names, metric `as` names, or both. */
120
+ export type DataRow = Record<string, any>;
121
+ /** What a host's executor hands back. */
122
+ export interface DataResult {
123
+ rows: DataRow[];
124
+ /**
125
+ * Total rows the query matched, when the host can say cheaply. Lets an
126
+ * answer say "the top 10 of 240" rather than implying it saw everything.
127
+ */
128
+ totalRows?: number;
129
+ }
130
+ /**
131
+ * A host's queryable data.
132
+ *
133
+ * `execute` is only ever called with a query that has already been validated
134
+ * against the named dataset: every field exists, every operator is allowed on
135
+ * it, every enum value is one of the declared ones, and the limit is within the
136
+ * set's cap. A host does not need to re-check any of that, and must not accept
137
+ * a query from anywhere else.
138
+ */
139
+ export interface DataSource {
140
+ /** Identifies the source in logs and in the schema guide's title. */
141
+ name: string;
142
+ /** Shown at the top of the schema guide. */
143
+ description?: string;
144
+ datasets: DataSet[];
145
+ /**
146
+ * Runs one validated query.
147
+ * @param query The validated query
148
+ * @param context The host's opaque per-invocation context, threaded from
149
+ * `sendRoomMessage` — where the tenant scoping lives. Never anything the
150
+ * model supplied.
151
+ * @returns The rows, and the total when it is cheap to know
152
+ */
153
+ execute(query: DataQuery, context: unknown): Promise<DataResult>;
154
+ }
155
+ /** Rows returned when neither the query nor the dataset names a limit. */
156
+ export declare const DEFAULT_ROW_LIMIT = 50;
157
+ /** The ceiling no dataset's `maxLimit` may exceed. */
158
+ export declare const MAX_ROW_LIMIT = 1000;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ /**
3
+ * The shape of a host's queryable data, and of the questions an agent may ask
4
+ * about it.
5
+ *
6
+ * Briyah owns the protocol and the safety properties; the host owns the data. A
7
+ * host describes its datasets and supplies one {@link DataSource.execute}, and
8
+ * gets a validated, bounded, read-only query capability without writing a tool,
9
+ * a validator, a prompt schema or a result envelope.
10
+ *
11
+ * The safety model is *construction*, not inspection. An agent never writes a
12
+ * query language — it fills in {@link DataQuery}, whose every field name is
13
+ * looked up in the dataset's declared {@link DataField} list before the host
14
+ * sees it. A name that was not declared cannot reach the host, so a host's
15
+ * executor can treat a validated query as trusted input and never has to parse
16
+ * or sanitize anything a model wrote. That is what makes it safe to run against
17
+ * a database with no read-only role behind it.
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.MAX_ROW_LIMIT = exports.DEFAULT_ROW_LIMIT = void 0;
21
+ /** Rows returned when neither the query nor the dataset names a limit. */
22
+ exports.DEFAULT_ROW_LIMIT = 50;
23
+ /** The ceiling no dataset's `maxLimit` may exceed. */
24
+ exports.MAX_ROW_LIMIT = 1_000;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Turns whatever a model produced into a query a host can trust, or into an
3
+ * error the model can act on.
4
+ *
5
+ * Two rules shape everything here.
6
+ *
7
+ * **Nothing undeclared survives.** Every dataset, field, operator, enum value
8
+ * and aggregate is checked against the host's {@link DataSet} before the query
9
+ * is handed on. A host's executor therefore never sees a name it did not
10
+ * declare, which is what lets it build a statement without sanitizing anything.
11
+ *
12
+ * **A rejection names the alternatives.** "Unknown field" teaches a model
13
+ * nothing and it guesses again; "unknown field X — this set has A, B, C" is
14
+ * repaired on the next turn. This mirrors how the rest of Briyah answers a bad
15
+ * argument, and it is why these return strings rather than throwing.
16
+ */
17
+ import { DataAggregateFn, DataQuery, DataSet } from './data.types';
18
+ /**
19
+ * A validated query, or the reason it was refused.
20
+ *
21
+ * One shape with optional halves rather than a discriminated union: this
22
+ * package compiles with `strictNullChecks` off, where narrowing on a boolean
23
+ * discriminant does not hold, so a union would force a cast at every use.
24
+ */
25
+ export interface ValidationResult {
26
+ ok: boolean;
27
+ /** The normalized query. Present when `ok`. */
28
+ query?: DataQuery;
29
+ /** The dataset it names. Present when `ok`. */
30
+ dataset?: DataSet;
31
+ /** Why it was refused. Present when not `ok`. */
32
+ error?: string;
33
+ /** What could have been used instead, when naming them helps. */
34
+ available?: string[];
35
+ }
36
+ /** The name a metric carries in the result rows. */
37
+ export declare function metricName(fn: DataAggregateFn, field?: string, as?: string): string;
38
+ /**
39
+ * Checks a raw query against a dataset and fills in its defaults.
40
+ *
41
+ * @param raw The query as the model produced it
42
+ * @param sets Every dataset the source declares
43
+ * @returns The validated query, or a refusal naming what was allowed instead
44
+ */
45
+ export declare function validateQuery(raw: any, sets: DataSet[]): ValidationResult;
@@ -0,0 +1,245 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.metricName = metricName;
4
+ exports.validateQuery = validateQuery;
5
+ /**
6
+ * Turns whatever a model produced into a query a host can trust, or into an
7
+ * error the model can act on.
8
+ *
9
+ * Two rules shape everything here.
10
+ *
11
+ * **Nothing undeclared survives.** Every dataset, field, operator, enum value
12
+ * and aggregate is checked against the host's {@link DataSet} before the query
13
+ * is handed on. A host's executor therefore never sees a name it did not
14
+ * declare, which is what lets it build a statement without sanitizing anything.
15
+ *
16
+ * **A rejection names the alternatives.** "Unknown field" teaches a model
17
+ * nothing and it guesses again; "unknown field X — this set has A, B, C" is
18
+ * repaired on the next turn. This mirrors how the rest of Briyah answers a bad
19
+ * argument, and it is why these return strings rather than throwing.
20
+ */
21
+ const data_types_1 = require("./data.types");
22
+ /** Operators that make sense per field type. */
23
+ const OPS_BY_TYPE = {
24
+ number: ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'in', 'between', 'isNull', 'notNull'],
25
+ date: ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'in', 'between', 'isNull', 'notNull'],
26
+ string: ['eq', 'ne', 'in', 'contains', 'isNull', 'notNull'],
27
+ enum: ['eq', 'ne', 'in', 'isNull', 'notNull'],
28
+ boolean: ['eq', 'ne', 'isNull', 'notNull'],
29
+ };
30
+ /** Operators that take no value at all. */
31
+ const VALUELESS_OPS = ['isNull', 'notNull'];
32
+ /** Aggregates that need a numeric or date field to mean anything. */
33
+ const NUMERIC_AGGREGATES = ['sum', 'avg'];
34
+ function fail(error, available) {
35
+ return available ? { ok: false, error, available } : { ok: false, error };
36
+ }
37
+ function fieldNames(set) {
38
+ return set.fields.map((field) => field.name);
39
+ }
40
+ function findField(set, name) {
41
+ return set.fields.find((field) => field.name === name);
42
+ }
43
+ /** The name a metric carries in the result rows. */
44
+ function metricName(fn, field, as) {
45
+ if (as) {
46
+ return as;
47
+ }
48
+ return field ? `${fn}_${field}` : fn;
49
+ }
50
+ /**
51
+ * Checks a raw query against a dataset and fills in its defaults.
52
+ *
53
+ * @param raw The query as the model produced it
54
+ * @param sets Every dataset the source declares
55
+ * @returns The validated query, or a refusal naming what was allowed instead
56
+ */
57
+ function validateQuery(raw, sets) {
58
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
59
+ return fail('The query must be a JSON object.');
60
+ }
61
+ const set = sets.find((candidate) => candidate.name === raw.dataset);
62
+ if (!set) {
63
+ return fail(`Unknown dataset "${raw.dataset}". Available datasets:`, sets.map((candidate) => candidate.name));
64
+ }
65
+ const filters = [];
66
+ for (const rawFilter of asArray(raw.filters)) {
67
+ const checked = validateFilter(rawFilter, set);
68
+ if ('error' in checked) {
69
+ return checked.error;
70
+ }
71
+ filters.push(checked.filter);
72
+ }
73
+ const groupBy = [];
74
+ for (const name of asArray(raw.groupBy)) {
75
+ const field = findField(set, String(name));
76
+ if (!field) {
77
+ return fail(`Cannot group by "${name}" — no such field in "${set.name}". Fields:`, fieldNames(set));
78
+ }
79
+ if (field.groupable === false) {
80
+ return fail(`Cannot group by "${name}". Groupable fields:`, set.fields.filter((f) => f.groupable !== false).map((f) => f.name));
81
+ }
82
+ groupBy.push(field.name);
83
+ }
84
+ const metrics = [];
85
+ for (const rawMetric of asArray(raw.metrics)) {
86
+ const checked = validateMetric(rawMetric, set);
87
+ if ('error' in checked) {
88
+ return checked.error;
89
+ }
90
+ metrics.push(checked.metric);
91
+ }
92
+ const select = [];
93
+ for (const name of asArray(raw.select)) {
94
+ const field = findField(set, String(name));
95
+ if (!field) {
96
+ return fail(`Cannot select "${name}" — no such field in "${set.name}". Fields:`, fieldNames(set));
97
+ }
98
+ select.push(field.name);
99
+ }
100
+ // An aggregate answers with its dimensions and its numbers; anything else
101
+ // asked for has no row to come from.
102
+ const isAggregate = groupBy.length > 0 || metrics.length > 0;
103
+ const orderable = isAggregate
104
+ ? [...groupBy, ...metrics.map((m) => m.as)]
105
+ : [...fieldNames(set)];
106
+ const orderBy = [];
107
+ for (const rawOrder of asArray(raw.orderBy)) {
108
+ const by = String(rawOrder?.by ?? '');
109
+ if (!orderable.includes(by)) {
110
+ return fail(`Cannot order by "${by}". ${isAggregate ? 'An aggregate can be ordered by a grouped field or a metric:' : 'Orderable fields:'}`, orderable);
111
+ }
112
+ const dir = String(rawOrder?.dir ?? 'asc').toLowerCase();
113
+ if (dir !== 'asc' && dir !== 'desc') {
114
+ return fail(`Order direction must be "asc" or "desc", not "${rawOrder?.dir}".`);
115
+ }
116
+ orderBy.push({ by, dir: dir });
117
+ }
118
+ return {
119
+ ok: true,
120
+ dataset: set,
121
+ query: {
122
+ dataset: set.name,
123
+ filters,
124
+ groupBy,
125
+ metrics,
126
+ select,
127
+ orderBy,
128
+ limit: resolveLimit(raw.limit, set),
129
+ },
130
+ };
131
+ }
132
+ /** Clamps a requested row count into the dataset's and the engine's bounds. */
133
+ function resolveLimit(requested, set) {
134
+ const ceiling = Math.min(set.maxLimit ?? data_types_1.MAX_ROW_LIMIT, data_types_1.MAX_ROW_LIMIT);
135
+ const asked = Number(requested);
136
+ if (!Number.isFinite(asked) || asked <= 0) {
137
+ return Math.min(set.defaultLimit ?? data_types_1.DEFAULT_ROW_LIMIT, ceiling);
138
+ }
139
+ return Math.min(Math.floor(asked), ceiling);
140
+ }
141
+ function asArray(value) {
142
+ if (value === undefined || value === null) {
143
+ return [];
144
+ }
145
+ return Array.isArray(value) ? value : [value];
146
+ }
147
+ function validateFilter(raw, set) {
148
+ if (!raw || typeof raw !== 'object') {
149
+ return { error: fail('Each filter must be an object of {field, op, value}.') };
150
+ }
151
+ const field = findField(set, String(raw.field ?? ''));
152
+ if (!field) {
153
+ return {
154
+ error: fail(`Cannot filter on "${raw.field}" — no such field in "${set.name}". Fields:`, fieldNames(set)),
155
+ };
156
+ }
157
+ if (field.filterable === false) {
158
+ return {
159
+ error: fail(`Cannot filter on "${field.name}". Filterable fields:`, set.fields.filter((f) => f.filterable !== false).map((f) => f.name)),
160
+ };
161
+ }
162
+ const op = String(raw.op ?? '');
163
+ const allowed = OPS_BY_TYPE[field.type] || [];
164
+ if (!allowed.includes(op)) {
165
+ return {
166
+ error: fail(`Operator "${raw.op}" does not apply to ${field.type} field "${field.name}". Allowed:`, allowed),
167
+ };
168
+ }
169
+ if (VALUELESS_OPS.includes(op)) {
170
+ return { filter: { field: field.name, op } };
171
+ }
172
+ if (raw.value === undefined || raw.value === null) {
173
+ return { error: fail(`Filter on "${field.name}" with "${op}" needs a value.`) };
174
+ }
175
+ if (op === 'in') {
176
+ const values = asArray(raw.value);
177
+ if (values.length === 0) {
178
+ return { error: fail(`Filter on "${field.name}" with "in" needs a non-empty list of values.`) };
179
+ }
180
+ const bad = enumViolation(field, values);
181
+ if (bad) {
182
+ return { error: bad };
183
+ }
184
+ return { filter: { field: field.name, op, value: values } };
185
+ }
186
+ if (op === 'between') {
187
+ const values = asArray(raw.value);
188
+ if (values.length !== 2) {
189
+ return {
190
+ error: fail(`Filter on "${field.name}" with "between" needs exactly two values: [low, high].`),
191
+ };
192
+ }
193
+ return { filter: { field: field.name, op, value: values } };
194
+ }
195
+ const bad = enumViolation(field, [raw.value]);
196
+ if (bad) {
197
+ return { error: bad };
198
+ }
199
+ return { filter: { field: field.name, op, value: raw.value } };
200
+ }
201
+ /** Enum fields accept only what they declared, so a typo is caught here. */
202
+ function enumViolation(field, values) {
203
+ if (field.type !== 'enum' || !field.enumValues?.length) {
204
+ return null;
205
+ }
206
+ for (const value of values) {
207
+ if (!field.enumValues.includes(String(value))) {
208
+ return fail(`"${value}" is not a value of "${field.name}". Allowed:`, field.enumValues);
209
+ }
210
+ }
211
+ return null;
212
+ }
213
+ function validateMetric(raw, set) {
214
+ if (!raw || typeof raw !== 'object') {
215
+ return { error: fail('Each metric must be an object of {fn, field}.') };
216
+ }
217
+ const fn = String(raw.fn ?? '');
218
+ if (!['count', 'sum', 'avg', 'min', 'max'].includes(fn)) {
219
+ return {
220
+ error: fail(`Unknown aggregate "${raw.fn}". Available:`, ['count', 'sum', 'avg', 'min', 'max']),
221
+ };
222
+ }
223
+ // `count` alone counts rows, which needs no field and is always allowed.
224
+ if (fn === 'count' && (raw.field === undefined || raw.field === null || raw.field === '')) {
225
+ return { metric: { fn, as: metricName(fn, undefined, raw.as) } };
226
+ }
227
+ const field = findField(set, String(raw.field ?? ''));
228
+ if (!field) {
229
+ return {
230
+ error: fail(`Cannot ${fn} "${raw.field}" — no such field in "${set.name}". Fields:`, fieldNames(set)),
231
+ };
232
+ }
233
+ if (!field.aggregates?.includes(fn)) {
234
+ const capable = set.fields.filter((f) => f.aggregates?.includes(fn)).map((f) => f.name);
235
+ return {
236
+ error: fail(capable.length
237
+ ? `Cannot ${fn} "${field.name}". Fields that support ${fn}:`
238
+ : `Cannot ${fn} "${field.name}", and no field in "${set.name}" supports ${fn}.`, capable.length ? capable : undefined),
239
+ };
240
+ }
241
+ if (NUMERIC_AGGREGATES.includes(fn) && field.type !== 'number') {
242
+ return { error: fail(`Cannot ${fn} "${field.name}" — it is a ${field.type}, not a number.`) };
243
+ }
244
+ return { metric: { fn, field: field.name, as: metricName(fn, field.name, raw.as) } };
245
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Turning an uploaded file into Markdown pages, whatever kind of file it was.
3
+ *
4
+ * PDFs go through the per-page AI conversion in `pdf-conversion.ts`, because a
5
+ * PDF is a picture of a page and needs reading. Word and Excel files do not: they
6
+ * already carry their text and structure, so they convert locally, instantly and
7
+ * for nothing. This module owns that local half, plus the one decision both
8
+ * halves depend on — what kind of file this actually is.
9
+ *
10
+ * That decision is the part worth getting right. A host that assumed "not a PDF,
11
+ * so text" would decode a .docx as UTF-8 and hand an agent a page of mojibake,
12
+ * which the agent then summarises with complete confidence. So an unrecognised
13
+ * file is refused with a reason a person can act on, never guessed at.
14
+ *
15
+ * Page numbers mean what a reader would expect. A PDF has real pages. A Word
16
+ * document does not — its pagination is decided by whatever renders it — so it
17
+ * comes back as one page, and an agent locates a passage by its heading instead
18
+ * of by a page number that would not match the user's screen. A workbook comes
19
+ * back as one page per visible sheet, labelled with the sheet's name.
20
+ */
21
+ /** What a file turned out to be. */
22
+ export type DocumentFileType = 'pdf' | 'docx' | 'xlsx' | 'text' | 'unsupported';
23
+ export interface DocumentTypeDetection {
24
+ type: DocumentFileType;
25
+ /** Why the file cannot be read, phrased for the person who uploaded it. Set only when unsupported. */
26
+ reason?: string;
27
+ }
28
+ /** One page of a converted document. */
29
+ export interface DocumentPage {
30
+ /** 1-based. For a workbook, the sheet's position among the sheets converted. */
31
+ pageNum: number;
32
+ markdown: string;
33
+ /** A name for the page when it has one — a workbook's sheet name. */
34
+ label?: string;
35
+ }
36
+ /** A locally converted document. PDFs are not produced here; see `convertPdfToMarkdownPages`. */
37
+ export interface LocalDocumentConversion {
38
+ type: 'docx' | 'xlsx' | 'text';
39
+ pages: DocumentPage[];
40
+ /** The pages assembled with `<!-- Page N -->` markers, the same format the PDF path writes. */
41
+ markdown: string;
42
+ /** Things the reader should know were changed or left out: hidden sheets, truncated rows, images. */
43
+ warnings: string[];
44
+ }
45
+ export interface LocalConversionOptions {
46
+ /**
47
+ * Rows kept per worksheet. A sheet past this is cut, and the cut is stated in
48
+ * the page and in `warnings` — a silently shortened schedule reads as complete.
49
+ * Defaults to 5,000.
50
+ */
51
+ maxRowsPerSheet?: number;
52
+ }
53
+ /** Thrown for a file that cannot be read. `message` is written for the person who uploaded it. */
54
+ export declare class UnsupportedDocumentError extends Error {
55
+ constructor(message: string);
56
+ }
57
+ /**
58
+ * Decides what a file is from its contents, using the name only to break ties.
59
+ *
60
+ * .docx and .xlsx are both ZIP archives, so their magic bytes are identical; the
61
+ * archive's entries are what tell them apart. The extension alone is never
62
+ * trusted over the contents — a renamed file is refused rather than misread.
63
+ */
64
+ export declare function detectDocumentType(bytes: Uint8Array, fileName: string): DocumentTypeDetection;
65
+ /**
66
+ * Converts a Word, Excel or plain-text file to Markdown pages, locally.
67
+ *
68
+ * @throws {UnsupportedDocumentError} For a PDF (which needs the AI path) or anything unreadable
69
+ */
70
+ export declare function convertLocalDocument(bytes: Uint8Array, fileName: string, options?: LocalConversionOptions): Promise<LocalDocumentConversion>;