briyah 2.0.4 → 2.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/README.md +12 -1
  2. package/data/common/config/markup +1 -1
  3. package/data/common/config/story_models.json +3 -3
  4. package/data/common/prompts/illustrator/describe_scene.prompt +4 -4
  5. package/data/common/prompts/moderate.json +34 -0
  6. package/data/common/prompts/moderate.prompt +136 -0
  7. package/data/common/prompts/perceive.prompt +1 -1
  8. package/data/packs/dnd5e/prompts/battle_master/perceive.prompt +1 -1
  9. package/data/packs/dnd5e/prompts/campaign_designer/perceive.prompt +1 -1
  10. package/data/packs/dnd5e/prompts/character_creator/perceive.prompt +795 -787
  11. package/data/packs/dnd5e/prompts/dungeon_master/defaults_config.json +2 -1
  12. package/data/packs/dnd5e/prompts/dungeon_master/perceive.prompt +1 -1
  13. package/data/packs/dnd5e/rooms/campaign.json +18 -15
  14. package/data/packs/dnd5e/rooms/table.json +17 -16
  15. package/dist-sdk/server/src/ai/LLM/anthropic.service.js +1 -1
  16. package/dist-sdk/server/src/ai/LLM/base-ai.service.d.ts +38 -0
  17. package/dist-sdk/server/src/ai/LLM/base-ai.service.js +83 -16
  18. package/dist-sdk/server/src/ai/LLM/blank-image.d.ts +36 -0
  19. package/dist-sdk/server/src/ai/LLM/blank-image.js +80 -0
  20. package/dist-sdk/server/src/ai/LLM/deepseek.service.js +1 -1
  21. package/dist-sdk/server/src/ai/LLM/fal.service.js +1 -1
  22. package/dist-sdk/server/src/ai/LLM/googleai.service.js +1 -1
  23. package/dist-sdk/server/src/ai/LLM/grok.service.js +1 -1
  24. package/dist-sdk/server/src/ai/LLM/openai.service.js +1 -1
  25. package/dist-sdk/server/src/ai/LLM/self-hosted.service.js +1 -1
  26. package/dist-sdk/server/src/ai/LLM/together.service.js +1 -1
  27. package/dist-sdk/server/src/ai/agent-config.d.ts +0 -1
  28. package/dist-sdk/server/src/ai/agent-store.service.js +2 -4
  29. package/dist-sdk/server/src/ai/agent.d.ts +7 -2
  30. package/dist-sdk/server/src/ai/agent.js +11 -3
  31. package/dist-sdk/server/src/app/user-service-factory.js +8 -2
  32. package/dist-sdk/server/src/app.controller.d.ts +33 -0
  33. package/dist-sdk/server/src/app.controller.js +93 -2
  34. package/dist-sdk/server/src/app.service.d.ts +49 -4
  35. package/dist-sdk/server/src/app.service.js +101 -16
  36. package/dist-sdk/server/src/auth/jwt-auth.guard.js +26 -0
  37. package/dist-sdk/server/src/data/data-guide.builder.d.ts +2 -0
  38. package/dist-sdk/server/src/data/data-guide.builder.js +90 -0
  39. package/dist-sdk/server/src/data/data-registry.d.ts +32 -0
  40. package/dist-sdk/server/src/data/data-registry.js +61 -0
  41. package/dist-sdk/server/src/data/data.types.d.ts +158 -0
  42. package/dist-sdk/server/src/data/data.types.js +24 -0
  43. package/dist-sdk/server/src/data/query-validation.d.ts +45 -0
  44. package/dist-sdk/server/src/data/query-validation.js +245 -0
  45. package/dist-sdk/server/src/packs/pack-instantiation.service.js +5 -0
  46. package/dist-sdk/server/src/packs/pack-manifest.d.ts +14 -0
  47. package/dist-sdk/server/src/packs/pack-manifest.js +11 -0
  48. package/dist-sdk/server/src/room/illustration/illustration.service.d.ts +211 -0
  49. package/dist-sdk/server/src/room/illustration/illustration.service.js +771 -0
  50. package/dist-sdk/server/src/room/illustration/illustration.types.d.ts +101 -0
  51. package/dist-sdk/server/src/room/illustration/illustration.types.js +2 -0
  52. package/dist-sdk/server/src/room/room-config.d.ts +58 -1
  53. package/dist-sdk/server/src/room/room-config.js +19 -0
  54. package/dist-sdk/server/src/room/room-factory.d.ts +8 -0
  55. package/dist-sdk/server/src/room/room-factory.js +11 -0
  56. package/dist-sdk/server/src/room/room-store.service.d.ts +8 -0
  57. package/dist-sdk/server/src/room/room-store.service.js +43 -2
  58. package/dist-sdk/server/src/room/room.d.ts +110 -6
  59. package/dist-sdk/server/src/room/room.js +277 -10
  60. package/dist-sdk/server/src/rpg/rpg.service.js +5 -1
  61. package/dist-sdk/server/src/sdk/index.d.ts +4 -0
  62. package/dist-sdk/server/src/sdk/index.js +11 -1
  63. package/dist-sdk/server/src/story/story.service.d.ts +24 -65
  64. package/dist-sdk/server/src/story/story.service.js +105 -458
  65. package/dist-sdk/server/src/tools/core/data.tools.d.ts +17 -0
  66. package/dist-sdk/server/src/tools/core/data.tools.js +165 -0
  67. package/dist-sdk/server/src/tools/core/illustrate.tool.d.ts +14 -0
  68. package/dist-sdk/server/src/tools/core/illustrate.tool.js +80 -0
  69. package/dist-sdk/server/src/tools/core/index.js +3 -1
  70. package/dist-sdk/server/src/tools/native-tool.types.d.ts +90 -0
  71. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.d.ts +9 -0
  72. package/dist-sdk/server/src/tools/packs/dnd5e/engine/sheet.js +5 -0
  73. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.d.ts +30 -0
  74. package/dist-sdk/server/src/tools/packs/dnd5e/tools/shared.js +75 -0
  75. package/dist-sdk/server/src/tools/packs/dnd5e/tools/sheet.tools.js +11 -2
  76. package/dist-sdk/server/src/tools/tool-execution.service.d.ts +36 -5
  77. package/dist-sdk/server/src/tools/tool-execution.service.js +91 -21
  78. package/dist-sdk/shared/types/app.types.d.ts +43 -0
  79. package/dist-sdk/shared/types/app.types.js +15 -1
  80. package/package.json +1 -1
