briyah 2.0.18 → 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.
Files changed (44) hide show
  1. package/dist-sdk/server/src/ai/agent-config.d.ts +2 -0
  2. package/dist-sdk/server/src/ai/agent-store.service.js +4 -0
  3. package/dist-sdk/server/src/ai/agent.d.ts +7 -0
  4. package/dist-sdk/server/src/ai/agent.js +7 -0
  5. package/dist-sdk/server/src/app.service.d.ts +2 -0
  6. package/dist-sdk/server/src/app.service.js +2 -0
  7. package/dist-sdk/server/src/data/change-validation.d.ts +49 -0
  8. package/dist-sdk/server/src/data/change-validation.js +246 -0
  9. package/dist-sdk/server/src/data/data-guide.builder.d.ts +13 -0
  10. package/dist-sdk/server/src/data/data-guide.builder.js +56 -0
  11. package/dist-sdk/server/src/data/data-registry.js +7 -0
  12. package/dist-sdk/server/src/data/data.types.d.ts +98 -0
  13. package/dist-sdk/server/src/data/data.types.js +3 -1
  14. package/dist-sdk/server/src/data/propose-changes.d.ts +19 -0
  15. package/dist-sdk/server/src/data/propose-changes.js +69 -0
  16. package/dist-sdk/server/src/data/query-validation.d.ts +9 -1
  17. package/dist-sdk/server/src/data/query-validation.js +9 -5
  18. package/dist-sdk/server/src/data/run-query.d.ts +14 -0
  19. package/dist-sdk/server/src/data/run-query.js +39 -0
  20. package/dist-sdk/server/src/documents/document-conversion.d.ts +27 -9
  21. package/dist-sdk/server/src/documents/document-conversion.js +131 -10
  22. package/dist-sdk/server/src/documents/html-data.d.ts +49 -0
  23. package/dist-sdk/server/src/documents/html-data.js +120 -0
  24. package/dist-sdk/server/src/documents/html-template.d.ts +108 -0
  25. package/dist-sdk/server/src/documents/html-template.js +332 -0
  26. package/dist-sdk/server/src/documents/library/document.types.d.ts +64 -0
  27. package/dist-sdk/server/src/documents/library/document.types.js +6 -0
  28. package/dist-sdk/server/src/documents/library/html-template-guide.builder.d.ts +13 -0
  29. package/dist-sdk/server/src/documents/library/html-template-guide.builder.js +185 -0
  30. package/dist-sdk/server/src/documents/template-mapping.d.ts +203 -0
  31. package/dist-sdk/server/src/documents/template-mapping.js +452 -0
  32. package/dist-sdk/server/src/room/room.d.ts +2 -1
  33. package/dist-sdk/server/src/room/room.js +7 -3
  34. package/dist-sdk/server/src/sdk/index.d.ts +17 -4
  35. package/dist-sdk/server/src/sdk/index.js +37 -2
  36. package/dist-sdk/server/src/tools/core/data-change.tools.d.ts +19 -0
  37. package/dist-sdk/server/src/tools/core/data-change.tools.js +82 -0
  38. package/dist-sdk/server/src/tools/core/data.tools.js +22 -3
  39. package/dist-sdk/server/src/tools/core/document.tools.d.ts +22 -0
  40. package/dist-sdk/server/src/tools/core/document.tools.js +20 -6
  41. package/dist-sdk/server/src/tools/core/html-template.tools.d.ts +31 -0
  42. package/dist-sdk/server/src/tools/core/html-template.tools.js +494 -0
  43. package/dist-sdk/server/src/tools/core/index.js +4 -0
  44. package/package.json +1 -1
