briyah 2.0.17 → 2.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist-sdk/server/src/ai/agent-config.d.ts +4 -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/balance.service.js +1 -1
  6. package/dist-sdk/server/src/app/usage-context.d.ts +19 -1
  7. package/dist-sdk/server/src/app/usage-context.js +21 -4
  8. package/dist-sdk/server/src/app.service.d.ts +2 -0
  9. package/dist-sdk/server/src/app.service.js +2 -0
  10. package/dist-sdk/server/src/data/query-validation.d.ts +9 -1
  11. package/dist-sdk/server/src/data/query-validation.js +9 -5
  12. package/dist-sdk/server/src/data/run-query.d.ts +14 -0
  13. package/dist-sdk/server/src/data/run-query.js +39 -0
  14. package/dist-sdk/server/src/documents/document-conversion.d.ts +27 -9
  15. package/dist-sdk/server/src/documents/document-conversion.js +131 -10
  16. package/dist-sdk/server/src/documents/html-data.d.ts +49 -0
  17. package/dist-sdk/server/src/documents/html-data.js +120 -0
  18. package/dist-sdk/server/src/documents/html-template.d.ts +108 -0
  19. package/dist-sdk/server/src/documents/html-template.js +332 -0
  20. package/dist-sdk/server/src/documents/library/document.types.d.ts +64 -0
  21. package/dist-sdk/server/src/documents/library/document.types.js +6 -0
  22. package/dist-sdk/server/src/documents/library/html-template-guide.builder.d.ts +13 -0
  23. package/dist-sdk/server/src/documents/library/html-template-guide.builder.js +185 -0
  24. package/dist-sdk/server/src/documents/template-mapping.d.ts +203 -0
  25. package/dist-sdk/server/src/documents/template-mapping.js +452 -0
  26. package/dist-sdk/server/src/room/room.d.ts +2 -1
  27. package/dist-sdk/server/src/room/room.js +7 -3
  28. package/dist-sdk/server/src/sdk/index.d.ts +12 -3
  29. package/dist-sdk/server/src/sdk/index.js +28 -2
  30. package/dist-sdk/server/src/tools/core/document.tools.d.ts +22 -0
  31. package/dist-sdk/server/src/tools/core/document.tools.js +20 -6
  32. package/dist-sdk/server/src/tools/core/html-template.tools.d.ts +31 -0
  33. package/dist-sdk/server/src/tools/core/html-template.tools.js +494 -0
  34. package/dist-sdk/server/src/tools/core/index.js +2 -0
  35. package/package.json +1 -1
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.documentTools = exports.unloadDocumentTool = exports.loadDocumentTool = exports.readDocumentTool = exports.findInDocumentsTool = exports.listDocumentsTool = void 0;
3
+ exports.documentTools = exports.unloadDocumentTool = exports.loadDocumentTool = exports.readDocumentTool = exports.findInDocumentsTool = exports.listDocumentsTool = exports.unavailable = void 0;
4
4
  exports.libraryAttachmentName = libraryAttachmentName;
5
5
  exports.isLibraryAttachment = isLibraryAttachment;
6
6
  exports.libraryDocumentIdOf = libraryDocumentIdOf;
7
+ exports.inScope = inScope;
8
+ exports.unknownDocument = unknownDocument;
7
9
  const coerce_1 = require("../shared/coerce");
8
10
  const document_registry_1 = require("../../documents/library/document-registry");
9
11
  /** A holding request past this many characters must be confirmed. Override with `DOCUMENT_LOAD_CONFIRM_CHARS`. */
@@ -52,7 +54,7 @@ function limitFromEnv(name, fallback) {
52
54
  const value = Number(process.env[name]);
53
55
  return Number.isFinite(value) && value > 0 ? value : fallback;
54
56
  }