@@ -0,0 +1,32 @@
1
+ /**
2
+ * The process-global registry of host data sources.
3
+ *
4
+ * Module state rather than an injectable, for the same reason
5
+ * {@link NativeToolRegistry} is process-global: a data source is registered once
6
+ * by the host at boot and is the same for every room, and a tool handler runs
7
+ * with no Nest scope to inject into. Per-user and per-tenant scoping does not
8
+ * belong here — it rides the opaque tool context, which is the only thing that
9
+ * knows *whose* data a call is for.
10
+ */
11
+ import { DataSet, DataSource } from './data.types';
12
+ /**
13
+ * Registers (or replaces) a data source.
14
+ *
15
+ * Dataset names are global: two sources cannot both offer `claims`, because an
16
+ * agent names a dataset and nothing else, so a duplicate would be ambiguous at
17
+ * exactly the moment it mattered.
18
+ * @param source The host's data source
19
+ */
20
+ export declare function registerDataSource(source: DataSource): void;
21
+ /** Removes a data source. @returns True if one was removed */
22
+ export declare function unregisterDataSource(name: string): boolean;
23
+ /** @returns Every registered source, in registration order */
24
+ export declare function listDataSources(): DataSource[];
25
+ /** @returns Every dataset any source offers, flattened as an agent sees them */
26
+ export declare function listDatasets(): DataSet[];
27
+ /** @returns The source that owns a dataset, or undefined */
28
+ export declare function sourceForDataset(datasetName: string): DataSource | undefined;
29
+ /** @returns Whether any source is registered — the tools say so rather than failing oddly */
30
+ export declare function hasDataSources(): boolean;
31
+ /** Test seam. */
32
+ export declare function resetDataSources(): void;
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.registerDataSource = registerDataSource;
4
+ exports.unregisterDataSource = unregisterDataSource;
5
+ exports.listDataSources = listDataSources;
6
+ exports.listDatasets = listDatasets;
7
+ exports.sourceForDataset = sourceForDataset;
8
+ exports.hasDataSources = hasDataSources;
9
+ exports.resetDataSources = resetDataSources;
10
+ const logger_1 = require("../common/logger");
11
+ const sources = new Map();
12
+ /**
13
+ * Registers (or replaces) a data source.
14
+ *
15
+ * Dataset names are global: two sources cannot both offer `claims`, because an
16
+ * agent names a dataset and nothing else, so a duplicate would be ambiguous at
17
+ * exactly the moment it mattered.
18
+ * @param source The host's data source
19
+ */
20
+ function registerDataSource(source) {
21
+ if (!source?.name) {
22
+ throw new Error('A data source needs a name');
23
+ }
24
+ if (typeof source.execute !== 'function') {
25
+ throw new Error(`Data source "${source.name}" must have an execute function`);
26
+ }
27
+ for (const set of source.datasets || []) {
28
+ const owner = sourceForDataset(set.name);
29
+ if (owner && owner.name !== source.name) {
30
+ throw new Error(`Dataset "${set.name}" is already offered by data source "${owner.name}"`);
31
+ }
32
+ }
33
+ if (sources.has(source.name)) {
34
+ logger_1.logger.warn(`Data source "${source.name}" is already registered; overwriting`);
35
+ }
36
+ sources.set(source.name, source);
37
+ }
38
+ /** Removes a data source. @returns True if one was removed */
39
+ function unregisterDataSource(name) {
40
+ return sources.delete(name);
41
+ }
42
+ /** @returns Every registered source, in registration order */
43
+ function listDataSources() {
44
+ return [...sources.values()];
45
+ }
46
+ /** @returns Every dataset any source offers, flattened as an agent sees them */
47
+ function listDatasets() {
48
+ return listDataSources().flatMap((source) => source.datasets || []);
49
+ }
50
+ /** @returns The source that owns a dataset, or undefined */
51
+ function sourceForDataset(datasetName) {
52
+ return listDataSources().find((source) => (source.datasets || []).some((set) => set.name === datasetName));
53
+ }
54
+ /** @returns Whether any source is registered — the tools say so rather than failing oddly */
55
+ function hasDataSources() {
56
+ return sources.size > 0;
57
+ }
58
+ /** Test seam. */
59
+ function resetDataSources() {
60
+ sources.clear();
61
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * The shape of a host's queryable data, and of the questions an agent may ask
3
+ * about it.
4
+ *
5
+ * Briyah owns the protocol and the safety properties; the host owns the data. A
6
+ * host describes its datasets and supplies one {@link DataSource.execute}, and
7
+ * gets a validated, bounded, read-only query capability without writing a tool,
8
+ * a validator, a prompt schema or a result envelope.
9
+ *
10
+ * The safety model is *construction*, not inspection. An agent never writes a
11
+ * query language — it fills in {@link DataQuery}, whose every field name is
12
+ * looked up in the dataset's declared {@link DataField} list before the host
13
+ * sees it. A name that was not declared cannot reach the host, so a host's
14
+ * executor can treat a validated query as trusted input and never has to parse
15
+ * or sanitize anything a model wrote. That is what makes it safe to run against
16
+ * a database with no read-only role behind it.
17
+ */
18
+ /** What kind of value a field holds, and therefore how it may be compared. */
19
+ export type DataFieldType = 'string' | 'number' | 'boolean' | 'date' | 'enum';
20
+ /** The aggregate functions a query may ask for. */
21
+ export type DataAggregateFn = 'count' | 'sum' | 'avg' | 'min' | 'max';
22
+ /**
23
+ * How a filter compares a field to a value.
24
+ *
25
+ * Deliberately small: everything here maps onto something every store can do,
26
+ * and nothing here can express a subquery, a join the host did not declare, or
27
+ * a raw expression.
28
+ */
29
+ export type DataFilterOp = 'eq' | 'ne' | 'lt' | 'lte' | 'gt' | 'gte' | 'in' | 'contains' | 'between' | 'isNull' | 'notNull';
30
+ /**
31
+ * One queryable field.
32
+ *
33
+ * A field is not required to be a stored column. A host may declare a *derived*
34
+ * field — an age computed from a date of birth, a total computed from five
35
+ * columns — and translate it in its executor. Declaring it here is what keeps
36
+ * the arithmetic out of the model, which is the difference between an answer
37
+ * that is right and one that is plausible.
38
+ */
39
+ export interface DataField {
40
+ /** The name an agent uses. Stable; it appears in prompts and saved queries. */
41
+ name: string;
42
+ type: DataFieldType;
43
+ /** Human-facing name for the schema guide. Falls back to `name`. */
44
+ label?: string;
45
+ /** What the field means, and anything an agent would otherwise assume wrongly. */
46
+ description?: string;
47
+ /** For `enum`, the values it may hold. Rendered into the guide and enforced. */
48
+ enumValues?: string[];
49
+ /** May appear in `filters`. Default true. */
50
+ filterable?: boolean;
51
+ /** May appear in `groupBy` or be selected as a dimension. Default true. */
52
+ groupable?: boolean;
53
+ /**
54
+ * The aggregate functions allowed on this field. Omit for none — a field
55
+ * nothing can be summed over, like a name.
56
+ */
57
+ aggregates?: DataAggregateFn[];
58
+ }
59
+ /** One queryable collection of records. */
60
+ export interface DataSet {
61
+ /** The name an agent uses. */
62
+ name: string;
63
+ /** Human-facing name for the schema guide. Falls back to `name`. */
64
+ label?: string;
65
+ /** One or two sentences: what one row is, and what the set covers. */
66
+ description: string;
67
+ fields: DataField[];
68
+ /**
69
+ * Things an agent must know to read an answer correctly, rendered verbatim
70
+ * into the schema guide. This is the place to say what a set silently
71
+ * excludes, which of two plausible definitions a metric uses, and — just as
72
+ * importantly — what it is *not* related to, so an agent refuses a question
73
+ * instead of inventing a way to answer it.
74
+ */
75
+ notes?: string[];
76
+ /** Rows returned when a query names no limit. Defaults to {@link DEFAULT_ROW_LIMIT}. */
77
+ defaultLimit?: number;
78
+ /** The most rows this set will ever return, whatever a query asks for. */
79
+ maxLimit?: number;
80
+ }
81
+ /** One comparison in a query. */
82
+ export interface DataFilter {
83
+ field: string;
84
+ op: DataFilterOp;
85
+ /** Omitted for `isNull`/`notNull`; an array for `in` and `between`. */
86
+ value?: any;
87
+ }
88
+ /** One aggregate in a query. */
89
+ export interface DataMetric {
90
+ fn: DataAggregateFn;
91
+ /** Omitted only for `count`, which counts rows. */
92
+ field?: string;
93
+ /** The name this metric has in the result rows. Defaults to `fn_field`. */
94
+ as?: string;
95
+ }
96
+ /** How to order a result. */
97
+ export interface DataOrder {
98
+ /** A grouped field's name, or a metric's `as` name. */
99
+ by: string;
100
+ dir?: 'asc' | 'desc';
101
+ }
102
+ /**
103
+ * A question, as an agent asks it.
104
+ *
105
+ * With no `groupBy` and no `metrics` this is a plain listing of rows. With
106
+ * either, it is an aggregate: `groupBy` names the dimensions and `metrics` the
107
+ * numbers, exactly as a pivot table would.
108
+ */
109
+ export interface DataQuery {
110
+ dataset: string;
111
+ filters?: DataFilter[];
112
+ groupBy?: string[];
113
+ metrics?: DataMetric[];
114
+ /** Fields to return when this is a listing rather than an aggregate. */
115
+ select?: string[];
116
+ orderBy?: DataOrder[];
117
+ limit?: number;
118
+ }
119
+ /** One row of a result. Keys are field names, metric `as` names, or both. */
120
+ export type DataRow = Record<string, any>;
121
+ /** What a host's executor hands back. */
122
+ export interface DataResult {
123
+ rows: DataRow[];
124
+ /**
125
+ * Total rows the query matched, when the host can say cheaply. Lets an
126
+ * answer say "the top 10 of 240" rather than implying it saw everything.
127
+ */
128
+ totalRows?: number;
129
+ }
130
+ /**
131
+ * A host's queryable data.
132
+ *
133
+ * `execute` is only ever called with a query that has already been validated
134
+ * against the named dataset: every field exists, every operator is allowed on
135
+ * it, every enum value is one of the declared ones, and the limit is within the
136
+ * set's cap. A host does not need to re-check any of that, and must not accept
137
+ * a query from anywhere else.
138
+ */
139
+ export interface DataSource {
140
+ /** Identifies the source in logs and in the schema guide's title. */
141
+ name: string;
142
+ /** Shown at the top of the schema guide. */
143
+ description?: string;
144
+ datasets: DataSet[];
145
+ /**
146
+ * Runs one validated query.
147
+ * @param query The validated query
148
+ * @param context The host's opaque per-invocation context, threaded from
149
+ * `sendRoomMessage` — where the tenant scoping lives. Never anything the
150
+ * model supplied.
151
+ * @returns The rows, and the total when it is cheap to know
152
+ */
153
+ execute(query: DataQuery, context: unknown): Promise<DataResult>;
154
+ }
155
+ /** Rows returned when neither the query nor the dataset names a limit. */
156
+ export declare const DEFAULT_ROW_LIMIT = 50;
157
+ /** The ceiling no dataset's `maxLimit` may exceed. */
158
+ export declare const MAX_ROW_LIMIT = 1000;
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ /**
3
+ * The shape of a host's queryable data, and of the questions an agent may ask
4
+ * about it.
5
+ *
6
+ * Briyah owns the protocol and the safety properties; the host owns the data. A
7
+ * host describes its datasets and supplies one {@link DataSource.execute}, and
8
+ * gets a validated, bounded, read-only query capability without writing a tool,
9
+ * a validator, a prompt schema or a result envelope.
10
+ *
11
+ * The safety model is *construction*, not inspection. An agent never writes a
12
+ * query language — it fills in {@link DataQuery}, whose every field name is
13
+ * looked up in the dataset's declared {@link DataField} list before the host
14
+ * sees it. A name that was not declared cannot reach the host, so a host's
15
+ * executor can treat a validated query as trusted input and never has to parse
16
+ * or sanitize anything a model wrote. That is what makes it safe to run against
17
+ * a database with no read-only role behind it.
18
+ */
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.MAX_ROW_LIMIT = exports.DEFAULT_ROW_LIMIT = void 0;
21
+ /** Rows returned when neither the query nor the dataset names a limit. */
22
+ exports.DEFAULT_ROW_LIMIT = 50;
23
+ /** The ceiling no dataset's `maxLimit` may exceed. */
24
+ exports.MAX_ROW_LIMIT = 1_000;
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Turns whatever a model produced into a query a host can trust, or into an
3
+ * error the model can act on.
4
+ *
5
+ * Two rules shape everything here.
6
+ *
7
+ * **Nothing undeclared survives.** Every dataset, field, operator, enum value
8
+ * and aggregate is checked against the host's {@link DataSet} before the query
9
+ * is handed on. A host's executor therefore never sees a name it did not
10
+ * declare, which is what lets it build a statement without sanitizing anything.
11
+ *
12
+ * **A rejection names the alternatives.** "Unknown field" teaches a model
13
+ * nothing and it guesses again; "unknown field X — this set has A, B, C" is
14
+ * repaired on the next turn. This mirrors how the rest of Briyah answers a bad
15
+ * argument, and it is why these return strings rather than throwing.
16
+ */
17
+ import { DataAggregateFn, DataQuery, DataSet } from './data.types';
18
+ /**
19
+ * A validated query, or the reason it was refused.
20
+ *
21
+ * One shape with optional halves rather than a discriminated union: this
22
+ * package compiles with `strictNullChecks` off, where narrowing on a boolean
23
+ * discriminant does not hold, so a union would force a cast at every use.
24
+ */
25
+ export interface ValidationResult {
26
+ ok: boolean;
27
+ /** The normalized query. Present when `ok`. */
28
+ query?: DataQuery;
29
+ /** The dataset it names. Present when `ok`. */
30
+ dataset?: DataSet;
31
+ /** Why it was refused. Present when not `ok`. */
32
+ error?: string;
33
+ /** What could have been used instead, when naming them helps. */
34
+ available?: string[];
35
+ }
36
+ /** The name a metric carries in the result rows. */
37
+ export declare function metricName(fn: DataAggregateFn, field?: string, as?: string): string;
38
+ /**
39
+ * Checks a raw query against a dataset and fills in its defaults.
40
+ *
41
+ * @param raw The query as the model produced it
42
+ * @param sets Every dataset the source declares
43
+ * @returns The validated query, or a refusal naming what was allowed instead
44
+ */
45
+ export declare function validateQuery(raw: any, sets: DataSet[]): ValidationResult;
@@ -0,0 +1,245 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.metricName = metricName;
4
+ exports.validateQuery = validateQuery;
5
+ /**
6
+ * Turns whatever a model produced into a query a host can trust, or into an
7
+ * error the model can act on.
8
+ *
9
+ * Two rules shape everything here.
10
+ *
11
+ * **Nothing undeclared survives.** Every dataset, field, operator, enum value
12
+ * and aggregate is checked against the host's {@link DataSet} before the query
13
+ * is handed on. A host's executor therefore never sees a name it did not
14
+ * declare, which is what lets it build a statement without sanitizing anything.
15
+ *
16
+ * **A rejection names the alternatives.** "Unknown field" teaches a model
17
+ * nothing and it guesses again; "unknown field X — this set has A, B, C" is
18
+ * repaired on the next turn. This mirrors how the rest of Briyah answers a bad
19
+ * argument, and it is why these return strings rather than throwing.
20
+ */
21
+ const data_types_1 = require("./data.types");
22
+ /** Operators that make sense per field type. */
23
+ const OPS_BY_TYPE = {
24
+ number: ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'in', 'between', 'isNull', 'notNull'],
25
+ date: ['eq', 'ne', 'lt', 'lte', 'gt', 'gte', 'in', 'between', 'isNull', 'notNull'],
26
+ string: ['eq', 'ne', 'in', 'contains', 'isNull', 'notNull'],
27
+ enum: ['eq', 'ne', 'in', 'isNull', 'notNull'],
28
+ boolean: ['eq', 'ne', 'isNull', 'notNull'],
29
+ };
30
+ /** Operators that take no value at all. */
31
+ const VALUELESS_OPS = ['isNull', 'notNull'];
32
+ /** Aggregates that need a numeric or date field to mean anything. */
33
+ const NUMERIC_AGGREGATES = ['sum', 'avg'];
34
+ function fail(error, available) {
35
+ return available ? { ok: false, error, available } : { ok: false, error };
36
+ }
37
+ function fieldNames(set) {
38
+ return set.fields.map((field) => field.name);
39
+ }
40
+ function findField(set, name) {
41
+ return set.fields.find((field) => field.name === name);
42
+ }
43
+ /** The name a metric carries in the result rows. */
44
+ function metricName(fn, field, as) {
45
+ if (as) {
46
+ return as;
47
+ }
48
+ return field ? `${fn}_${field}` : fn;
49
+ }
50
+ /**
51
+ * Checks a raw query against a dataset and fills in its defaults.
52
+ *
53
+ * @param raw The query as the model produced it
54
+ * @param sets Every dataset the source declares
55
+ * @returns The validated query, or a refusal naming what was allowed instead
56
+ */
57
+ function validateQuery(raw, sets) {
58
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
59
+ return fail('The query must be a JSON object.');
60
+ }
61
+ const set = sets.find((candidate) => candidate.name === raw.dataset);
62
+ if (!set) {
63
+ return fail(`Unknown dataset "${raw.dataset}". Available datasets:`, sets.map((candidate) => candidate.name));
64
+ }
65
+ const filters = [];
66
+ for (const rawFilter of asArray(raw.filters)) {
67
+ const checked = validateFilter(rawFilter, set);
68
+ if ('error' in checked) {
69
+ return checked.error;
70
+ }
71
+ filters.push(checked.filter);
72
+ }
73
+ const groupBy = [];
74
+ for (const name of asArray(raw.groupBy)) {
75
+ const field = findField(set, String(name));
76
+ if (!field) {
77
+ return fail(`Cannot group by "${name}" — no such field in "${set.name}". Fields:`, fieldNames(set));
78
+ }
79
+ if (field.groupable === false) {
80
+ return fail(`Cannot group by "${name}". Groupable fields:`, set.fields.filter((f) => f.groupable !== false).map((f) => f.name));
81
+ }
82
+ groupBy.push(field.name);
83
+ }
84
+ const metrics = [];
85
+ for (const rawMetric of asArray(raw.metrics)) {
86
+ const checked = validateMetric(rawMetric, set);
87
+ if ('error' in checked) {
88
+ return checked.error;
89
+ }
90
+ metrics.push(checked.metric);
91
+ }
92
+ const select = [];
93
+ for (const name of asArray(raw.select)) {
94
+ const field = findField(set, String(name));
95
+ if (!field) {
96
+ return fail(`Cannot select "${name}" — no such field in "${set.name}". Fields:`, fieldNames(set));
97
+ }
98
+ select.push(field.name);
99
+ }
100
+ // An aggregate answers with its dimensions and its numbers; anything else
101
+ // asked for has no row to come from.
102
+ const isAggregate = groupBy.length > 0 || metrics.length > 0;
103
+ const orderable = isAggregate
104
+ ? [...groupBy, ...metrics.map((m) => m.as)]
105
+ : [...fieldNames(set)];
106
+ const orderBy = [];
107
+ for (const rawOrder of asArray(raw.orderBy)) {
108
+ const by = String(rawOrder?.by ?? '');
109
+ if (!orderable.includes(by)) {
110
+ return fail(`Cannot order by "${by}". ${isAggregate ? 'An aggregate can be ordered by a grouped field or a metric:' : 'Orderable fields:'}`, orderable);
111
+ }
112
+ const dir = String(rawOrder?.dir ?? 'asc').toLowerCase();
113
+ if (dir !== 'asc' && dir !== 'desc') {
114
+ return fail(`Order direction must be "asc" or "desc", not "${rawOrder?.dir}".`);
115
+ }
116
+ orderBy.push({ by, dir: dir });
117
+ }
118
+ return {
119
+ ok: true,
120
+ dataset: set,
121
+ query: {
122
+ dataset: set.name,
123
+ filters,
124
+ groupBy,
125
+ metrics,
126
+ select,
127
+ orderBy,
128
+ limit: resolveLimit(raw.limit, set),
129
+ },
130
+ };
131
+ }
132
+ /** Clamps a requested row count into the dataset's and the engine's bounds. */
133
+ function resolveLimit(requested, set) {
134
+ const ceiling = Math.min(set.maxLimit ?? data_types_1.MAX_ROW_LIMIT, data_types_1.MAX_ROW_LIMIT);
135
+ const asked = Number(requested);
136
+ if (!Number.isFinite(asked) || asked <= 0) {
137
+ return Math.min(set.defaultLimit ?? data_types_1.DEFAULT_ROW_LIMIT, ceiling);
138
+ }
139
+ return Math.min(Math.floor(asked), ceiling);
140
+ }
141
+ function asArray(value) {
142
+ if (value === undefined || value === null) {
143
+ return [];
144
+ }
145
+ return Array.isArray(value) ? value : [value];
146
+ }
147
+ function validateFilter(raw, set) {
148
+ if (!raw || typeof raw !== 'object') {
149
+ return { error: fail('Each filter must be an object of {field, op, value}.') };
150
+ }
151
+ const field = findField(set, String(raw.field ?? ''));
152
+ if (!field) {
153
+ return {
154
+ error: fail(`Cannot filter on "${raw.field}" — no such field in "${set.name}". Fields:`, fieldNames(set)),
155
+ };
156
+ }
157
+ if (field.filterable === false) {
158
+ return {
159
+ error: fail(`Cannot filter on "${field.name}". Filterable fields:`, set.fields.filter((f) => f.filterable !== false).map((f) => f.name)),
160
+ };
161
+ }
162
+ const op = String(raw.op ?? '');
163
+ const allowed = OPS_BY_TYPE[field.type] || [];
164
+ if (!allowed.includes(op)) {
165
+ return {
166
+ error: fail(`Operator "${raw.op}" does not apply to ${field.type} field "${field.name}". Allowed:`, allowed),
167
+ };
168
+ }
169
+ if (VALUELESS_OPS.includes(op)) {
170
+ return { filter: { field: field.name, op } };
171
+ }
172
+ if (raw.value === undefined || raw.value === null) {
173
+ return { error: fail(`Filter on "${field.name}" with "${op}" needs a value.`) };
174
+ }
175
+ if (op === 'in') {
176
+ const values = asArray(raw.value);
177
+ if (values.length === 0) {
178
+ return { error: fail(`Filter on "${field.name}" with "in" needs a non-empty list of values.`) };
179
+ }
180
+ const bad = enumViolation(field, values);
181
+ if (bad) {
182
+ return { error: bad };
183
+ }
184
+ return { filter: { field: field.name, op, value: values } };
185
+ }
186
+ if (op === 'between') {
187
+ const values = asArray(raw.value);
188
+ if (values.length !== 2) {
189
+ return {
190
+ error: fail(`Filter on "${field.name}" with "between" needs exactly two values: [low, high].`),
191
+ };
192
+ }
193
+ return { filter: { field: field.name, op, value: values } };
194
+ }
195
+ const bad = enumViolation(field, [raw.value]);
196
+ if (bad) {
197
+ return { error: bad };
198
+ }
199
+ return { filter: { field: field.name, op, value: raw.value } };
200
+ }
201
+ /** Enum fields accept only what they declared, so a typo is caught here. */
202
+ function enumViolation(field, values) {
203
+ if (field.type !== 'enum' || !field.enumValues?.length) {
204
+ return null;
205
+ }
206
+ for (const value of values) {
207
+ if (!field.enumValues.includes(String(value))) {
208
+ return fail(`"${value}" is not a value of "${field.name}". Allowed:`, field.enumValues);
209
+ }
210
+ }
211
+ return null;
212
+ }
213
+ function validateMetric(raw, set) {
214
+ if (!raw || typeof raw !== 'object') {
215
+ return { error: fail('Each metric must be an object of {fn, field}.') };
216
+ }
217
+ const fn = String(raw.fn ?? '');
218
+ if (!['count', 'sum', 'avg', 'min', 'max'].includes(fn)) {
219
+ return {
220
+ error: fail(`Unknown aggregate "${raw.fn}". Available:`, ['count', 'sum', 'avg', 'min', 'max']),
221
+ };
222
+ }
223
+ // `count` alone counts rows, which needs no field and is always allowed.
224
+ if (fn === 'count' && (raw.field === undefined || raw.field === null || raw.field === '')) {
225
+ return { metric: { fn, as: metricName(fn, undefined, raw.as) } };
226
+ }
227
+ const field = findField(set, String(raw.field ?? ''));
228
+ if (!field) {
229
+ return {
230
+ error: fail(`Cannot ${fn} "${raw.field}" — no such field in "${set.name}". Fields:`, fieldNames(set)),
231
+ };
232
+ }
233
+ if (!field.aggregates?.includes(fn)) {
234
+ const capable = set.fields.filter((f) => f.aggregates?.includes(fn)).map((f) => f.name);
235
+ return {
236
+ error: fail(capable.length
237
+ ? `Cannot ${fn} "${field.name}". Fields that support ${fn}:`
238
+ : `Cannot ${fn} "${field.name}", and no field in "${set.name}" supports ${fn}.`, capable.length ? capable : undefined),
239
+ };
240
+ }
241
+ if (NUMERIC_AGGREGATES.includes(fn) && field.type !== 'number') {
242
+ return { error: fail(`Cannot ${fn} "${field.name}" — it is a ${field.type}, not a number.`) };
243
+ }
244
+ return { metric: { fn, field: field.name, as: metricName(fn, field.name, raw.as) } };
245
+ }
@@ -121,6 +121,11 @@ class PackInstantiationService {
121
121
  moderator: moderatorKey ? (nicknames.get(moderatorKey) ?? '') : '',
122
122
  pack: packName,
123
123
  packRoomKey: template.key,
124
+ beginInstruction: template.beginInstruction ?? '',
125
+ // A template that names neither leaves the room on the server's
126
+ // default model, drawing only when an agent asks.
127
+ imageModel: template.imageModel,
128
+ illustrationMode: template.illustrationMode ?? 'on-request',
124
129
  });