@@ -20,6 +20,8 @@ export interface AgentConfig {
20
20
  attachedArtifacts?: string[];
21
21
  history?: any[];
22
22
  maxHistoryMessages: number;
23
+ /** Tool calls this agent may chain in one turn, in place of the room's default. */
24
+ maxToolIterations?: number;
23
25
  totalInputTokens?: number;
24
26
  totalOutputTokens?: number;
25
27
  totalCost?: number;
@@ -208,6 +208,7 @@ let AgentStoreService = class AgentStoreService {
208
208
  instance.attachedFiles = [...template.attachedFiles];
209
209
  instance.attachedArtifacts = [...template.attachedArtifacts];
210
210
  instance.maxHistoryMessages = template.maxHistoryMessages;
211
+ instance.maxToolIterations = template.maxToolIterations;
211
212
  instance.promptCacheTTL = template.promptCacheTTL;
212
213
  instance.markupRate = template.markupRate;
213
214
  instance.smallModelName = template.smallModelName;
@@ -277,6 +278,7 @@ let AgentStoreService = class AgentStoreService {
277
278
  instance.attachedArtifacts = [...template.attachedArtifacts];
278
279
  instance.beginInstruction = template.beginInstruction;
279
280
  instance.maxHistoryMessages = template.maxHistoryMessages;
281
+ instance.maxToolIterations = template.maxToolIterations;
280
282
  instance.promptCacheTTL = template.promptCacheTTL;
281
283
  instance.markupRate = template.markupRate;
282
284
  instance.toolNames = [...template.toolNames];
@@ -394,6 +396,7 @@ let AgentStoreService = class AgentStoreService {
394
396
  // Restore begin instruction
395
397
  agent.beginInstruction = config.beginInstruction || '';
396
398
  agent.maxHistoryMessages = config.maxHistoryMessages || undefined;
399
+ agent.maxToolIterations = config.maxToolIterations || undefined;
397
400
  // Restore cache keep-alive settings
398
401
  agent.promptCacheTTL = Number(config.promptCacheTTL) ?? 0;
399
402
  // Restore tool grants
@@ -488,6 +491,7 @@ let AgentStoreService = class AgentStoreService {
488
491
  attachedArtifacts: agent.attachedArtifacts,
489
492
  history: agent.history,
490
493
  maxHistoryMessages: agent.maxHistoryMessages,
494
+ ...(agent.maxToolIterations ? { maxToolIterations: agent.maxToolIterations } : {}),
491
495
  totalInputTokens: agent.totalInputTokens,
492
496
  totalOutputTokens: agent.totalOutputTokens,
493
497
  totalCost: agent.totalCost,
@@ -82,6 +82,13 @@ export declare class Agent {
82
82
  */
83
83
  enabledPacks?: () => readonly string[];
84
84
  maxHistoryMessages?: number;
85
+ /**
86
+ * Tool calls this agent may chain in one turn, in place of the room's default
87
+ * (`ROOM_MAX_TOOL_ITERATIONS`, 30). For an agent whose one job is long — read a
88
+ * template, run its queries, fill, check, fill again — where the default would
89
+ * end its turn mid-task.
90
+ */
91
+ maxToolIterations?: number;
85
92
  /**
86
93
  * Index into {@link history} below which the rolling window may trim, and at or
87
94
  * above which it may not. Protects a task that must survive intact from an agent
@@ -83,6 +83,13 @@ class Agent {
83
83
  */
84
84
  enabledPacks;
85
85
  maxHistoryMessages; // If set, keep only last N messages (rolling window)
86
+ /**
87
+ * Tool calls this agent may chain in one turn, in place of the room's default
88
+ * (`ROOM_MAX_TOOL_ITERATIONS`, 30). For an agent whose one job is long — read a
89
+ * template, run its queries, fill, check, fill again — where the default would
90
+ * end its turn mid-task.
91
+ */
92
+ maxToolIterations;
86
93
  /**
87
94
  * Index into {@link history} below which the rolling window may trim, and at or
88
95
  * above which it may not. Protects a task that must survive intact from an agent
@@ -58,6 +58,8 @@ export interface AgentCreationOptions {
58
58
  promptCacheTTL?: number;
59
59
  /** Rolling history window: keep only the last N messages. */
60
60
  maxHistoryMessages?: number;
61
+ /** Tool calls the agent may chain in one turn, in place of the room's default. */
62
+ maxToolIterations?: number;
61
63
  /** A cheaper same-service model for mechanical prompts. */
62
64
  smallModelName?: string;
63
65
  /**
@@ -367,6 +367,8 @@ class AppService {
367
367
  agent.promptCacheTTL = options.promptCacheTTL;
368
368
  if (options.maxHistoryMessages !== undefined)
369
369
  agent.maxHistoryMessages = options.maxHistoryMessages;
370
+ if (options.maxToolIterations !== undefined)
371
+ agent.maxToolIterations = options.maxToolIterations;
370
372
  if (options.smallModelName !== undefined)
371
373
  agent.smallModelName = options.smallModelName;
372
374
  if (options.ownerRoomId !== undefined)
@@ -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>;