55
- const unavailable = {
57
+ exports.unavailable = {
56
58
  ok: false,
57
59
  summary: 'No documents are available',
58
60
  error: 'This application has not made any documents available to search.',
@@ -94,6 +96,16 @@ function listedEntry(document, held, withSummary) {
94
96
  ...(document.addedAt ? { addedAt: document.addedAt } : {}),
95
97
  ...(document.state && document.state !== 'ready' ? { state: document.state } : {}),
96
98
  ...(held.has(document.documentId) ? { heldInFull: true } : {}),
99
+ ...(document.template?.length
100
+ ? {
101
+ htmlTemplate: {
102
+ dataBlocks: document.template,
103
+ ...(document.templateRecipe
104
+ ? { recipe: { savedAt: document.templateRecipe.savedAt, parameters: document.templateRecipe.parameters } }
105
+ : {}),
106
+ },
107
+ }
108
+ : {}),
97
109
  ...(withSummary && document.summary ? { summary: clip(document.summary, LIST_SUMMARY_CHARS) } : {}),
98
110
  };
99
111
  }
@@ -141,6 +153,8 @@ exports.listDocumentsTool = {
141
153
  description: 'Lists the documents available to you: each one\'s documentId, name, kind, page count, ' +
142
154
  'size and a short summary, and which of them you are holding in full. Documents can ' +
143
155
  'be added while you work, so list again rather than relying on an earlier answer. ' +
156
+ 'A document with htmlTemplate is an HTML page drawn from embedded data, which ' +
157
+ 'inspect_html_template and fill_html_template can make a new page from. ' +
144
158
  'A large library comes back without summaries, or in pages: when the result has a ' +
145
159
  'nextOffset you have NOT seen every document — call again with that offset, or narrow ' +
146
160
  'with kind or name, before saying what the library holds.',
@@ -166,7 +180,7 @@ exports.listDocumentsTool = {
166
180
  ],
167
181
  handler: async (args, helpers, context) => {
168
182
  if (!(0, document_registry_1.hasDocumentSources)())
169
- return unavailable;
183
+ return exports.unavailable;
170
184
  const kind = optionalString(args.kind, 'kind').toLowerCase();
171
185
  const name = optionalString(args.name, 'name').toLowerCase();
172
186
  const offset = Math.max(0, (0, coerce_1.int)(args.offset, 'offset', 0));
@@ -248,7 +262,7 @@ exports.findInDocumentsTool = {
248
262
  ],
249
263
  handler: async (args, _helpers, context) => {
250
264
  if (!(0, document_registry_1.hasDocumentSources)())
251
- return unavailable;
265
+ return exports.unavailable;
252
266
  const query = (0, coerce_1.str)(args.query, 'query');
253
267
  if (!query) {
254
268
  return { ok: false, summary: 'Nothing to search for', error: 'Say what to look for in "query".' };
@@ -310,7 +324,7 @@ exports.readDocumentTool = {
310
324
  ],
311
325
  handler: async (args, _helpers, context) => {
312
326
  if (!(0, document_registry_1.hasDocumentSources)())
313
- return unavailable;
327
+ return exports.unavailable;
314
328
  const documentId = (0, coerce_1.str)(args.documentId, 'documentId');
315
329
  const scope = await inScope(context);
316
330
  const match = scope.find(({ document }) => document.documentId === documentId);
@@ -370,7 +384,7 @@ exports.loadDocumentTool = {
370
384
  ],
371
385
  handler: async (args, helpers, context) => {
372
386
  if (!(0, document_registry_1.hasDocumentSources)())
373
- return unavailable;
387
+ return exports.unavailable;
374
388
  if (!helpers.documents) {
375
389
  return {
376
390
  ok: false,
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Making a new HTML page from a template in the document library.
3
+ *
4
+ * A template is an HTML page whose scripts draw everything from an embedded JSON
5
+ * data block (`html-data.ts`). An agent asked for "one like this, for someone
6
+ * else" inspects the template's data, works out what each part means, and names
7
+ * the changes; `fill_html_template` copies the page with exactly that data
8
+ * replaced and hands it to the host as a new document.
9
+ *
10
+ * A change can hold its value, or describe it: a query and how each row becomes a
11
+ * record (`template-mapping.ts`). Those queries run here, with the host's context,
12
+ * and their rows go straight into the page — never through the agent. A fill that
13
+ * works can be saved on the template as a recipe, with the customer as a
14
+ * parameter, so the next fill replays its queries and the agent writes only the
15
+ * narrative.
16
+ *
17
+ * Both tools read the template's original file through the source's optional
18
+ * `original`, the fill adds its result through `create`, and recipes go through
19
+ * `saveRecipe` / `recipe` — so they work for any host whose source implements
20
+ * them, and refuse plainly for one that does not. Scope is the same as every
21
+ * document tool's: an id is used only after the host lists it for this context.
22
+ */
23
+ import { NativeToolDefinition } from '../native-tool.types';
24
+ /**
25
+ * The most rows one query in a fill may bring back. Far above `query_data`'s,
26
+ * because these rows go into the page, not into an agent's context.
27
+ */
28
+ export declare const TEMPLATE_FILL_MAX_ROWS = 10000;
29
+ export declare const inspectHtmlTemplateTool: NativeToolDefinition;
30
+ export declare const fillHtmlTemplateTool: NativeToolDefinition;
31
+ export declare const htmlTemplateTools: NativeToolDefinition[];
@@ -0,0 +1,494 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.htmlTemplateTools = exports.fillHtmlTemplateTool = exports.inspectHtmlTemplateTool = exports.TEMPLATE_FILL_MAX_ROWS = void 0;
4
+ const coerce_1 = require("../shared/coerce");
5
+ const document_registry_1 = require("../../documents/library/document-registry");
6
+ const document_conversion_1 = require("../../documents/document-conversion");
7
+ const html_data_1 = require("../../documents/html-data");
8
+ const html_template_1 = require("../../documents/html-template");
9
+ const template_mapping_1 = require("../../documents/template-mapping");
10
+ const run_query_1 = require("../../data/run-query");
11
+ const document_tools_1 = require("./document.tools");
12
+ /** Records a list is read in when no limit is given, and the most one read may ask for. */
13
+ const DEFAULT_RECORDS = 10;
14
+ const MAX_RECORDS = 50;
15
+ /**
16
+ * The most rows one query in a fill may bring back. Far above `query_data`'s,
17
+ * because these rows go into the page, not into an agent's context.
18
+ */
19
+ exports.TEMPLATE_FILL_MAX_ROWS = 10_000;
20
+ const CHANGES_EXAMPLE = '[{"path":"meta.client","value":{"$param":"customer"}},' +
21
+ '{"path":"claims","rows":{"dataset":"claims","filters":[{"field":"customer","op":"eq","value":{"$param":"customer"}}],' +
22
+ '"select":["claimNumber","paid"]},"each":{"n":"claimNumber","pd":{"field":"paid","scale":100}}},' +
23
+ '{"path":"story.summary","value":"Acme had 12 claims…","note":"one-paragraph summary of the losses"}]';
24
+ const PARAMETERS_EXAMPLE = '{"customer": "Acme Trucking"}';
25
+ const FACTS_EXAMPLE = '[{"name":"losses by year","query":{"dataset":"claims","groupBy":["policyYear"],"metrics":[{"fn":"sum","field":"incurred"}]}}]';
26
+ function refusal(summary, error) {
27
+ return { ok: false, summary, error };
28
+ }
29
+ /** The template an agent named, read from its original file — or why it cannot be. */
30
+ async function openTemplate(documentId, context) {
31
+ if (!(0, document_registry_1.hasDocumentSources)())
32
+ return document_tools_1.unavailable;
33
+ const scope = await (0, document_tools_1.inScope)(context);
34
+ const match = scope.find(({ document }) => document.documentId === documentId);
35
+ if (!match)
36
+ return (0, document_tools_1.unknownDocument)(documentId, scope);
37
+ const { source, document } = match;
38
+ if (!source.original) {
39
+ return refusal('No original file', `"${document.name}" is kept as text only here, so it cannot be used as a template.`);
40
+ }
41
+ const original = await source.original(context, documentId);
42
+ if (!original) {
43
+ return refusal('No original file', `"${document.name}" has no original file to work from, so it cannot be used as a template.`);
44
+ }
45
+ if ((0, document_conversion_1.detectDocumentType)(original.bytes, original.fileName).type !== 'html') {
46
+ return refusal('Not an HTML page', `"${document.name}" is not an HTML page, so it is not a template that can be filled.`);
47
+ }
48
+ const html = new TextDecoder('utf-8').decode(original.bytes).replace(/^\uFEFF/, '');
49
+ return { source, document, html };
50
+ }
51
+ function isRefusal(value) {
52
+ return !!value && typeof value === 'object' && value.ok === false;
53
+ }
54
+ /**
55
+ * The recipe saved for a template, checked against the template as it is now —
56
+ * or why there is none to use.
57
+ */
58
+ async function openRecipe(template, context, currentValue) {
59
+ const { source, document } = template;
60
+ if (!source.recipe) {
61
+ return refusal('No recipes here', 'This library does not keep fill recipes. Fill the template without recipe.');
62
+ }
63
+ const recipe = await source.recipe(context, document.documentId);
64
+ if (!recipe) {
65
+ return refusal('No recipe saved', `No recipe is saved for "${document.name}". Fill it without recipe, then save one with saveRecipe.`);
66
+ }
67
+ if (recipe.shape !== (0, html_data_1.describeShape)(currentValue)) {
68
+ return refusal('The recipe is stale', `The recipe saved for "${document.name}" was made for a different version of the template's data. ` +
69
+ 'Fill it without recipe, and save a new recipe with saveRecipe.');
70
+ }
71
+ return recipe;
72
+ }
73
+ /** A file name for a new page, from what it is called. */
74
+ function htmlFileName(name) {
75
+ const safe = (name || 'Page').replace(/[\\/:*?"<>|]/g, '_').replace(/\s+/g, ' ').trim().slice(0, 150);
76
+ return `${safe || 'Page'}.html`;
77
+ }
78
+ function optionalString(value, param) {
79
+ return value === undefined || value === null || value === '' ? '' : (0, coerce_1.str)(value, param);
80
+ }
81
+ /**
82
+ * Applies changes to a copy of the template's data in order, running the
83
+ * query-backed ones.
84
+ *
85
+ * @throws {TemplateError} As the changes do
86
+ */
87
+ async function applyAll(value, changes, context, parameters) {
88
+ let data = structuredClone(value);
89
+ const warnings = [];
90
+ const touched = new Set();
91
+ const reports = [];
92
+ const run = fillRunner(context);
93
+ for (const change of changes) {
94
+ let plain;
95
+ if ((0, template_mapping_1.isQueryBacked)(change)) {
96
+ const made = await (0, template_mapping_1.materializeChange)(change, data, run, parameters, exports.TEMPLATE_FILL_MAX_ROWS);
97
+ plain = made.change;
98
+ reports.push(made.report);
99
+ warnings.push(...made.warnings);
100
+ }
101
+ else {
102
+ plain = (0, template_mapping_1.resolveParams)(change, parameters);
103
+ }
104
+ data = (0, html_template_1.applyChange)(data, plain, warnings, touched);
105
+ }
106
+ return { data, warnings, touched, reports };
107
+ }
108
+ /** An item of a list in a few words: its first text and number fields, so the agent knows which one it is writing for. */
109
+ function itemSummary(item) {
110
+ if (!item || typeof item !== 'object' || Array.isArray(item))
111
+ return undefined;
112
+ const scalars = Object.entries(item).filter(([, value]) => ['string', 'number', 'boolean'].includes(typeof value));
113
+ return Object.fromEntries(scalars.slice(0, 5));
114
+ }
115
+ /** Runs a fill's queries with the caller's context and the fill's own row ceiling. */
116
+ function fillRunner(context) {
117
+ return (query) => (0, run_query_1.runDataQuery)(query, context, { maxLimit: exports.TEMPLATE_FILL_MAX_ROWS });
118
+ }
119
+ exports.inspectHtmlTemplateTool = {
120
+ name: 'inspect_html_template',
121
+ description: 'Shows the data inside an HTML template — a page whose scripts draw everything from an ' +
122
+ 'embedded JSON data block (list_documents marks these htmlTemplate). Without a path it ' +
123
+ 'lists the data blocks and their shape, and says whether a fill recipe is saved. With a ' +
124
+ 'path it returns the exact data there: "meta", "claims", "lines[0].terms", "$" for ' +
125
+ 'everything; a list comes back a page of records at a time. Pass paths to read several ' +
126
+ 'parts in one call — every narrative and settings part at once. With recipe: true and ' +
127
+ 'parameters it shows the saved recipe — the parts to write and its facts, run for those ' +
128
+ 'parameters — without filling anything.',
129
+ parameters: [
130
+ { name: 'documentId', type: 'string', description: 'The template.', required: true },
131
+ { name: 'path', type: 'string', description: 'The part of the data to read. Omit to see the shape.', required: false },
132
+ {
133
+ name: 'paths',
134
+ type: 'array',
135
+ description: 'Several parts to read in one call, e.g. ["meta", "story", "titles", "findings", "claims"]; lists come a page at a time.',
136
+ required: false,
137
+ },
138
+ {
139
+ name: 'block',
140
+ type: 'string',
141
+ description: 'Which data block, when the page has more than one. Omit when it has one.',
142
+ required: false,
143
+ },
144
+ { name: 'offset', type: 'number', description: 'For a list: the first record to return. Defaults to 0.', required: false },
145
+ {
146
+ name: 'limit',
147
+ type: 'number',
148
+ description: `For a list: how many records, up to ${MAX_RECORDS}. Defaults to ${DEFAULT_RECORDS}.`,
149
+ required: false,
150
+ },
151
+ { name: 'recipe', type: 'boolean', description: 'Show the saved fill recipe instead of the data.', required: false },
152
+ {
153
+ name: 'parameters',
154
+ type: 'object',
155
+ description: `With recipe: the values for its parameters, e.g. ${PARAMETERS_EXAMPLE}.`,
156
+ required: false,
157
+ },
158
+ ],
159
+ handler: async (args, _helpers, context) => {
160
+ const template = await openTemplate((0, coerce_1.str)(args.documentId, 'documentId'), context);
161
+ if (isRefusal(template))
162
+ return template;
163
+ const { document, html, source } = template;
164
+ const path = optionalString(args.path, 'path');
165
+ const block = optionalString(args.block, 'block');
166
+ const paths = args.paths === undefined || args.paths === null || args.paths === ''
167
+ ? []
168
+ : (Array.isArray(args.paths) ? args.paths : (0, coerce_1.jsonArray)(args.paths, 'paths', '["meta", "story"]')).map(String);
169
+ if ((0, coerce_1.bool)(args.recipe)) {
170
+ let value;
171
+ try {
172
+ ({ value } = (0, html_template_1.templateData)(html, block || undefined));
173
+ }
174
+ catch (error) {
175
+ if (error instanceof html_template_1.TemplateError)
176
+ return refusal('Not a template', error.message);
177
+ throw error;
178
+ }
179
+ const recipe = await openRecipe(template, context, value);
180
+ if (isRefusal(recipe))
181
+ return recipe;
182
+ const parameters = (0, coerce_1.jsonObject)(args.parameters, 'parameters', PARAMETERS_EXAMPLE);
183
+ const missing = recipe.parameters.filter((name) => !(name in parameters));
184
+ if (missing.length) {
185
+ return refusal('Parameters missing', `The recipe needs a value for ${missing.map((name) => `"${name}"`).join(', ')} in parameters.`);
186
+ }
187
+ // Replay the recipe for these parameters, so each part written per item
188
+ // ([*]) can be named for each item this client actually has.
189
+ let built;
190
+ try {
191
+ built = (await applyAll(value, recipe.changes, context, parameters)).data;
192
+ }
193
+ catch (error) {
194
+ if (error instanceof html_template_1.TemplateError)
195
+ return refusal('The recipe could not run', error.message);
196
+ throw error;
197
+ }
198
+ const write = recipe.written.flatMap((part) => part.path.includes('[*]')
199
+ ? (0, template_mapping_1.expandWrittenPath)(part.path, built).map((path) => {
200
+ const itemPath = path.slice(0, path.lastIndexOf(']') + 1);
201
+ let item;
202
+ try {
203
+ item = (0, html_template_1.valueAtPath)(built, itemPath);
204
+ }
205
+ catch {
206
+ item = undefined;
207
+ }
208
+ return { path, ...(part.note ? { note: part.note } : {}), ...(itemSummary(item) ? { item: itemSummary(item) } : {}) };
209
+ })
210
+ : [part]);
211
+ const facts = [];
212
+ for (const fact of recipe.facts) {
213
+ const result = await (0, run_query_1.runDataQuery)((0, template_mapping_1.resolveParams)(fact.query, parameters), context);
214
+ facts.push(result.ok
215
+ ? { name: fact.name, rows: result.rows.slice(0, 50) }
216
+ : { name: fact.name, error: result.error });
217
+ }
218
+ return {
219
+ ok: true,
220
+ summary: `Read the recipe for "${document.name}"`,
221
+ documentId: document.documentId,
222
+ savedAt: recipe.savedAt,
223
+ ...(recipe.savedBy ? { savedBy: recipe.savedBy } : {}),
224
+ parameters: recipe.parameters,
225
+ ...(recipe.notes ? { notes: recipe.notes } : {}),
226
+ write,
227
+ facts,
228
+ note: 'Write each part in "write" from these facts (and any other queries you need), in the template\'s ' +
229
+ 'voice; a part for one item of a list says which item it is. Then call fill_html_template with ' +
230
+ 'recipe: true, the same parameters, and exactly those paths as changes.',
231
+ };
232
+ }
233
+ if (paths.length) {
234
+ let chosen;
235
+ let value;
236
+ try {
237
+ ({ block: chosen, value } = (0, html_template_1.templateData)(html, block || undefined));
238
+ }
239
+ catch (error) {
240
+ if (error instanceof html_template_1.TemplateError)
241
+ return refusal('Not a template', error.message);
242
+ throw error;
243
+ }
244
+ const limit = Math.min(Math.max(1, (0, coerce_1.int)(args.limit, 'limit', DEFAULT_RECORDS)), MAX_RECORDS);
245
+ const offset = Math.max(0, (0, coerce_1.int)(args.offset, 'offset', 0));
246
+ const parts = paths.map((wanted) => {
247
+ try {
248
+ const part = (0, html_template_1.readTemplateData)(value, wanted, { offset, limit });
249
+ return Array.isArray((0, html_template_1.valueAtPath)(value, wanted)) ? { path: wanted, ...part } : { path: wanted, value: part };
250
+ }
251
+ catch (error) {
252
+ if (error instanceof html_template_1.TemplateError)
253
+ return { path: wanted, error: error.message };
254
+ throw error;
255
+ }
256
+ });
257
+ return {
258
+ ok: true,
259
+ summary: `Read ${paths.length} part(s) of "${document.name}"`,
260
+ block: chosen.label,
261
+ parts,
262
+ };
263
+ }
264
+ if (!path) {
265
+ const blocks = (0, html_data_1.findDataBlocks)(html);
266
+ if (!blocks.length) {
267
+ return refusal('Not a template', `"${document.name}" has no JSON data block, so it is not a template that can be filled.`);
268
+ }
269
+ const title = html.match(/<title\b[^>]*>([\s\S]*?)<\/title\s*>/i)?.[1]?.trim();
270
+ const saved = source.recipe ? await source.recipe(context, document.documentId) : null;
271
+ return {
272
+ ok: true,
273
+ summary: `Inspected "${document.name}": ${blocks.map((entry) => entry.label).join(', ')}`,
274
+ documentId: document.documentId,
275
+ name: document.name,
276
+ ...(title ? { title } : {}),
277
+ dataBlocks: blocks.map((entry) => ({
278
+ block: entry.label,
279
+ chars: entry.text.length,
280
+ shape: entry.value === undefined ? 'not valid JSON' : (0, html_data_1.describeShape)(entry.value),
281
+ })),
282
+ ...(saved ? { recipe: { savedAt: saved.savedAt, parameters: saved.parameters, ...(saved.savedBy ? { savedBy: saved.savedBy } : {}) } } : {}),
283
+ note: saved
284
+ ? 'A fill recipe is saved: read it with recipe: true and parameters, write its parts, and fill with recipe: true.'
285
+ : 'Read the parts with paths before filling — every narrative and settings object whole and a few ' +
286
+ 'records of every list, in one or two calls. Work out what each field means from its values and from the parts that ' +
287
+ 'describe them (totals, labels, prose).',
288
+ };
289
+ }
290
+ try {
291
+ const { block: chosen, value } = (0, html_template_1.templateData)(html, block || undefined);
292
+ const limit = Math.min(Math.max(1, (0, coerce_1.int)(args.limit, 'limit', DEFAULT_RECORDS)), MAX_RECORDS);
293
+ const offset = Math.max(0, (0, coerce_1.int)(args.offset, 'offset', 0));
294
+ const part = (0, html_template_1.readTemplateData)(value, path, { offset, limit });
295
+ const isList = Array.isArray((0, html_template_1.valueAtPath)(value, path));
296
+ return {
297
+ ok: true,
298
+ summary: `Read "${path}" in "${document.name}"`,
299
+ block: chosen.label,
300
+ path,
301
+ ...(isList ? part : { value: part }),
302
+ };
303
+ }
304
+ catch (error) {
305
+ if (error instanceof html_template_1.TemplateError)
306
+ return refusal(`Could not read "${path}"`, error.message);
307
+ throw error;
308
+ }
309
+ },
310
+ maxResultChars: 30_000,
311
+ timeoutMs: 60_000,
312
+ };
313
+ exports.fillHtmlTemplateTool = {
314
+ name: 'fill_html_template',
315
+ description: 'Makes a new HTML page from a template: a copy with the data you name replaced and everything ' +
316
+ 'else — its scripts, styles and any data you do not name — kept. Each change sets a path: ' +
317
+ '{"path","value"} with the value itself; or {"path","rows","each"} to build a list of records ' +
318
+ 'from a query (each row mapped by "each"); or {"path","query","take"} for one figure from a ' +
319
+ 'query. Query rows go straight into the page. Write the customer and other changing values as ' +
320
+ '{"$param": "name"} and pass their values in parameters. saveRecipe: true keeps this fill as the ' +
321
+ 'template\'s recipe; recipe: true replays a saved recipe, with the parts it says to write given ' +
322
+ 'as changes. The page is added to the documents under the name you give; filling again with the ' +
323
+ 'same name replaces it. Read the warnings and each query-backed change\'s sample.',
324
+ parameters: [
325
+ { name: 'documentId', type: 'string', description: 'The template.', required: true },
326
+ {
327
+ name: 'name',
328
+ type: 'string',
329
+ description: 'What to call the new page: whose it is and what, e.g. "Acme Trucking - Loss Analysis 2022-2026".',
330
+ required: true,
331
+ },
332
+ {
333
+ name: 'changes',
334
+ type: 'array',
335
+ description: `The data to replace, as a JSON array, e.g. ${CHANGES_EXAMPLE}. Mark a fixed change that is the ` +
336
+ 'same for every client "keep": true, and give a written one (narrative) a short "note".',
337
+ required: false,
338
+ },
339
+ {
340
+ name: 'parameters',
341
+ type: 'object',
342
+ description: `Values for the {"$param": …} placeholders, e.g. ${PARAMETERS_EXAMPLE}.`,
343
+ required: false,
344
+ },
345
+ { name: 'title', type: 'string', description: 'A new browser-tab title for the page.', required: false },
346
+ {
347
+ name: 'block',
348
+ type: 'string',
349
+ description: 'Which data block, when the page has more than one. Omit when it has one.',
350
+ required: false,
351
+ },
352
+ { name: 'recipe', type: 'boolean', description: 'Replay the recipe saved for this template, then apply changes.', required: false },
353
+ {
354
+ name: 'saveRecipe',
355
+ type: 'boolean',
356
+ description: 'Save this fill as the template\'s recipe, replacing any saved before. Only once the fill is right.',
357
+ required: false,
358
+ },
359
+ {
360
+ name: 'facts',
361
+ type: 'array',
362
+ description: `With saveRecipe: the totals queries the narrative is written from, e.g. ${FACTS_EXAMPLE}.`,
363
+ required: false,
364
+ },
365
+ { name: 'notes', type: 'string', description: 'With saveRecipe: anything the next fill should know.', required: false },
366
+ ],
367
+ handler: async (args, _helpers, context) => {
368
+ const name = (0, coerce_1.str)(args.name, 'name').trim();
369
+ if (!name) {
370
+ return refusal('No name', 'Give the new page a name that says whose it is and what.');
371
+ }
372
+ const callChanges = (0, coerce_1.jsonArray)(args.changes, 'changes', CHANGES_EXAMPLE);
373
+ const parameters = (0, coerce_1.jsonObject)(args.parameters, 'parameters', PARAMETERS_EXAMPLE);
374
+ const title = optionalString(args.title, 'title');
375
+ const useRecipe = (0, coerce_1.bool)(args.recipe);
376
+ const saveRecipe = (0, coerce_1.bool)(args.saveRecipe);
377
+ const template = await openTemplate((0, coerce_1.str)(args.documentId, 'documentId'), context);
378
+ if (isRefusal(template))
379
+ return template;
380
+ const { source, document, html } = template;
381
+ if (!source.create) {
382
+ return refusal('Cannot add documents', 'New documents cannot be added to this library, so a template cannot be filled here.');
383
+ }
384
+ let block;
385
+ let value;
386
+ try {
387
+ ({ block, value } = (0, html_template_1.templateData)(html, optionalString(args.block, 'block') || undefined));
388
+ }
389
+ catch (error) {
390
+ if (error instanceof html_template_1.TemplateError)
391
+ return refusal('Could not fill the template', error.message);
392
+ throw error;
393
+ }
394
+ let changes = callChanges;
395
+ let recipe = null;
396
+ if (useRecipe) {
397
+ const opened = await openRecipe(template, context, value);
398
+ if (isRefusal(opened))
399
+ return opened;
400
+ recipe = opened;
401
+ changes = [...recipe.changes, ...callChanges];
402
+ }
403
+ if (!changes.length && !title) {
404
+ return refusal('No changes', `There is nothing to change. Give changes, e.g. ${CHANGES_EXAMPLE}.`);
405
+ }
406
+ let data;
407
+ let warnings;
408
+ let touched;
409
+ let reports;
410
+ try {
411
+ ({ data, warnings, touched, reports } = await applyAll(value, changes, context, parameters));
412
+ }
413
+ catch (error) {
414
+ if (error instanceof html_template_1.TemplateError)
415
+ return refusal('Could not fill the template', error.message);
416
+ throw error;
417
+ }
418
+ // Checked once the recipe's lists are built: a part written for every line
419
+ // (`lines[*].exec_title`) means every line this client has.
420
+ if (recipe) {
421
+ const missing = recipe.written.flatMap((part) => (0, template_mapping_1.expandWrittenPath)(part.path, data)
422
+ .filter((path) => !callChanges.some((change) => change?.path && (0, template_mapping_1.coversPath)(change.path, path)))
423
+ .map((path) => ({ path, ...(part.note ? { note: part.note } : {}) })));
424
+ if (missing.length) {
425
+ return {
426
+ ...refusal('Written parts missing', 'The recipe says these parts are written afresh for each fill, and the changes do not set them:'),
427
+ missing,
428
+ note: 'inspect_html_template with recipe: true shows what each says and the facts to write it from. Nothing was saved.',
429
+ };
430
+ }
431
+ }
432
+ const written = (0, html_template_1.writeTemplateData)(html, block, data, title || undefined);
433
+ warnings.push(...written.warnings);
434
+ const created = await source.create(context, {
435
+ name,
436
+ fileName: htmlFileName(name),
437
+ mimeType: 'text/html',
438
+ bytes: new TextEncoder().encode(written.html),
439
+ basedOn: document.documentId,
440
+ });
441
+ warnings.push(...(created.warnings ?? []));
442
+ let recipeNote;
443
+ if (saveRecipe) {
444
+ if (!source.saveRecipe) {
445
+ recipeNote = 'This library does not keep fill recipes, so none was saved.';
446
+ }
447
+ else {
448
+ const facts = args.facts === undefined || args.facts === null
449
+ ? (recipe?.facts ?? [])
450
+ : (0, coerce_1.jsonArray)(args.facts, 'facts', FACTS_EXAMPLE);
451
+ const saved = (0, template_mapping_1.buildRecipe)({
452
+ block: block.label,
453
+ templateValue: value,
454
+ changes,
455
+ parameters,
456
+ facts,
457
+ notes: optionalString(args.notes, 'notes') || recipe?.notes,
458
+ });
459
+ await source.saveRecipe(context, document.documentId, saved);
460
+ recipeNote =
461
+ `Saved as the recipe for "${document.name}": ${saved.changes.length} change(s) replayed, ` +
462
+ `${saved.written.length} part(s) to write each time, parameters ${saved.parameters.join(', ') || '(none)'}.`;
463
+ }
464
+ }
465
+ const untouched = (0, html_template_1.untouchedKeys)(value, touched);
466
+ return {
467
+ ok: true,
468
+ summary: `Made "${created.name}" from "${document.name}"${recipe ? ' with its recipe' : ''}` +
469
+ `${warnings.length ? ` (${warnings.length} warning(s))` : ''}`,
470
+ documentId: created.documentId,
471
+ name: created.name,
472
+ block: block.label,
473
+ changed: changes.map((change) => change.path),
474
+ ...(reports.length ? { fromQueries: reports } : {}),
475
+ ...(untouched.length
476
+ ? {
477
+ untouched,
478
+ untouchedNote: 'These parts still hold the template\'s data. Leave a part only if it is the same for anyone ' +
479
+ '(reference data, settings, labels); anything about the template\'s own subject must be replaced.',
480
+ }
481
+ : {}),
482
+ ...(warnings.length
483
+ ? {
484
+ warnings,
485
+ note: 'Check each warning. To fix one, call fill_html_template again with the same name: it replaces this page.',
486
+ }
487
+ : {}),
488
+ ...(recipeNote ? { recipe: recipeNote } : {}),
489
+ };
490
+ },
491
+ maxResultChars: 16_000,
492
+ timeoutMs: 120_000,
493
+ };
494
+ exports.htmlTemplateTools = [exports.inspectHtmlTemplateTool, exports.fillHtmlTemplateTool];
@@ -20,6 +20,7 @@ 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
22
  const document_tools_1 = require("./document.tools");
23
+ const html_template_tools_1 = require("./html-template.tools");
23
24
  const illustrate_tool_1 = require("./illustrate.tool");
24
25
  const rename_tool_1 = require("./rename.tool");
25
26
  /** The name the UI groups these under, in place of a pack name. */
@@ -40,5 +41,6 @@ function coreTools() {
40
41
  data_tools_1.describeDataTool,
41
42
  data_tools_1.queryDataTool,
42
43
  ...document_tools_1.documentTools,
44
+ ...html_template_tools_1.htmlTemplateTools,
43
45
  ];
44
46
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "briyah",
3
- "version": "2.0.17",
3
+ "version": "2.0.19",
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",