125
130
  room.saveMetadata();
126
131
  return { roomId, agentIds, warnings };
@@ -96,6 +96,13 @@ export interface PackRoomTemplate {
96
96
  name: string;
97
97
  goal: string;
98
98
  turnMode?: 'broadcast' | 'directed';
99
+ /**
100
+ * Which entry in `image_models.json` draws this room, when the pack wants a
101
+ * particular one. Absent leaves the room on the server default.
102
+ */
103
+ imageModel?: string;
104
+ /** When the room illustrates itself. Absent means `on-request`. */
105
+ illustrationMode?: 'off' | 'on-request' | 'auto';
99
106
  /**
100
107
  * The roster, as loaded.
101
108
  *
@@ -115,6 +122,13 @@ export interface PackRoomTemplate {
115
122
  roomLeader?: string;
116
123
  /** The moderator, also named by agent key. */
117
124
  moderator?: string;
125
+ /**
126
+ * What Begin sends to this room's leader, shipped with the template.
127
+ *
128
+ * Here rather than in whatever service builds the room, so a pack's opening
129
+ * move is written beside the prompts it has to agree with.
130
+ */
131
+ beginInstruction?: string;
118
132
  }
119
133
  /** A pack directory, read. */
120
134
  export interface LoadedPack {
@@ -267,9 +267,20 @@ function validateRoomTemplate(value, file) {
267
267
  ...(value.turnMode === 'directed' || value.turnMode === 'broadcast'
268
268
  ? { turnMode: value.turnMode }
269
269
  : {}),
270
+ ...(typeof value.imageModel === 'string' &&
271
+ value.imageModel.trim() && { imageModel: value.imageModel.trim() }),
272
+ ...(value.illustrationMode === 'off' ||
273
+ value.illustrationMode === 'on-request' ||
274
+ value.illustrationMode === 'auto'
275
+ ? { illustrationMode: value.illustrationMode }
276
+ : {}),
270
277
  agents,
271
278
  ...(isValidKey(value.roomLeader) && { roomLeader: value.roomLeader }),
272
279
  ...(isValidKey(value.moderator) && { moderator: value.moderator }),
280
+ ...(typeof value.beginInstruction === 'string' &&
281
+ value.beginInstruction.trim() && {
282
+ beginInstruction: value.beginInstruction.trim(),
283
+ }),
273
284
  };
274
285
  }
275
286
  function normalizeRoomAgentEntry(entry, file) {