briyah 2.0.19 → 2.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Turns the changes a model proposed into a set a host can trust, or into an
3
+ * error the model can act on — the write-side twin of query-validation.ts, with
4
+ * the same two rules.
5
+ *
6
+ * **Nothing undeclared survives.** A change names a dataset the host declared
7
+ * editable for that kind of change, a key the dataset declared, and only fields
8
+ * the host marked `editable`. Every value is checked against its field's type
9
+ * and normalized (a numeric string becomes a number, an enum value the declared
10
+ * spelling), so the host's applier never sees a field it did not open or a value
11
+ * of the wrong kind.
12
+ *
13
+ * **A rejection names the alternatives.** Which fields are editable, which
14
+ * values an enum takes, which kinds of change a set accepts — so the next
15
+ * attempt is right rather than another guess.
16
+ *
17
+ * What this cannot know is whether a keyed row exists or belongs to the caller.
18
+ * That is the host's, in `proposeChanges`, with its own context.
19
+ */
20
+ import { DataChangeSet, DataField, DataSet } from './data.types';
21
+ /** A validated change set, or the reason it was refused. One shape, as in query-validation.ts. */
22
+ export interface ChangeValidationResult {
23
+ ok: boolean;
24
+ /** The normalized set. Present when `ok`. */
25
+ changes?: DataChangeSet;
26
+ /** Why it was refused. Present when not `ok`. */
27
+ error?: string;
28
+ /** What could have been used instead, when naming them helps. */
29
+ available?: string[];
30
+ }
31
+ /**
32
+ * Checks a raw change set against the declared datasets.
33
+ * @param raw The set as the model produced it: `{title, changes, note?}`
34
+ * @param sets Every dataset the sources declare
35
+ * @returns The normalized set, or a refusal naming what was allowed instead
36
+ */
37
+ export declare function validateChanges(raw: any, sets: DataSet[]): ChangeValidationResult;
38
+ /**
39
+ * One value against its field's type, normalized. Lenient where a model's
40
+ * spelling is unambiguous (a number sent as "1200", "Yes" for a boolean, an enum
41
+ * value in the wrong case), strict where it is not (a date in any form but
42
+ * YYYY-MM-DD, which "03/04/2025" would otherwise make ambiguous).
43
+ */
44
+ export declare function checkValue(field: DataField, value: any): {
45
+ value: any;
46
+ } | {
47
+ error: string;
48
+ available?: string[];
49
+ };
@@ -0,0 +1,246 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateChanges = validateChanges;
4
+ exports.checkValue = checkValue;
5
+ /**
6
+ * Turns the changes a model proposed into a set a host can trust, or into an
7
+ * error the model can act on — the write-side twin of query-validation.ts, with
8
+ * the same two rules.
9
+ *
10
+ * **Nothing undeclared survives.** A change names a dataset the host declared
11
+ * editable for that kind of change, a key the dataset declared, and only fields
12
+ * the host marked `editable`. Every value is checked against its field's type
13
+ * and normalized (a numeric string becomes a number, an enum value the declared
14
+ * spelling), so the host's applier never sees a field it did not open or a value
15
+ * of the wrong kind.
16
+ *
17
+ * **A rejection names the alternatives.** Which fields are editable, which
18
+ * values an enum takes, which kinds of change a set accepts — so the next
19
+ * attempt is right rather than another guess.
20
+ *
21
+ * What this cannot know is whether a keyed row exists or belongs to the caller.
22
+ * That is the host's, in `proposeChanges`, with its own context.
23
+ */
24
+ const data_types_1 = require("./data.types");
25
+ const OPS = ['update', 'create', 'delete'];
26
+ function fail(error, available) {
27
+ return available ? { ok: false, error, available } : { ok: false, error };
28
+ }
29
+ /** Which change, for a message: "Change 3 (update claims)". */
30
+ function which(index, op, dataset) {
31
+ return `Change ${index + 1} (${op} ${dataset})`;
32
+ }
33
+ function editableNames(set) {
34
+ return set.fields.filter((field) => field.editable).map((field) => field.name);
35
+ }
36
+ /** The sets that accept a given kind of change, for a refusal naming them. */
37
+ function setsAccepting(sets, op) {
38
+ return sets.filter((set) => set.edits?.[op]).map((set) => set.name);
39
+ }
40
+ /**
41
+ * Checks a raw change set against the declared datasets.
42
+ * @param raw The set as the model produced it: `{title, changes, note?}`
43
+ * @param sets Every dataset the sources declare
44
+ * @returns The normalized set, or a refusal naming what was allowed instead
45
+ */
46
+ function validateChanges(raw, sets) {
47
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
48
+ return fail('The proposal must be a JSON object: {"title": "...", "changes": [...]}.');
49
+ }
50
+ const title = typeof raw.title === 'string' ? raw.title.trim() : '';
51
+ if (!title) {
52
+ return fail('The proposal needs a "title": one line saying what it does, e.g. "Add policy prefixes to 42 claim numbers".');
53
+ }
54
+ const rawChanges = Array.isArray(raw.changes) ? raw.changes : raw.changes ? [raw.changes] : [];
55
+ if (rawChanges.length === 0) {
56
+ return fail('The proposal has no "changes".');
57
+ }
58
+ if (rawChanges.length > data_types_1.MAX_DATA_CHANGES) {
59
+ return fail(`A proposal may carry at most ${data_types_1.MAX_DATA_CHANGES} changes; this one has ${rawChanges.length}. Split it into several proposals.`);
60
+ }
61
+ const changes = [];
62
+ // One row, one change: two updates to the same row would make the approver
63
+ // read both to know the outcome, and an update and a delete contradict.
64
+ const touched = new Set();
65
+ for (let index = 0; index < rawChanges.length; index++) {
66
+ const checked = validateChange(rawChanges[index], index, sets);
67
+ if ('result' in checked) {
68
+ return checked.result;
69
+ }
70
+ const change = checked.change;
71
+ if (change.op !== 'create') {
72
+ const id = `${change.dataset}|${String(change.key)}`;
73
+ if (touched.has(id)) {
74
+ return fail(`${which(index, change.op, change.dataset)} names row ${String(change.key)} again. ` +
75
+ 'Give each row one change, with every field it needs in one "set".');
76
+ }
77
+ touched.add(id);
78
+ }
79
+ changes.push(change);
80
+ }
81
+ const note = typeof raw.note === 'string' && raw.note.trim() ? raw.note.trim() : undefined;
82
+ return { ok: true, changes: { title, changes, ...(note ? { note } : {}) } };
83
+ }
84
+ function refuse(error, available) {
85
+ return { result: fail(error, available) };
86
+ }
87
+ function validateChange(raw, index, sets) {
88
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
89
+ return refuse(`Change ${index + 1} must be an object: {"op", "dataset", ...}.`);
90
+ }
91
+ const op = String(raw.op ?? '').toLowerCase();
92
+ if (!OPS.includes(op)) {
93
+ return refuse(`Change ${index + 1} has op "${raw.op}". Allowed:`, [...OPS]);
94
+ }
95
+ const set = sets.find((candidate) => candidate.name === raw.dataset);
96
+ if (!set) {
97
+ const accepting = setsAccepting(sets, op);
98
+ return refuse(accepting.length
99
+ ? `Change ${index + 1} names dataset "${raw.dataset}", which does not accept ${op}s. Datasets that do:`
100
+ : `Change ${index + 1} names dataset "${raw.dataset}", and no dataset accepts ${op}s.`, accepting.length ? accepting : undefined);
101
+ }
102
+ if (!set.edits?.[op]) {
103
+ const kinds = OPS.filter((kind) => set.edits?.[kind]);
104
+ return refuse(kinds.length
105
+ ? `${which(index, op, set.name)}: "${set.name}" does not accept ${op}s. It accepts:`
106
+ : `${which(index, op, set.name)}: "${set.name}" is read-only.`, kinds.length ? [...kinds] : undefined);
107
+ }
108
+ const reason = typeof raw.reason === 'string' && raw.reason.trim() ? raw.reason.trim() : undefined;
109
+ if (op === 'create') {
110
+ const checked = checkValues(raw.values, set, index, op, true);
111
+ if ('error' in checked) {
112
+ return checked.error;
113
+ }
114
+ return { change: { op: 'create', dataset: set.name, values: checked.values, ...(reason ? { reason } : {}) } };
115
+ }
116
+ const key = raw.key;
117
+ if (key === undefined || key === null || key === '' || (typeof key !== 'string' && typeof key !== 'number')) {
118
+ return refuse(`${which(index, op, set.name)} needs "key": the row's "${set.key}", as query_data returns it. ` +
119
+ 'Query the rows first; never guess a key.');
120
+ }
121
+ if (op === 'delete') {
122
+ return { change: { op: 'delete', dataset: set.name, key, ...(reason ? { reason } : {}) } };
123
+ }
124
+ const checked = checkValues(raw.set, set, index, op, false);
125
+ if ('error' in checked) {
126
+ return checked.error;
127
+ }
128
+ if (Object.keys(checked.values).length === 0) {
129
+ return refuse(`${which(index, op, set.name)} sets no fields. Editable fields:`, editableNames(set));
130
+ }
131
+ return { change: { op: 'update', dataset: set.name, key, set: checked.values, ...(reason ? { reason } : {}) } };
132
+ }
133
+ /** Checks the field → value map of an update's `set` or a create's `values`. */
134
+ function checkValues(raw, set, index, op, creating) {
135
+ const label = which(index, op, set.name);
136
+ const property = creating ? 'values' : 'set';
137
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
138
+ return { error: refuse(`${label} needs "${property}": an object of field → value.`) };
139
+ }
140
+ const values = {};
141
+ for (const [name, value] of Object.entries(raw)) {
142
+ const field = set.fields.find((candidate) => candidate.name === name);
143
+ if (!field) {
144
+ return { error: refuse(`${label}: "${set.name}" has no field "${name}". Editable fields:`, editableNames(set)) };
145
+ }
146
+ if (!field.editable) {
147
+ return { error: refuse(`${label}: "${name}" cannot be changed. Editable fields:`, editableNames(set)) };
148
+ }
149
+ const checked = checkValue(field, value);
150
+ if ('error' in checked) {
151
+ return { error: refuse(`${label}: ${checked.error}`, checked.available) };
152
+ }
153
+ values[field.name] = checked.value;
154
+ }
155
+ if (creating) {
156
+ const missing = set.fields
157
+ .filter((field) => field.requiredOnCreate && (values[field.name] === undefined || values[field.name] === null || values[field.name] === ''))
158
+ .map((field) => field.name);
159
+ if (missing.length) {
160
+ return { error: refuse(`${label} is missing fields a new row needs:`, missing) };
161
+ }
162
+ }
163
+ return { values };
164
+ }
165
+ const TRUE_WORDS = ['true', 'yes', 'y', '1'];
166
+ const FALSE_WORDS = ['false', 'no', 'n', '0'];
167
+ /**
168
+ * One value against its field's type, normalized. Lenient where a model's
169
+ * spelling is unambiguous (a number sent as "1200", "Yes" for a boolean, an enum
170
+ * value in the wrong case), strict where it is not (a date in any form but
171
+ * YYYY-MM-DD, which "03/04/2025" would otherwise make ambiguous).
172
+ */
173
+ function checkValue(field, value) {
174
+ if (value === null || value === undefined || value === '') {
175
+ if (field.nullable) {
176
+ return { value: null };
177
+ }
178
+ if (value === '' && field.type === 'string') {
179
+ return { error: `"${field.name}" cannot be cleared.` };
180
+ }
181
+ return { error: `"${field.name}" cannot be cleared; give it a value.` };
182
+ }
183
+ switch (field.type) {
184
+ case 'number': {
185
+ const number = typeof value === 'number' ? value : Number(String(value).replace(/[$,\s]/g, ''));
186
+ if (!Number.isFinite(number)) {
187
+ return { error: `"${field.name}" is a number, not "${value}".` };
188
+ }
189
+ return { value: number };
190
+ }
191
+ case 'boolean': {
192
+ if (typeof value === 'boolean') {
193
+ return { value };
194
+ }
195
+ const word = String(value).trim().toLowerCase();
196
+ if (TRUE_WORDS.includes(word))
197
+ return { value: true };
198
+ if (FALSE_WORDS.includes(word))
199
+ return { value: false };
200
+ return { error: `"${field.name}" is true or false, not "${value}".` };
201
+ }
202
+ case 'date': {
203
+ const text = String(value).trim();
204
+ const match = /^(\d{4})-(\d{2})-(\d{2})(?:[T ].*)?$/.exec(text);
205
+ if (!match) {
206
+ return { error: `"${field.name}" is a date written YYYY-MM-DD, not "${value}".` };
207
+ }
208
+ const [, year, month, day] = match;
209
+ const date = new Date(Date.UTC(Number(year), Number(month) - 1, Number(day)));
210
+ if (date.getUTCMonth() !== Number(month) - 1 || date.getUTCDate() !== Number(day)) {
211
+ return { error: `"${value}" is not a real date for "${field.name}".` };
212
+ }
213
+ return { value: `${year}-${month}-${day}` };
214
+ }
215
+ case 'enum': {
216
+ const declared = field.enumValues || [];
217
+ if (!declared.length) {
218
+ return { value: String(value) };
219
+ }
220
+ const text = String(value).trim();
221
+ const exact = declared.find((candidate) => candidate === text)
222
+ ?? declared.find((candidate) => candidate.toLowerCase() === text.toLowerCase());
223
+ if (exact === undefined) {
224
+ return { error: `"${value}" is not a value of "${field.name}". Allowed:`, available: declared };
225
+ }
226
+ return { value: exact };
227
+ }
228
+ case 'list': {
229
+ const members = (Array.isArray(value) ? value : [value]).map((member) => String(member).trim()).filter(Boolean);
230
+ const declared = field.enumValues || [];
231
+ if (declared.length) {
232
+ const bad = members.find((member) => !declared.includes(member));
233
+ if (bad !== undefined) {
234
+ return { error: `"${bad}" is not a value of "${field.name}". Allowed:`, available: declared };
235
+ }
236
+ }
237
+ return { value: members };
238
+ }
239
+ default: {
240
+ if (typeof value === 'object') {
241
+ return { error: `"${field.name}" is text, not an object.` };
242
+ }
243
+ return { value: String(value) };
244
+ }
245
+ }
246
+ }
@@ -1,2 +1,15 @@
1
+ /**
2
+ * Renders the registered datasets as a document to attach to an analyst agent.
3
+ *
4
+ * An agent that has to *ask* what it can query spends a tool call and a turn
5
+ * discovering something that never changes during a conversation. Attaching the
6
+ * schema instead puts it in the cached prompt prefix, where it costs almost
7
+ * nothing per turn and lets the agent write a correct query in the turn it is
8
+ * already taking. `describe_data` still exists, because the attached copy is a
9
+ * snapshot and the tool is the live truth.
10
+ */
11
+ import { DataField } from './data.types';
1
12
  /** @returns The schema guide, or an empty string when nothing is registered */
2
13
  export declare function buildDataGuideMarkdown(): string;
14
+ /** One field line: what it is, and what may be done with it. */
15
+ export declare function describeField(field: DataField): string;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.buildDataGuideMarkdown = buildDataGuideMarkdown;
4
+ exports.describeField = describeField;
4
5
  const data_registry_1 = require("./data-registry");
5
6
  /** @returns The schema guide, or an empty string when nothing is registered */
6
7
  function buildDataGuideMarkdown() {
@@ -52,6 +53,9 @@ function buildDataGuideMarkdown() {
52
53
  'excludes and which definition a metric uses.',
53
54
  '',
54
55
  ];
56
+ if (sources.some((source) => typeof source.proposeChanges === 'function' && (source.datasets || []).some((set) => hasEdits(set)))) {
57
+ lines.push(...CHANGES_SECTION);
58
+ }
55
59
  for (const source of sources) {
56
60
  if (sources.length > 1) {
57
61
  lines.push(`## ${source.name}`);
@@ -66,16 +70,59 @@ function buildDataGuideMarkdown() {
66
70
  }
67
71
  return lines.join('\n');
68
72
  }
73
+ /** How changes are proposed; only in a guide where some set accepts them. */
74
+ const CHANGES_SECTION = [
75
+ '## Changing Data',
76
+ '',
77
+ 'Some datasets can be changed: their heading says which kinds of change',
78
+ '(update, create, delete) they accept and which field is their **key**, and',
79
+ 'their changeable fields are marked **editable**. You never change data',
80
+ 'directly. You propose changes with `propose_data_changes`; a person sees',
81
+ 'every one and applies or discards them after your turn, and you are told',
82
+ 'which. Until then, nothing has changed — never say it has.',
83
+ '',
84
+ '1. Query the rows first, selecting the key, so every change names a real row.',
85
+ ' Never guess a key or reuse one from another dataset.',
86
+ '2. Put everything one request needs into one proposal, each row once.',
87
+ '3. Give each change a short `reason` the person can check against, and use',
88
+ ' `note` for what you could not match or had to assume.',
89
+ '',
90
+ '```json',
91
+ '{"title": "Add the policy prefix to 2 claim numbers", "changes": [',
92
+ ' {"op": "update", "dataset": "claims", "key": "6f1c…",',
93
+ ' "set": {"claimNumber": "CA-24-1187"}, "reason": "Loss run lists CA-24-1187"},',
94
+ ' {"op": "create", "dataset": "claims", "values": {"claimNumber": "CA-24-1201"}},',
95
+ ' {"op": "delete", "dataset": "claims", "key": "9a2e…"}],',
96
+ ' "note": "24-1190 is in the report but not in the records."}',
97
+ '```',
98
+ '',
99
+ 'Dates are YYYY-MM-DD. A field can be cleared (null) only where it says',
100
+ '*clearable*; a new row must give every field marked *required to add*.',
101
+ '',
102
+ ];
103
+ function hasEdits(set) {
104
+ return !!(set.edits?.update || set.edits?.create || set.edits?.delete);
105
+ }
69
106
  function describeDataset(set, heading) {
70
107
  const lines = [`${heading} ${set.label || set.name}`, ''];
71
108
  lines.push(`- dataset: \`${set.name}\``);
72
109
  lines.push(`- ${set.description}`);
110
+ if (hasEdits(set)) {
111
+ const kinds = ['update', 'create', 'delete'].filter((kind) => set.edits?.[kind]);
112
+ lines.push(`- Changes: ${kinds.join(', ')}${set.key ? `; key \`${set.key}\`` : ''}`);
113
+ }
73
114
  if (set.notes?.length) {
74
115
  lines.push('- Important:');
75
116
  for (const note of set.notes) {
76
117
  lines.push(` - ${note}`);
77
118
  }
78
119
  }
120
+ if (set.fieldsInGuide === false) {
121
+ lines.push(`- Fields: ${set.fields.length}, not listed here. Call \`describe_data\` with ` +
122
+ `\`"dataset": "${set.name}"\` (and a \`search\` word to narrow them) to list them.`);
123
+ lines.push('');
124
+ return lines;
125
+ }
79
126
  lines.push('- Fields:');
80
127
  for (const field of set.fields) {
81
128
  lines.push(` - ${describeField(field)}`);
@@ -100,6 +147,15 @@ function describeField(field) {
100
147
  if (field.aggregates?.length) {
101
148
  caps.push(field.aggregates.join('/'));
102
149
  }
150
+ if (field.editable) {
151
+ caps.push('editable');
152
+ if (field.nullable) {
153
+ caps.push('clearable');
154
+ }
155
+ if (field.requiredOnCreate) {
156
+ caps.push('required to add');
157
+ }
158
+ }
103
159
  const label = field.label && field.label !== field.name ? ` — ${field.label}` : '';
104
160
  const description = field.description ? `. ${field.description}` : '';
105
161
  const capText = caps.length ? ` [${caps.join(', ')}]` : '';
@@ -29,6 +29,13 @@ function registerDataSource(source) {
29
29
  if (owner && owner.name !== source.name) {
30
30
  throw new Error(`Dataset "${set.name}" is already offered by data source "${owner.name}"`);
31
31
  }
32
+ // An editable set whose rows cannot be named would accept proposals that
33
+ // nothing could ever apply; caught here, at the host's boot.
34
+ const edits = set.edits || {};
35
+ if ((edits.update || edits.delete) && !set.fields.some((field) => field.name === set.key)) {
36
+ throw new Error(`Dataset "${set.name}" accepts ${edits.update ? 'updates' : 'deletes'} but its key ` +
37
+ `"${set.key ?? ''}" is not one of its fields`);
38
+ }
32
39
  }
33
40
  if (sources.has(source.name)) {
34
41
  logger_1.logger.warn(`Data source "${source.name}" is already registered; overwriting`);
@@ -80,6 +80,16 @@ export interface DataField {
80
80
  * nothing can be summed over, like a name.
81
81
  */
82
82
  aggregates?: DataAggregateFn[];
83
+ /**
84
+ * May be set by a proposed change (see {@link DataChange}). Default false: a
85
+ * field is read-only unless the host says otherwise, so a derived field — an
86
+ * age, a total — can never be written by accident.
87
+ */
88
+ editable?: boolean;
89
+ /** Must be given when a change creates a row. Implies nothing about updates. */
90
+ requiredOnCreate?: boolean;
91
+ /** A change may clear it (set it to null). Default false. */
92
+ nullable?: boolean;
83
93
  }
84
94
  /** One queryable collection of records. */
85
95
  export interface DataSet {
@@ -102,6 +112,28 @@ export interface DataSet {
102
112
  defaultLimit?: number;
103
113
  /** The most rows this set will ever return, whatever a query asks for. */
104
114
  maxLimit?: number;
115
+ /**
116
+ * The field that identifies one row, which a change names to update or delete
117
+ * it. Required for `update` and `delete` in {@link edits}; it must be one of
118
+ * {@link fields}, so an agent reads it with `query_data` before proposing.
119
+ */
120
+ key?: string;
121
+ /** Which kinds of change may be proposed for this set. Omit for none: read-only. */
122
+ edits?: DataEditKinds;
123
+ /**
124
+ * False keeps this set's fields out of the attached data guide, which then
125
+ * names the set and says to list its fields with `describe_data`. For a set
126
+ * with hundreds of fields — a long questionnaire — that would otherwise
127
+ * swell every turn's prompt for the sake of the occasional question about it.
128
+ * Default true.
129
+ */
130
+ fieldsInGuide?: boolean;
131
+ }
132
+ /** The kinds of change a dataset accepts. */
133
+ export interface DataEditKinds {
134
+ update?: boolean;
135
+ create?: boolean;
136
+ delete?: boolean;
105
137
  }
106
138
  /** One comparison in a query. */
107
139
  export interface DataFilter {
@@ -196,7 +228,73 @@ export interface DataSource {
196
228
  * @returns The rows, and the total when it is cheap to know
197
229
  */
198
230
  execute(query: DataQuery, context: unknown): Promise<DataResult>;
231
+ /**
232
+ * Receives a validated set of proposed changes. Optional: a source without it
233
+ * is read-only, and `propose_data_changes` says so.
234
+ *
235
+ * Briyah never writes. A tool call cannot wait for a person, so the host
236
+ * stores the proposal, shows it to someone who can approve it, and applies it
237
+ * (or not) after the agent's turn has ended — telling the agent the outcome in
238
+ * whatever way it tells agents things. Every dataset, field, key and value
239
+ * type has been checked against the declarations by the time this is called;
240
+ * whether the keyed rows exist, and belong to the caller, is the host's to
241
+ * check, with `context` as its scope exactly as in {@link execute}.
242
+ * @param changes The validated changes
243
+ * @param context The host's opaque per-invocation context
244
+ * @returns The stored proposal, or a refusal naming what was wrong
245
+ */
246
+ proposeChanges?(changes: DataChangeSet, context: unknown): Promise<DataProposalResult>;
247
+ }
248
+ /** Updates the named fields of one row. */
249
+ export interface DataUpdateChange {
250
+ op: 'update';
251
+ dataset: string;
252
+ /** The row's value of the dataset's key field. */
253
+ key: string | number;
254
+ /** Field name → new value. Only editable fields; null only where nullable. */
255
+ set: Record<string, any>;
256
+ /** Why — shown to the person approving it. */
257
+ reason?: string;
258
+ }
259
+ /** Adds one row. */
260
+ export interface DataCreateChange {
261
+ op: 'create';
262
+ dataset: string;
263
+ /** Field name → value. Every `requiredOnCreate` field must be present. */
264
+ values: Record<string, any>;
265
+ reason?: string;
266
+ }
267
+ /** Removes one row. */
268
+ export interface DataDeleteChange {
269
+ op: 'delete';
270
+ dataset: string;
271
+ key: string | number;
272
+ reason?: string;
273
+ }
274
+ /** One proposed change. */
275
+ export type DataChange = DataUpdateChange | DataCreateChange | DataDeleteChange;
276
+ /** What an agent proposes at once, and a person approves or rejects at once. */
277
+ export interface DataChangeSet {
278
+ /** One line saying what the set does, e.g. "Add policy prefixes to 42 claim numbers". */
279
+ title: string;
280
+ changes: DataChange[];
281
+ /** Anything the approver should know: what could not be matched, what was assumed. */
282
+ note?: string;
283
+ }
284
+ /** A host's answer to {@link DataSource.proposeChanges}. */
285
+ export interface DataProposalResult {
286
+ ok: boolean;
287
+ /** The host's id for the stored proposal. Present when `ok`. */
288
+ proposalId?: string;
289
+ /** One line for the room log. */
290
+ summary?: string;
291
+ /** Why it was refused. Present when not `ok`. */
292
+ error?: string;
293
+ /** What could have been used instead, when naming them helps. */
294
+ available?: string[];
199
295
  }
296
+ /** The most changes one proposal may carry. */
297
+ export declare const MAX_DATA_CHANGES = 500;
200
298
  /** Rows returned when neither the query nor the dataset names a limit. */
201
299
  export declare const DEFAULT_ROW_LIMIT = 50;
202
300
  /** The ceiling no dataset's `maxLimit` may exceed. */
@@ -17,7 +17,9 @@
17
17
  * a database with no read-only role behind it.
18
18
  */
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.MAX_ROW_LIMIT = exports.DEFAULT_ROW_LIMIT = void 0;
20
+ exports.MAX_ROW_LIMIT = exports.DEFAULT_ROW_LIMIT = exports.MAX_DATA_CHANGES = void 0;
21
+ /** The most changes one proposal may carry. */
22
+ exports.MAX_DATA_CHANGES = 500;
21
23
  /** Rows returned when neither the query nor the dataset names a limit. */
22
24
  exports.DEFAULT_ROW_LIMIT = 50;
23
25
  /** The ceiling no dataset's `maxLimit` may exceed. */
@@ -0,0 +1,19 @@
1
+ import { DataChangeSet } from './data.types';
2
+ export interface ProposeChangesResult {
3
+ ok: boolean;
4
+ /** The validated set the host received. Present when `ok`. */
5
+ changes?: DataChangeSet;
6
+ /** The host's id for the stored proposal. Present when `ok`. */
7
+ proposalId?: string;
8
+ /** One line for the room log. */
9
+ summary?: string;
10
+ error?: string;
11
+ available?: string[];
12
+ }
13
+ /**
14
+ * Validates a raw change set and hands it to the source that owns its datasets.
15
+ * @param raw The set as the model produced it
16
+ * @param context The host's per-invocation context
17
+ * @returns The host's proposal id, or a refusal
18
+ */
19
+ export declare function proposeDataChanges(raw: unknown, context: unknown): Promise<ProposeChangesResult>;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.proposeDataChanges = proposeDataChanges;
4
+ /**
5
+ * Proposing changes an agent wrote: validate them against the registered
6
+ * datasets, find the one source that owns them, and hand them to its
7
+ * `proposeChanges` with the host's context — what `propose_data_changes` does,
8
+ * for anything else that proposes on an agent's behalf. Never throws: a refusal,
9
+ * whether Briyah's or the host's, comes back as one with what was allowed.
10
+ */
11
+ const data_registry_1 = require("./data-registry");
12
+ const change_validation_1 = require("./change-validation");
13
+ /** The source offering a dataset, among every registered one. */
14
+ function ownerOf(dataset, sources) {
15
+ return sources.find((source) => (source.datasets || []).some((set) => set.name === dataset));
16
+ }
17
+ /**
18
+ * Validates a raw change set and hands it to the source that owns its datasets.
19
+ * @param raw The set as the model produced it
20
+ * @param context The host's per-invocation context
21
+ * @returns The host's proposal id, or a refusal
22
+ */
23
+ async function proposeDataChanges(raw, context) {
24
+ const checked = (0, change_validation_1.validateChanges)(raw, (0, data_registry_1.listDatasets)());
25
+ if (!checked.ok || !checked.changes) {
26
+ return {
27
+ ok: false,
28
+ error: checked.error ?? 'The proposal was refused.',
29
+ ...(checked.available ? { available: checked.available } : {}),
30
+ };
31
+ }
32
+ const set = checked.changes;
33
+ const sources = (0, data_registry_1.listDataSources)();
34
+ const owners = new Set(set.changes.map((change) => ownerOf(change.dataset, sources)));
35
+ if (owners.size !== 1) {
36
+ // One approval, one host transaction: a set spanning two sources could
37
+ // half-apply with nobody able to say which half.
38
+ return {
39
+ ok: false,
40
+ error: 'These changes belong to different data sources. Propose each source\'s changes separately.',
41
+ };
42
+ }
43
+ const source = [...owners][0];
44
+ if (!source || typeof source.proposeChanges !== 'function') {
45
+ return {
46
+ ok: false,
47
+ error: `"${source?.name ?? set.changes[0].dataset}" data can be read but not changed from here.`,
48
+ };
49
+ }
50
+ try {
51
+ const result = await source.proposeChanges(set, context);
52
+ if (!result?.ok || !result.proposalId) {
53
+ return {
54
+ ok: false,
55
+ error: result?.error || 'The application refused the proposal.',
56
+ ...(result?.available ? { available: result.available } : {}),
57
+ };
58
+ }
59
+ return {
60
+ ok: true,
61
+ changes: set,
62
+ proposalId: result.proposalId,
63
+ summary: result.summary || `Proposed ${set.changes.length} change(s): ${set.title}`,
64
+ };
65
+ }
66
+ catch (error) {
67
+ return { ok: false, error: `The application could not store the proposal: ${error?.message || error}` };
68
+ }
69
+ }
@@ -34,8 +34,12 @@ export type { NativeToolDefinition, ToolHelpers, ToolContext, ToolCaller, ToolAr
34
34
  export { dnd5eTools } from '../tools/packs/dnd5e';
35
35
  export { installToolPacks, registerToolPacks, availableToolPacks } from '../tools/packs';
36
36
  export { NativeToolRegistry } from '../tools/native-tool-registry.service';
37
- export type { DataSource, DataSet, DataField, DataFieldType, DataAggregateFn, DataFilter, DataFilterOp, DataHaving, DataMetric, DataOrder, DataQuery, DataRow, DataResult, } from '../data/data.types';
38
- export { DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT } from '../data/data.types';
37
+ export type { DataSource, DataSet, DataField, DataFieldType, DataAggregateFn, DataFilter, DataFilterOp, DataHaving, DataMetric, DataOrder, DataQuery, DataRow, DataResult, DataEditKinds, DataChange, DataUpdateChange, DataCreateChange, DataDeleteChange, DataChangeSet, DataProposalResult, } from '../data/data.types';
38
+ export { DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT, MAX_DATA_CHANGES } from '../data/data.types';
39
+ export { validateChanges, checkValue } from '../data/change-validation';
40
+ export type { ChangeValidationResult } from '../data/change-validation';
41
+ export { proposeDataChanges } from '../data/propose-changes';
42
+ export type { ProposeChangesResult } from '../data/propose-changes';
39
43
  export { registerDataSource, unregisterDataSource, listDataSources, listDatasets, } from '../data/data-registry';
40
44
  export { buildDataGuideMarkdown } from '../data/data-guide.builder';
41
45
  export { queryRows } from '../data/row-executor';
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
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;
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.proposeDataChanges = exports.checkValue = exports.validateChanges = exports.MAX_DATA_CHANGES = 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; } });
@@ -107,6 +107,16 @@ Object.defineProperty(exports, "NativeToolRegistry", { enumerable: true, get: fu
107
107
  var data_types_1 = require("../data/data.types");
108
108
  Object.defineProperty(exports, "DEFAULT_ROW_LIMIT", { enumerable: true, get: function () { return data_types_1.DEFAULT_ROW_LIMIT; } });
109
109
  Object.defineProperty(exports, "MAX_ROW_LIMIT", { enumerable: true, get: function () { return data_types_1.MAX_ROW_LIMIT; } });
110
+ Object.defineProperty(exports, "MAX_DATA_CHANGES", { enumerable: true, get: function () { return data_types_1.MAX_DATA_CHANGES; } });
111
+ // Changing host data: declare a set's `key`, its `edits` and its `editable`
112
+ // fields, and give the source a `proposeChanges`, and the `propose_data_changes`
113
+ // core tool hands the host validated change sets to show a person. Briyah never
114
+ // writes; the host applies what the person approves.
115
+ var change_validation_1 = require("../data/change-validation");
116
+ Object.defineProperty(exports, "validateChanges", { enumerable: true, get: function () { return change_validation_1.validateChanges; } });
117
+ Object.defineProperty(exports, "checkValue", { enumerable: true, get: function () { return change_validation_1.checkValue; } });
118
+ var propose_changes_1 = require("../data/propose-changes");
119
+ Object.defineProperty(exports, "proposeDataChanges", { enumerable: true, get: function () { return propose_changes_1.proposeDataChanges; } });
110
120
  var data_registry_1 = require("../data/data-registry");
111
121
  Object.defineProperty(exports, "registerDataSource", { enumerable: true, get: function () { return data_registry_1.registerDataSource; } });
112
122
  Object.defineProperty(exports, "unregisterDataSource", { enumerable: true, get: function () { return data_registry_1.unregisterDataSource; } });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Changing a host's data, without the agent ever writing to it.
3
+ *
4
+ * `propose_data_changes` takes a set of changes — update these fields of these
5
+ * rows, add these rows, remove these — validates every name and value against
6
+ * what the host declared editable, and hands the set to the host's
7
+ * `proposeChanges`. The host stores it and shows it to a person; nothing is
8
+ * written until that person approves, which happens after this call has
9
+ * returned. The tool says so in its result, so an agent never reports a change
10
+ * as made.
11
+ *
12
+ * Arguments are read the way `query_data` reads its query: wrapped in
13
+ * `proposal`, or as the arguments themselves, since that is how a model
14
+ * following the example sends them.
15
+ */
16
+ import { NativeToolDefinition } from '../native-tool.types';
17
+ /** The proposal, in either form a model sends it. */
18
+ export declare function proposalFromArgs(args: Record<string, any>): Record<string, any>;
19
+ export declare const proposeDataChangesTool: NativeToolDefinition;
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.proposeDataChangesTool = void 0;
4
+ exports.proposalFromArgs = proposalFromArgs;
5
+ const coerce_1 = require("../shared/coerce");
6
+ const data_registry_1 = require("../../data/data-registry");
7
+ const propose_changes_1 = require("../../data/propose-changes");
8
+ const data_types_1 = require("../../data/data.types");
9
+ const PROPOSAL_EXAMPLE = '{"title": "Add the policy prefix to 2 claim numbers", "changes": [' +
10
+ '{"op": "update", "dataset": "claims", "key": "6f1c…", "set": {"claimNumber": "CA-24-1187"}, "reason": "Loss run lists it as CA-24-1187"}, ' +
11
+ '{"op": "create", "dataset": "claims", "values": {"claimNumber": "CA-24-1201", "lossDate": "2024-03-02"}}, ' +
12
+ '{"op": "delete", "dataset": "claims", "key": "9a2e…"}], ' +
13
+ '"note": "Claim 24-1190 is in the report but not in the records; left alone."}';
14
+ /** The proposal, in either form a model sends it. */
15
+ function proposalFromArgs(args) {
16
+ const wrapped = args?.proposal;
17
+ if (wrapped !== undefined && wrapped !== null && wrapped !== '') {
18
+ return (0, coerce_1.jsonObject)(wrapped, 'proposal', PROPOSAL_EXAMPLE);
19
+ }
20
+ if (args?.changes !== undefined && args.changes !== null && args.changes !== '') {
21
+ const fields = {};
22
+ for (const [key, value] of Object.entries(args)) {
23
+ if (key !== 'proposal')
24
+ fields[key] = (0, coerce_1.parsedIfJson)(value);
25
+ }
26
+ return fields;
27
+ }
28
+ throw new coerce_1.ArgumentError('proposal', wrapped, 'a JSON object with a title and changes', PROPOSAL_EXAMPLE);
29
+ }
30
+ exports.proposeDataChangesTool = {
31
+ name: 'propose_data_changes',
32
+ description: 'Proposes changes to the application\'s data for a person to approve. Nothing is changed ' +
33
+ 'by this call: the person sees every change and applies or discards it afterwards, and you ' +
34
+ 'are told which. Each change updates fields of one row ("update", by its key), adds a row ' +
35
+ '("create") or removes one ("delete", by its key). Only datasets and fields your data guide ' +
36
+ 'marks editable can be changed, and a key must come from a query_data result — never guess ' +
37
+ 'one. Put everything one request needs in one proposal, at most ' + data_types_1.MAX_DATA_CHANGES +
38
+ ' changes. Example: ' + PROPOSAL_EXAMPLE +
39
+ ' Send it as `proposal`, or its fields (title, changes, note) as the arguments themselves.',
40
+ parameters: [
41
+ {
42
+ name: 'proposal',
43
+ type: 'string',
44
+ description: 'The proposal as a JSON object: {"title", "changes": [...], "note"?}. Example: ' + PROPOSAL_EXAMPLE +
45
+ ' May be left out when its fields are sent as the arguments instead.',
46
+ required: false,
47
+ },
48
+ ],
49
+ handler: async (args, _helpers, context) => {
50
+ if (!(0, data_registry_1.hasDataSources)()) {
51
+ return {
52
+ ok: false,
53
+ summary: 'No data can be changed',
54
+ error: 'This application has not made any data available.',
55
+ };
56
+ }
57
+ const result = await (0, propose_changes_1.proposeDataChanges)(proposalFromArgs(args), context);
58
+ if (!result.ok) {
59
+ return {
60
+ ok: false,
61
+ summary: 'Proposal refused',
62
+ error: result.error,
63
+ ...(result.available ? { available: result.available } : {}),
64
+ };
65
+ }
66
+ return {
67
+ ok: true,
68
+ summary: result.summary,
69
+ // The room log's line for this call. It carries the id in a fixed
70
+ // form, `[proposal <id>]`, so a host replaying its room log can put
71
+ // the proposal back where it was made.
72
+ detail: `${result.summary} [proposal ${result.proposalId}]`,
73
+ proposalId: result.proposalId,
74
+ changeCount: result.changes.changes.length,
75
+ status: 'waiting for approval',
76
+ note: 'Nothing has been changed yet. The person now sees these changes and applies or discards them; ' +
77
+ 'you will be told which. Do not say the data has changed until then.',
78
+ };
79
+ },
80
+ // A proposal of hundreds of changes is a large argument but a small result.
81
+ timeoutMs: 60_000,
82
+ };
@@ -5,6 +5,7 @@ exports.queryFromArgs = queryFromArgs;
5
5
  const coerce_1 = require("../shared/coerce");
6
6
  const data_registry_1 = require("../../data/data-registry");
7
7
  const query_validation_1 = require("../../data/query-validation");
8
+ const data_guide_builder_1 = require("../../data/data-guide.builder");
8
9
  /** Serialized characters a query result may occupy. Under the tool's own budget. */
9
10
  const RESULT_BUDGET = 20_000;
10
11
  const QUERY_EXAMPLE = '{"dataset": "claims", "filters": [{"field": "year", "op": "gte", "value": 2022}], ' +
@@ -42,7 +43,9 @@ exports.describeDataTool = {
42
43
  name: 'describe_data',
43
44
  description: 'Lists the datasets you can query, or the fields of one dataset. Your attached ' +
44
45
  'data guide already describes these — use this when you need to confirm a field ' +
45
- 'exists, or when the guide and a query result disagree.',
46
+ 'exists, when the guide and a query result disagree, or to list the fields of a set ' +
47
+ 'the guide does not list them for. Pass search to narrow a long field list to the ' +
48
+ 'fields whose name, label or description contains that text.',
46
49
  parameters: [
47
50
  {
48
51
  name: 'dataset',
@@ -50,6 +53,12 @@ exports.describeDataTool = {
50
53
  description: 'The dataset to describe. Omit to list every dataset.',
51
54
  required: false,
52
55
  },
56
+ {
57
+ name: 'search',
58
+ type: 'string',
59
+ description: 'With a dataset: only the fields whose name, label or description contains this text (any case).',
60
+ required: false,
61
+ },
53
62
  ],
54
63
  handler: async (args) => {
55
64
  if (!(0, data_registry_1.hasDataSources)()) {
@@ -83,16 +92,26 @@ exports.describeDataTool = {
83
92
  available: datasetNames(),
84
93
  };
85
94
  }
95
+ const search = args.search === undefined || args.search === null ? '' : String(args.search).trim().toLowerCase();
96
+ const fields = search
97
+ ? set.fields.filter((field) => [field.name, field.label, field.description].some((text) => (text || '').toLowerCase().includes(search)))
98
+ : set.fields;
86
99
  return {
87
100
  ok: true,
88
- summary: `Described the "${set.name}" dataset`,
101
+ summary: `Described the "${set.name}" dataset${search ? ` (${fields.length} field(s) matching "${search}")` : ''}`,
89
102
  dataset: set.name,
90
103
  label: set.label || set.name,
91
104
  description: set.description,
92
105
  notes: set.notes || [],
93
- fields: set.fields,
106
+ ...(set.key ? { key: set.key } : {}),
107
+ ...(set.edits ? { edits: set.edits } : {}),
108
+ // One line per field, as the data guide writes them: a set with
109
+ // hundreds of fields still fits, and reads the same as the guide.
110
+ fields: fields.map(data_guide_builder_1.describeField),
94
111
  };
95
112
  },
113
+ // A questionnaire's worth of field lines.
114
+ maxResultChars: 60_000,
96
115
  timeoutMs: 5_000,
97
116
  };
98
117
  exports.queryDataTool = {
@@ -19,6 +19,7 @@ exports.coreTools = coreTools;
19
19
  const chart_tool_1 = require("./chart.tool");
20
20
  const create_image_tool_1 = require("./create-image.tool");
21
21
  const data_tools_1 = require("./data.tools");
22
+ const data_change_tools_1 = require("./data-change.tools");
22
23
  const document_tools_1 = require("./document.tools");
23
24
  const html_template_tools_1 = require("./html-template.tools");
24
25
  const illustrate_tool_1 = require("./illustrate.tool");
@@ -40,6 +41,7 @@ function coreTools() {
40
41
  chart_tool_1.makeChartTool,
41
42
  data_tools_1.describeDataTool,
42
43
  data_tools_1.queryDataTool,
44
+ data_change_tools_1.proposeDataChangesTool,
43
45
  ...document_tools_1.documentTools,
44
46
  ...html_template_tools_1.htmlTemplateTools,
45
47
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "briyah",
3
- "version": "2.0.19",
3
+ "version": "2.0.20",
4
4
  "description": "SDK for AI agents, multi-agent rooms, interactive stories, and role-playing games with per-user data isolation and cost tracking",
5
5
  "private": false,
6
6
  "license": "Apache-2.0",