briyah 2.0.15 → 2.0.17

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.
package/README.md CHANGED
@@ -1415,6 +1415,34 @@ Leave it out for a story or campaign, which keeps its own clock (the room's situ
1415
1415
  know is refused with a `ValidationError`. Room Settings has it as "Tell the agents today's date",
1416
1416
  and a pack room template as `timeZone`.
1417
1417
 
1418
+ ### Example 16: Letting an agent make charts
1419
+
1420
+ Grant the core tool `make_chart`. The agent describes a chart as data — a line, column, bar,
1421
+ stacked column or pie, its categories and one value per category in each series — and gets back
1422
+ a `block` to put in its message or document:
1423
+
1424
+ ````
1425
+ ```chart
1426
+ {"type":"line","title":"Fleet miles by quarter","categories":["2025 Q1","2025 Q2"],"series":[{"name":"Fleet miles","values":[970269,1007320]}]}
1427
+ ```
1428
+ ````
1429
+
1430
+ The host draws each block wherever it shows the agent's markdown:
1431
+
1432
+ ```typescript
1433
+ import { validateChart, renderChartSvg, CHART_BLOCK_LANGUAGE } from 'briyah';
1434
+
1435
+ // e.g. a marked renderer: code({ text, lang }) for lang === CHART_BLOCK_LANGUAGE
1436
+ const checked = validateChart(JSON.parse(text));
1437
+ const html = checked.ok ? renderChartSvg(checked.spec) : `<em>Chart could not be drawn: ${checked.error}</em>`;
1438
+ ```
1439
+
1440
+ `renderChartSvg` is a pure function: no dependencies, nothing fetched, every label escaped. The
1441
+ same spec gives the same SVG in a viewer and a printed PDF. Validate before drawing even though
1442
+ the tool already checked: stored text can be edited since. Columns and bars start at zero; a line
1443
+ fits its axis to the data unless the spec says `"startAtZero": true`. Never ask an image model
1444
+ for a chart — it draws a plausible one with numbers of its own.
1445
+
1418
1446
  ## Data Storage
1419
1447
 
1420
1448
  Briyah stores data in the following structure:
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Turns a Briyah response schema into one Anthropic's structured outputs accept.
3
+ *
4
+ * Every other provider already constrains its reply to the schema it is given
5
+ * (OpenAI `json_schema`, Gemini `responseSchema`, Together `json_schema`); the
6
+ * Anthropic path used to paste the schema into the prompt and only check that the
7
+ * reply parsed. Valid JSON in the wrong shape went straight through: an agent that
8
+ * answered with a tool's bare arguments — `{"dataset": …}` with no `action` — was
9
+ * accepted, routed to the moderator, and stalled its room. Sent as
10
+ * `output_config.format`, the schema is enforced while the reply is generated, so
11
+ * that shape cannot be produced.
12
+ *
13
+ * Anthropic's schema dialect is narrower than JSON Schema. Every object must say
14
+ * `additionalProperties: false`, and some keywords are refused. This returns a
15
+ * copy that meets those rules, or null when the schema needs something the dialect
16
+ * cannot express — the caller then sends no format and falls back to the prompt
17
+ * contract alone, which is what every call did before.
18
+ */
19
+ /**
20
+ * The schema to send as `output_config.format.schema`, or null when it cannot be sent.
21
+ * @param jsonSchema A Briyah response schema, as loaded from a prompt folder's `.json`
22
+ * @returns A converted copy (the input is never modified), or null
23
+ */
24
+ export declare function toAnthropicOutputSchema(jsonSchema: unknown): Record<string, unknown> | null;
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ /**
3
+ * Turns a Briyah response schema into one Anthropic's structured outputs accept.
4
+ *
5
+ * Every other provider already constrains its reply to the schema it is given
6
+ * (OpenAI `json_schema`, Gemini `responseSchema`, Together `json_schema`); the
7
+ * Anthropic path used to paste the schema into the prompt and only check that the
8
+ * reply parsed. Valid JSON in the wrong shape went straight through: an agent that
9
+ * answered with a tool's bare arguments — `{"dataset": …}` with no `action` — was
10
+ * accepted, routed to the moderator, and stalled its room. Sent as
11
+ * `output_config.format`, the schema is enforced while the reply is generated, so
12
+ * that shape cannot be produced.
13
+ *
14
+ * Anthropic's schema dialect is narrower than JSON Schema. Every object must say
15
+ * `additionalProperties: false`, and some keywords are refused. This returns a
16
+ * copy that meets those rules, or null when the schema needs something the dialect
17
+ * cannot express — the caller then sends no format and falls back to the prompt
18
+ * contract alone, which is what every call did before.
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.toAnthropicOutputSchema = toAnthropicOutputSchema;
22
+ /** Keywords Anthropic's structured outputs refuse. Dropping one loosens nothing the reply relies on. */
23
+ const UNSUPPORTED_KEYWORDS = [
24
+ 'minimum',
25
+ 'maximum',
26
+ 'exclusiveMinimum',
27
+ 'exclusiveMaximum',
28
+ 'multipleOf',
29
+ 'minLength',
30
+ 'maxLength',
31
+ 'maxItems',
32
+ 'uniqueItems',
33
+ 'minProperties',
34
+ 'maxProperties',
35
+ 'patternProperties',
36
+ ];
37
+ /** String formats Anthropic validates; any other `format` is dropped. */
38
+ const SUPPORTED_FORMATS = new Set([
39
+ 'date-time', 'time', 'date', 'duration', 'email', 'hostname', 'uri', 'ipv4', 'ipv6', 'uuid',
40
+ ]);
41
+ /** Keywords whose value is one subschema. */
42
+ const SUBSCHEMA_KEYS = ['items', 'not'];
43
+ /** Keywords whose value is a list of subschemas. */
44
+ const SUBSCHEMA_LIST_KEYS = ['anyOf', 'allOf', 'oneOf', 'prefixItems'];
45
+ /** Keywords whose value maps names to subschemas. */
46
+ const SUBSCHEMA_MAP_KEYS = ['properties', '$defs', 'definitions'];
47
+ /** Thrown inside the walk when a schema cannot be expressed; caught by the entry point. */
48
+ class Inexpressible extends Error {
49
+ }
50
+ function isObjectSchema(schema) {
51
+ const type = schema.type;
52
+ return type === 'object' || (Array.isArray(type) && type.includes('object')) || 'properties' in schema;
53
+ }
54
+ function convert(schema) {
55
+ if (Array.isArray(schema))
56
+ return schema.map(convert);
57
+ if (!schema || typeof schema !== 'object')
58
+ return schema;
59
+ const out = {};
60
+ for (const [key, value] of Object.entries(schema)) {
61
+ if (UNSUPPORTED_KEYWORDS.includes(key))
62
+ continue;
63
+ if (key === 'format' && !SUPPORTED_FORMATS.has(String(value)))
64
+ continue;
65
+ // Only 0 or 1 is accepted as a minimum item count.
66
+ if (key === 'minItems' && Number(value) > 1)
67
+ continue;
68
+ if (SUBSCHEMA_KEYS.includes(key)) {
69
+ out[key] = convert(value);
70
+ }
71
+ else if (SUBSCHEMA_LIST_KEYS.includes(key) && Array.isArray(value)) {
72
+ out[key] = value.map(convert);
73
+ }
74
+ else if (SUBSCHEMA_MAP_KEYS.includes(key) && value && typeof value === 'object') {
75
+ out[key] = Object.fromEntries(Object.entries(value).map(([name, sub]) => [name, convert(sub)]));
76
+ }
77
+ else {
78
+ out[key] = value;
79
+ }
80
+ }
81
+ if (isObjectSchema(out)) {
82
+ // An open object — a map of arbitrary keys — is not expressible at all.
83
+ if (out.additionalProperties !== undefined && out.additionalProperties !== false) {
84
+ throw new Inexpressible('additionalProperties other than false');
85
+ }
86
+ out.additionalProperties = false;
87
+ }
88
+ return out;
89
+ }
90
+ /**
91
+ * The schema to send as `output_config.format.schema`, or null when it cannot be sent.
92
+ * @param jsonSchema A Briyah response schema, as loaded from a prompt folder's `.json`
93
+ * @returns A converted copy (the input is never modified), or null
94
+ */
95
+ function toAnthropicOutputSchema(jsonSchema) {
96
+ if (!jsonSchema || typeof jsonSchema !== 'object' || Array.isArray(jsonSchema))
97
+ return null;
98
+ // `name` labels the schema for OpenAI's response_format; it is not a JSON Schema keyword.
99
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
100
+ const { name: _name, ...schema } = jsonSchema;
101
+ try {
102
+ const converted = convert(schema);
103
+ // Structured outputs describe an object reply; anything else stays on the prompt contract.
104
+ return isObjectSchema(converted) ? converted : null;
105
+ }
106
+ catch (error) {
107
+ if (error instanceof Inexpressible)
108
+ return null;
109
+ throw error;
110
+ }
111
+ }
@@ -76,6 +76,35 @@ export declare class AnthropicAiService extends BaseAiService {
76
76
  */
77
77
  private static trimHeadroom;
78
78
  textPrompt(agent: Agent, prompt: string, jsonSchema?: any, saveResponse?: boolean, promptInstructions?: string, cacheConfig?: any, maxOutputChars?: number): Promise<any>;
79
+ /**
80
+ * Model and schema pairs the API refused a format for. Later calls with the same
81
+ * pair go out on the prompt contract alone rather than failing first every time.
82
+ * Process-lifetime: a model that gains support is picked up on restart.
83
+ */
84
+ private static readonly unconstrained;
85
+ /**
86
+ * The schema to enforce on this call, or null to rely on the prompt contract.
87
+ * @param agent The agent being prompted
88
+ * @param jsonSchema The response schema, if the call has one
89
+ * @returns The converted schema and the key it is remembered under, or null
90
+ */
91
+ private outputFormatFor;
92
+ /**
93
+ * Sends a request, and when the API refuses its output format, sends it again
94
+ * without one.
95
+ *
96
+ * Not every model supports structured outputs, and the model table cannot say
97
+ * which: litellm's `supports_response_schema` is set on models the API refuses a
98
+ * format for. So the API decides. The pair is only remembered as refused when the
99
+ * same request then succeeds without the format; a 400 for any other reason
100
+ * fails again, the format is put back, and the error goes to the caller's retry
101
+ * loop as it always did.
102
+ * @param params The request, mutated to drop the format once it is refused, so the
103
+ * caller's retries and a paused-turn resume do not send it again
104
+ * @param formatKey The key from outputFormatFor, when a format was attached
105
+ * @returns The API's response
106
+ */
107
+ private createConstrained;
79
108
  /**
80
109
  * Appends "here is what you said, now correct it" to a local messages array
81
110
  * for a retry.
@@ -19,6 +19,7 @@ const errors_1 = require("../../common/errors");
19
19
  const logger_1 = require("../../common/logger");
20
20
  const ai_debug_logger_1 = require("../ai-debug-logger");
21
21
  const attachment_type_1 = require("./attachment-type");
22
+ const anthropic_output_schema_1 = require("./anthropic-output-schema");
22
23
  let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.BaseAiService {
23
24
  static { AnthropicAiService_1 = this; }
24
25
  anthropic;
@@ -322,10 +323,20 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
322
323
  createParams.thinking = { type: 'disabled' };
323
324
  createParams.temperature = 0;
324
325
  }
326
+ // Enforce the schema while the reply is generated, where the API can (see
327
+ // anthropic-output-schema.ts). The prompt keeps its copy of the schema: its
328
+ // descriptions still tell the model what each field is for.
329
+ const format = this.outputFormatFor(agent, jsonSchema);
330
+ if (format) {
331
+ createParams.output_config = {
332
+ ...(createParams.output_config ?? {}),
333
+ format: { type: 'json_schema', schema: format.schema },
334
+ };
335
+ }
325
336
  this.debugLogRequest(agent.agentName, createParams);
326
337
  for (let attempt = 1; attempt <= maxRetries; attempt++) {
327
338
  try {
328
- let response = await this.anthropic.messages.create(createParams);
339
+ let response = await this.createConstrained(createParams, format?.key);
329
340
  if (response.usage) {
330
341
  this.computeMessageCost(agent, response.usage);
331
342
  }
@@ -434,6 +445,71 @@ let AnthropicAiService = class AnthropicAiService extends base_ai_service_1.Base
434
445
  // If we get here, all retries failed
435
446
  throw new Error(`Failed to get valid response after ${maxRetries} attempts. Last error: ${lastError?.message || 'Unknown error'}`);
436
447
  }
448
+ /**
449
+ * Model and schema pairs the API refused a format for. Later calls with the same
450
+ * pair go out on the prompt contract alone rather than failing first every time.
451
+ * Process-lifetime: a model that gains support is picked up on restart.
452
+ */
453
+ static unconstrained = new Set();
454
+ /**
455
+ * The schema to enforce on this call, or null to rely on the prompt contract.
456
+ * @param agent The agent being prompted
457
+ * @param jsonSchema The response schema, if the call has one
458
+ * @returns The converted schema and the key it is remembered under, or null
459
+ */
460
+ outputFormatFor(agent, jsonSchema) {
461
+ if (!jsonSchema)
462
+ return null;
463
+ // A web search answer carries citations, and structured outputs refuse citations.
464
+ if (agent.allowSearch)
465
+ return null;
466
+ const schema = (0, anthropic_output_schema_1.toAnthropicOutputSchema)(jsonSchema);
467
+ if (!schema)
468
+ return null;
469
+ const key = `${agent.modelName}|${JSON.stringify(schema)}`;
470
+ return AnthropicAiService_1.unconstrained.has(key) ? null : { schema, key };
471
+ }
472
+ /**
473
+ * Sends a request, and when the API refuses its output format, sends it again
474
+ * without one.
475
+ *
476
+ * Not every model supports structured outputs, and the model table cannot say
477
+ * which: litellm's `supports_response_schema` is set on models the API refuses a
478
+ * format for. So the API decides. The pair is only remembered as refused when the
479
+ * same request then succeeds without the format; a 400 for any other reason
480
+ * fails again, the format is put back, and the error goes to the caller's retry
481
+ * loop as it always did.
482
+ * @param params The request, mutated to drop the format once it is refused, so the
483
+ * caller's retries and a paused-turn resume do not send it again
484
+ * @param formatKey The key from outputFormatFor, when a format was attached
485
+ * @returns The API's response
486
+ */
487
+ async createConstrained(params, formatKey) {
488
+ try {
489
+ return await this.anthropic.messages.create(params);
490
+ }
491
+ catch (error) {
492
+ const config = params.output_config;
493
+ if (!formatKey || error?.status !== 400 || !config?.format)
494
+ throw error;
495
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
496
+ const { format: _format, ...rest } = config;
497
+ if (Object.keys(rest).length)
498
+ params.output_config = rest;
499
+ else
500
+ delete params.output_config;
501
+ try {
502
+ const response = await this.anthropic.messages.create(params);
503
+ AnthropicAiService_1.unconstrained.add(formatKey);
504
+ logger_1.logger.warn(`Structured output refused for ${params.model}; this schema goes out unconstrained from now on: ${error.message}`);
505
+ return response;
506
+ }
507
+ catch (second) {
508
+ params.output_config = config;
509
+ throw second;
510
+ }
511
+ }
512
+ }
437
513
  /**
438
514
  * Appends "here is what you said, now correct it" to a local messages array
439
515
  * for a retry.
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Drawing a chart as SVG, from a spec {@link validateChart} has passed.
3
+ *
4
+ * A pure function with no dependencies and no I/O: the same spec gives the same
5
+ * markup on a server printing a PDF and on a client showing a viewer, and nothing
6
+ * in it fetches anything. Every piece of text is escaped, since categories and
7
+ * names come from a model.
8
+ *
9
+ * The rules a reader relies on are kept: a column's length is its value, so
10
+ * columns and bars start at zero; a line chart fits its value axis to the data
11
+ * unless asked to start at zero, because a trend that never nears zero would
12
+ * otherwise be a flat line; axis ticks are round numbers.
13
+ */
14
+ import { ChartSpec, ChartValueFormat } from './chart.types';
15
+ /**
16
+ * A value as the reader sees it. `compact` shortens large numbers for an axis
17
+ * (950K, 1.2M); labels on the data use the full figure.
18
+ */
19
+ export declare function formatChartValue(value: number, format?: ChartValueFormat, compact?: boolean, compactDigits?: number): string;
20
+ /**
21
+ * The chart as a standalone SVG document.
22
+ * @param spec A spec that {@link validateChart} returned
23
+ */
24
+ export declare function renderChartSvg(spec: ChartSpec): string;
@@ -0,0 +1,415 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatChartValue = formatChartValue;
4
+ exports.renderChartSvg = renderChartSvg;
5
+ const WIDTH = 720;
6
+ const HEIGHT = 400;
7
+ const FONT = 'Helvetica, Arial, sans-serif';
8
+ const TEXT = '#1f2937';
9
+ const MUTED = '#4b5563';
10
+ const GRID = '#e5e7eb';
11
+ const AXIS = '#9ca3af';
12
+ const TITLE = '#1d345d';
13
+ /** Distinct at a glance and in print; navy first, to match the reports around it. */
14
+ const PALETTE = [
15
+ '#1d345d', '#e07b39', '#2a9d8f', '#c9a227', '#b83b5e', '#6c5b9e',
16
+ '#4a90c2', '#7f8c8d', '#8fb339', '#d48a8a', '#3d5a80', '#a0522d',
17
+ ];
18
+ /** Value labels are written on the chart only when there are few enough to read. */
19
+ const MAX_LABELLED_POINTS = 12;
20
+ const esc = (text) => String(text ?? '')
21
+ .replace(/&/g, '&amp;')
22
+ .replace(/</g, '&lt;')
23
+ .replace(/>/g, '&gt;')
24
+ .replace(/"/g, '&quot;');
25
+ /** One decimal is plenty for coordinates and keeps the markup small. */
26
+ const r = (n) => Math.round(n * 10) / 10;
27
+ /** A rough width for 12px text, enough to lay labels out without measuring. */
28
+ const textWidth = (text, size = 12) => text.length * size * 0.55;
29
+ function fit(text, maxWidth, size = 12) {
30
+ if (textWidth(text, size) <= maxWidth)
31
+ return text;
32
+ const keep = Math.max(1, Math.floor(maxWidth / (size * 0.55)) - 1);
33
+ return `${text.slice(0, keep).trimEnd()}…`;
34
+ }
35
+ /**
36
+ * A value as the reader sees it. `compact` shortens large numbers for an axis
37
+ * (950K, 1.2M); labels on the data use the full figure.
38
+ */
39
+ function formatChartValue(value, format = 'number', compact = false, compactDigits = 1) {
40
+ const abs = Math.abs(value);
41
+ const digits = abs >= 100 ? 0 : abs >= 1 ? 1 : 2;
42
+ const plain = (n) => compact && n >= 10_000
43
+ ? new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: compactDigits }).format(n)
44
+ : n.toLocaleString('en-US', { maximumFractionDigits: digits });
45
+ if (format === 'percent')
46
+ return `${value < 0 ? '-' : ''}${plain(abs)}%`;
47
+ if (format === 'currency')
48
+ return `${value < 0 ? '-' : ''}$${plain(abs)}`;
49
+ return `${value < 0 ? '-' : ''}${plain(abs)}`;
50
+ }
51
+ /**
52
+ * Axis labels, compact (950K, 1.02M) with the fewest decimals that keep every tick
53
+ * distinct — one decimal alone writes 1.00M, 1.02M and 1.04M all as "1M".
54
+ */
55
+ function axisLabels(values, format) {
56
+ for (let digits = 1; digits <= 3; digits++) {
57
+ const labels = values.map((v) => formatChartValue(v, format, true, digits));
58
+ if (new Set(labels).size === labels.length)
59
+ return labels;
60
+ }
61
+ return values.map((v) => formatChartValue(v, format));
62
+ }
63
+ /** Round axis ticks spanning [min, max]: 1, 2 or 5 × 10ⁿ apart. */
64
+ function niceScale(min, max, targetTicks = 6) {
65
+ if (min === max) {
66
+ const pad = min === 0 ? 1 : Math.abs(min) * 0.1;
67
+ min -= pad;
68
+ max += pad;
69
+ }
70
+ const rough = (max - min) / Math.max(1, targetTicks - 1);
71
+ const power = Math.pow(10, Math.floor(Math.log10(rough)));
72
+ const fraction = rough / power;
73
+ const step = (fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10) * power;
74
+ return { min: Math.floor(min / step) * step, max: Math.ceil(max / step) * step, step };
75
+ }
76
+ function ticks(scale) {
77
+ const out = [];
78
+ // Counted rather than accumulated, so floating point never drops the last tick.
79
+ const count = Math.round((scale.max - scale.min) / scale.step);
80
+ for (let i = 0; i <= count; i++)
81
+ out.push(scale.min + i * scale.step);
82
+ return out;
83
+ }
84
+ function color(index) {
85
+ return PALETTE[index % PALETTE.length];
86
+ }
87
+ /** The legend, wrapped into rows across the width. @returns Its markup and height. */
88
+ function legend(items, top, width) {
89
+ if (items.length === 0)
90
+ return { svg: '', height: 0 };
91
+ const rows = [[]];
92
+ let rowWidth = 0;
93
+ for (const item of items) {
94
+ const name = fit(item.name, 220);
95
+ const itemWidth = 18 + textWidth(name) + 18;
96
+ if (rowWidth + itemWidth > width - 40 && rows[rows.length - 1].length) {
97
+ rows.push([]);
98
+ rowWidth = 0;
99
+ }
100
+ rows[rows.length - 1].push({ ...item, name, width: itemWidth });
101
+ rowWidth += itemWidth;
102
+ }
103
+ let svg = '';
104
+ rows.forEach((row, index) => {
105
+ const total = row.reduce((sum, item) => sum + item.width, 0);
106
+ let x = (width - total) / 2;
107
+ const y = top + index * 18;
108
+ for (const item of row) {
109
+ svg += `<rect x="${r(x)}" y="${r(y)}" width="12" height="12" rx="2" fill="${item.color}"/>`;
110
+ svg += `<text x="${r(x + 18)}" y="${r(y + 10)}" font-size="12" fill="${TEXT}">${esc(item.name)}</text>`;
111
+ x += item.width;
112
+ }
113
+ });
114
+ return { svg, height: rows.length * 18 };
115
+ }
116
+ /** The title, wrapped onto a second line when it is long. @returns Its markup and height. */
117
+ function heading(title, width) {
118
+ if (!title)
119
+ return { svg: '', height: 0 };
120
+ const perLine = Math.floor((width - 40) / (15 * 0.55));
121
+ const lines = [];
122
+ let line = '';
123
+ for (const word of title.split(/\s+/)) {
124
+ if (line && (line + ' ' + word).length > perLine) {
125
+ lines.push(line);
126
+ line = word;
127
+ }
128
+ else {
129
+ line = line ? `${line} ${word}` : word;
130
+ }
131
+ }
132
+ if (line)
133
+ lines.push(line);
134
+ const shown = lines.slice(0, 2);
135
+ const svg = shown
136
+ .map((text, index) => `<text x="${width / 2}" y="${24 + index * 19}" text-anchor="middle" font-size="15" font-weight="bold" fill="${TITLE}">${esc(text)}</text>`)
137
+ .join('');
138
+ return { svg, height: shown.length * 19 + 12 };
139
+ }
140
+ function open(spec, width, height) {
141
+ const label = esc(spec.title || 'Chart');
142
+ return (`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" ` +
143
+ `font-family="${FONT}" role="img" aria-label="${label}"><title>${label}</title>` +
144
+ `<rect width="${width}" height="${height}" fill="#ffffff"/>`);
145
+ }
146
+ /**
147
+ * The chart as a standalone SVG document.
148
+ * @param spec A spec that {@link validateChart} returned
149
+ */
150
+ function renderChartSvg(spec) {
151
+ switch (spec.type) {
152
+ case 'pie':
153
+ return pieSvg(spec);
154
+ case 'bar':
155
+ return barSvg(spec);
156
+ default:
157
+ return verticalSvg(spec);
158
+ }
159
+ }
160
+ /** Line, column and stacked column: categories along the bottom, values up the side. */
161
+ function verticalSvg(spec) {
162
+ const format = spec.format ?? 'number';
163
+ const values = spec.series.flatMap((s) => s.values).filter((v) => v !== null);
164
+ let low;
165
+ let high;
166
+ if (spec.type === 'stacked-column') {
167
+ const totals = spec.categories.map((_, i) => spec.series.reduce((sum, s) => sum + (s.values[i] ?? 0), 0));
168
+ low = 0;
169
+ high = Math.max(...totals, 0);
170
+ }
171
+ else if (spec.type === 'line' && !spec.startAtZero) {
172
+ low = Math.min(...values);
173
+ high = Math.max(...values);
174
+ // A little room above and below, so no point sits on the frame — but never
175
+ // across zero, which would put a negative tick under a series that has none.
176
+ const pad = (high - low) * 0.08;
177
+ low = low >= 0 ? Math.max(0, low - pad) : low - pad;
178
+ high = high <= 0 ? Math.min(0, high + pad) : high + pad;
179
+ }
180
+ else {
181
+ low = Math.min(0, ...values);
182
+ high = Math.max(0, ...values);
183
+ }
184
+ const scale = niceScale(low, high);
185
+ const tickValues = ticks(scale);
186
+ const head = heading(spec.title, WIDTH);
187
+ const showLegend = spec.series.length > 1;
188
+ const key = legend(showLegend ? spec.series.map((s, i) => ({ name: s.name, color: color(i) })) : [], head.height + 8, WIDTH);
189
+ const tickLabels = axisLabels(tickValues, format);
190
+ const left = 16 + (spec.yLabel ? 20 : 0) + Math.max(...tickLabels.map((t) => textWidth(t))) + 8;
191
+ const right = WIDTH - 16;
192
+ const plotWidth = right - left;
193
+ const n = spec.categories.length;
194
+ const band = plotWidth / n;
195
+ // Category labels lie flat when they fit their band, and slant when they do not.
196
+ const widest = Math.max(...spec.categories.map((c) => textWidth(c)));
197
+ const slanted = widest > band - 6;
198
+ const labelEvery = slanted ? Math.max(1, Math.ceil(n / Math.floor(plotWidth / 16))) : 1;
199
+ const slantDepth = slanted ? Math.min(widest, 130) * 0.64 + 8 : 0;
200
+ const bottomPad = 12 + (slanted ? slantDepth : 18) + (spec.xLabel ? 20 : 0);
201
+ const top = head.height + key.height + (key.height ? 18 : 10);
202
+ const height = Math.max(HEIGHT, top + 220 + bottomPad);
203
+ const bottom = height - bottomPad;
204
+ const plotHeight = bottom - top;
205
+ const y = (v) => bottom - ((v - scale.min) / (scale.max - scale.min)) * plotHeight;
206
+ const cx = (i) => left + band * (i + 0.5);
207
+ let svg = open(spec, WIDTH, height) + head.svg + key.svg;
208
+ for (const [index, tick] of tickValues.entries()) {
209
+ const ty = r(y(tick));
210
+ const stroke = tick === 0 && scale.min < 0 ? AXIS : GRID;
211
+ svg += `<line x1="${r(left)}" y1="${ty}" x2="${right}" y2="${ty}" stroke="${stroke}" stroke-width="1"/>`;
212
+ svg += `<text x="${r(left - 8)}" y="${r(ty + 4)}" text-anchor="end" font-size="12" fill="${MUTED}">${esc(tickLabels[index])}</text>`;
213
+ }
214
+ svg += `<line x1="${r(left)}" y1="${r(bottom)}" x2="${right}" y2="${r(bottom)}" stroke="${AXIS}" stroke-width="1"/>`;
215
+ for (const [i, category] of spec.categories.entries()) {
216
+ if (i % labelEvery !== 0)
217
+ continue;
218
+ const text = esc(slanted ? fit(category, 130) : category);
219
+ svg += slanted
220
+ ? `<text transform="translate(${r(cx(i))},${r(bottom + 14)}) rotate(-40)" text-anchor="end" font-size="12" fill="${TEXT}">${text}</text>`
221
+ : `<text x="${r(cx(i))}" y="${r(bottom + 18)}" text-anchor="middle" font-size="12" fill="${TEXT}">${text}</text>`;
222
+ }
223
+ if (spec.xLabel) {
224
+ svg += `<text x="${r(left + plotWidth / 2)}" y="${r(height - 10)}" text-anchor="middle" font-size="12" fill="${MUTED}">${esc(spec.xLabel)}</text>`;
225
+ }
226
+ if (spec.yLabel) {
227
+ svg += `<text transform="translate(18,${r(top + plotHeight / 2)}) rotate(-90)" text-anchor="middle" font-size="12" fill="${MUTED}">${esc(spec.yLabel)}</text>`;
228
+ }
229
+ const labelled = n <= MAX_LABELLED_POINTS;
230
+ const dataLabel = (x, yy, v, room, anchor = 'middle') => {
231
+ const full = formatChartValue(v, format);
232
+ const text = textWidth(full, 11) <= room ? full : formatChartValue(v, format, true);
233
+ return `<text x="${r(x)}" y="${r(yy)}" text-anchor="${anchor}" font-size="11" fill="${TEXT}">${esc(text)}</text>`;
234
+ };
235
+ if (spec.type === 'line') {
236
+ for (const [s, series] of spec.series.entries()) {
237
+ let path = '';
238
+ let drawing = false;
239
+ for (const [i, v] of series.values.entries()) {
240
+ if (v === null) {
241
+ drawing = false;
242
+ continue;
243
+ }
244
+ path += `${drawing ? 'L' : 'M'}${r(cx(i))},${r(y(v))}`;
245
+ drawing = true;
246
+ }
247
+ svg += `<path d="${path}" fill="none" stroke="${color(s)}" stroke-width="2.5" stroke-linejoin="round" stroke-linecap="round"/>`;
248
+ if (n <= 30) {
249
+ for (const [i, v] of series.values.entries()) {
250
+ if (v === null)
251
+ continue;
252
+ svg += `<circle cx="${r(cx(i))}" cy="${r(y(v))}" r="3.5" fill="#ffffff" stroke="${color(s)}" stroke-width="2"/>`;
253
+ }
254
+ }
255
+ if (labelled && spec.series.length === 1) {
256
+ for (const [i, v] of series.values.entries()) {
257
+ if (v === null)
258
+ continue;
259
+ // Kept off the line: below a low point, where the line comes down
260
+ // into it from both sides; above a high one; and on a slope, above
261
+ // and to the side away from the neighbour the line climbs toward.
262
+ const before = series.values[i - 1] ?? null;
263
+ const after = series.values[i + 1] ?? null;
264
+ const low = (before === null || before > v) && (after === null || after > v);
265
+ const high = (before === null || before <= v) && (after === null || after <= v);
266
+ if (low) {
267
+ svg += dataLabel(cx(i), y(v) + 20, v, band - 4);
268
+ }
269
+ else if (high) {
270
+ svg += dataLabel(cx(i), y(v) - 10, v, band - 4);
271
+ }
272
+ else if (after !== null && after > v) {
273
+ svg += dataLabel(cx(i) - 6, y(v) - 8, v, band - 4, 'end');
274
+ }
275
+ else {
276
+ svg += dataLabel(cx(i) + 6, y(v) - 8, v, band - 4, 'start');
277
+ }
278
+ }
279
+ }
280
+ }
281
+ }
282
+ else if (spec.type === 'column') {
283
+ const group = band * 0.72;
284
+ const barWidth = group / spec.series.length;
285
+ const zero = y(Math.max(scale.min, Math.min(0, scale.max)));
286
+ for (const [s, series] of spec.series.entries()) {
287
+ for (const [i, v] of series.values.entries()) {
288
+ if (v === null)
289
+ continue;
290
+ const x = cx(i) - group / 2 + s * barWidth;
291
+ const yy = y(v);
292
+ svg += `<rect x="${r(x + 1)}" y="${r(Math.min(yy, zero))}" width="${r(Math.max(1, barWidth - 2))}" height="${r(Math.abs(zero - yy))}" fill="${color(s)}"/>`;
293
+ if (labelled && spec.series.length === 1) {
294
+ svg += dataLabel(x + barWidth / 2, v >= 0 ? yy - 5 : yy + 14, v, band - 4);
295
+ }
296
+ }
297
+ }
298
+ }
299
+ else {
300
+ // stacked-column
301
+ const barWidth = band * 0.6;
302
+ for (const [i] of spec.categories.entries()) {
303
+ let base = 0;
304
+ for (const [s, series] of spec.series.entries()) {
305
+ const v = series.values[i];
306
+ if (v === null || v === 0)
307
+ continue;
308
+ const y0 = y(base);
309
+ const y1 = y(base + v);
310
+ svg += `<rect x="${r(cx(i) - barWidth / 2)}" y="${r(y1)}" width="${r(barWidth)}" height="${r(y0 - y1)}" fill="${color(s)}" stroke="#ffffff" stroke-width="1"/>`;
311
+ base += v;
312
+ }
313
+ if (labelled && base > 0)
314
+ svg += dataLabel(cx(i), y(base) - 5, base, band - 4);
315
+ }
316
+ }
317
+ return `${svg}</svg>`;
318
+ }
319
+ /** Bars running across: categories down the side, for long names or many of them. */
320
+ function barSvg(spec) {
321
+ const format = spec.format ?? 'number';
322
+ const values = spec.series.flatMap((s) => s.values).filter((v) => v !== null);
323
+ const scale = niceScale(Math.min(0, ...values), Math.max(0, ...values));
324
+ const tickValues = ticks(scale);
325
+ const n = spec.categories.length;
326
+ const perSeries = spec.series.length > 1 ? 14 : 22;
327
+ const rowHeight = perSeries * spec.series.length + 10;
328
+ const head = heading(spec.title, WIDTH);
329
+ const key = legend(spec.series.length > 1 ? spec.series.map((s, i) => ({ name: s.name, color: color(i) })) : [], head.height + 8, WIDTH);
330
+ const top = head.height + key.height + (key.height ? 18 : 10);
331
+ const labelWidth = Math.min(220, Math.max(...spec.categories.map((c) => textWidth(c))));
332
+ const left = 16 + labelWidth + 10;
333
+ const valueRoom = n <= 30 ? 70 : 0;
334
+ const right = WIDTH - 16 - valueRoom;
335
+ const bottom = top + n * rowHeight;
336
+ const height = bottom + 30 + (spec.xLabel ? 20 : 0);
337
+ const x = (v) => left + ((v - scale.min) / (scale.max - scale.min)) * (right - left);
338
+ const zero = x(Math.max(scale.min, Math.min(0, scale.max)));
339
+ let svg = open(spec, WIDTH, height) + head.svg + key.svg;
340
+ const tickLabels = axisLabels(tickValues, format);
341
+ for (const [index, tick] of tickValues.entries()) {
342
+ const tx = r(x(tick));
343
+ svg += `<line x1="${tx}" y1="${r(top)}" x2="${tx}" y2="${r(bottom)}" stroke="${tick === 0 ? AXIS : GRID}" stroke-width="1"/>`;
344
+ svg += `<text x="${tx}" y="${r(bottom + 18)}" text-anchor="middle" font-size="12" fill="${MUTED}">${esc(tickLabels[index])}</text>`;
345
+ }
346
+ for (const [i, category] of spec.categories.entries()) {
347
+ const rowTop = top + i * rowHeight + 5;
348
+ svg += `<text x="${r(left - 10)}" y="${r(rowTop + (rowHeight - 10) / 2 + 4)}" text-anchor="end" font-size="12" fill="${TEXT}">${esc(fit(category, labelWidth))}</text>`;
349
+ for (const [s, series] of spec.series.entries()) {
350
+ const v = series.values[i];
351
+ if (v === null)
352
+ continue;
353
+ const by = rowTop + s * perSeries;
354
+ const bx = x(v);
355
+ svg += `<rect x="${r(Math.min(bx, zero))}" y="${r(by)}" width="${r(Math.max(1, Math.abs(bx - zero)))}" height="${perSeries - 2}" fill="${color(s)}"/>`;
356
+ if (valueRoom) {
357
+ const anchor = v >= 0 ? 'start' : 'end';
358
+ const lx = v >= 0 ? Math.max(bx, zero) + 5 : Math.min(bx, zero) - 5;
359
+ svg += `<text x="${r(lx)}" y="${r(by + perSeries / 2 + 3)}" text-anchor="${anchor}" font-size="11" fill="${TEXT}">${esc(formatChartValue(v, format))}</text>`;
360
+ }
361
+ }
362
+ }
363
+ if (spec.xLabel) {
364
+ svg += `<text x="${r((left + right) / 2)}" y="${r(height - 8)}" text-anchor="middle" font-size="12" fill="${MUTED}">${esc(spec.xLabel)}</text>`;
365
+ }
366
+ return `${svg}</svg>`;
367
+ }
368
+ /** A pie, with the legend beside it naming each slice's value and share. */
369
+ function pieSvg(spec) {
370
+ const format = spec.format ?? 'number';
371
+ const values = spec.series[0].values.map((v) => (v !== null && v > 0 ? v : 0));
372
+ const total = values.reduce((sum, v) => sum + v, 0);
373
+ const head = heading(spec.title, WIDTH);
374
+ const top = head.height + 10;
375
+ const height = Math.max(HEIGHT, top + 40 + spec.categories.length * 22);
376
+ const radius = Math.min(150, (height - top - 30) / 2);
377
+ const cx = 40 + radius;
378
+ const cy = top + 10 + radius;
379
+ let svg = open(spec, WIDTH, height) + head.svg;
380
+ let angle = -Math.PI / 2;
381
+ const slices = values.map((v, i) => ({ v, i })).filter(({ v }) => v > 0);
382
+ for (const { v, i } of slices) {
383
+ const sweep = (v / total) * Math.PI * 2;
384
+ if (slices.length === 1) {
385
+ svg += `<circle cx="${r(cx)}" cy="${r(cy)}" r="${r(radius)}" fill="${color(i)}"/>`;
386
+ }
387
+ else {
388
+ const end = angle + sweep;
389
+ const x0 = cx + radius * Math.cos(angle);
390
+ const y0 = cy + radius * Math.sin(angle);
391
+ const x1 = cx + radius * Math.cos(end);
392
+ const y1 = cy + radius * Math.sin(end);
393
+ svg += `<path d="M${r(cx)},${r(cy)} L${r(x0)},${r(y0)} A${r(radius)},${r(radius)} 0 ${sweep > Math.PI ? 1 : 0} 1 ${r(x1)},${r(y1)} Z" fill="${color(i)}" stroke="#ffffff" stroke-width="1.5"/>`;
394
+ }
395
+ const share = v / total;
396
+ if (share >= 0.05) {
397
+ const mid = angle + sweep / 2;
398
+ const lx = cx + radius * 0.62 * Math.cos(mid);
399
+ const ly = cy + radius * 0.62 * Math.sin(mid);
400
+ svg += `<text x="${r(lx)}" y="${r(ly + 4)}" text-anchor="middle" font-size="12" font-weight="bold" fill="#ffffff">${Math.round(share * 100)}%</text>`;
401
+ }
402
+ angle += sweep;
403
+ }
404
+ const legendX = cx + radius + 40;
405
+ const legendTop = cy - (spec.categories.length * 22) / 2;
406
+ for (const [i, category] of spec.categories.entries()) {
407
+ const v = spec.series[0].values[i];
408
+ const ly = legendTop + i * 22;
409
+ const share = v !== null && v > 0 ? ` (${((v / total) * 100).toFixed(1)}%)` : '';
410
+ const text = `${fit(category, 200)} — ${v === null ? 'no data' : formatChartValue(v, format)}${share}`;
411
+ svg += `<rect x="${r(legendX)}" y="${r(ly)}" width="12" height="12" rx="2" fill="${color(i)}"/>`;
412
+ svg += `<text x="${r(legendX + 18)}" y="${r(ly + 10)}" font-size="12" fill="${TEXT}">${esc(text)}</text>`;
413
+ }
414
+ return `${svg}</svg>`;
415
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Checking a chart an agent described, before anything is drawn.
3
+ *
4
+ * The answer is written for the agent: each refusal says what was wrong and what
5
+ * would be right, so its next attempt is a correction rather than another guess.
6
+ * A chart that passes is normalized — trimmed, defaulted, numbers that arrived as
7
+ * strings read as numbers — so a renderer never has to be forgiving.
8
+ */
9
+ import { ChartSpec } from './chart.types';
10
+ /**
11
+ * Each branch names the other's field as absent: this project compiles without
12
+ * strictNullChecks, which turns off narrowing on `ok`, and a caller reads
13
+ * `error` after `if (!checked.ok)`.
14
+ */
15
+ export type ChartValidation = {
16
+ ok: true;
17
+ spec: ChartSpec;
18
+ error?: undefined;
19
+ } | {
20
+ ok: false;
21
+ error: string;
22
+ spec?: undefined;
23
+ };
24
+ /**
25
+ * @param raw What the agent sent, already parsed from JSON
26
+ * @returns The normalized spec, or what is wrong with it
27
+ */
28
+ export declare function validateChart(raw: unknown): ChartValidation;
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateChart = validateChart;
4
+ /**
5
+ * Checking a chart an agent described, before anything is drawn.
6
+ *
7
+ * The answer is written for the agent: each refusal says what was wrong and what
8
+ * would be right, so its next attempt is a correction rather than another guess.
9
+ * A chart that passes is normalized — trimmed, defaulted, numbers that arrived as
10
+ * strings read as numbers — so a renderer never has to be forgiving.
11
+ */
12
+ const chart_types_1 = require("./chart.types");
13
+ /** A short label: trimmed, and cut where a chart could not show the rest anyway. */
14
+ function label(value, max) {
15
+ const text = value === undefined || value === null ? '' : String(value).trim();
16
+ return text.length <= max ? text : `${text.slice(0, max - 1).trimEnd()}…`;
17
+ }
18
+ /** A value as a number: a number, a numeric string ("1,234", "$5.6"), or null for a gap. */
19
+ function value(raw) {
20
+ if (raw === null || raw === '')
21
+ return null;
22
+ if (typeof raw === 'number')
23
+ return Number.isFinite(raw) ? raw : undefined;
24
+ if (typeof raw === 'string') {
25
+ const parsed = Number(raw.replace(/[$,%\s]/g, ''));
26
+ return Number.isFinite(parsed) ? parsed : undefined;
27
+ }
28
+ return undefined;
29
+ }
30
+ function fail(error) {
31
+ return { ok: false, error };
32
+ }
33
+ /**
34
+ * @param raw What the agent sent, already parsed from JSON
35
+ * @returns The normalized spec, or what is wrong with it
36
+ */
37
+ function validateChart(raw) {
38
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
39
+ return fail('A chart is a JSON object: {"type": "line", "categories": [...], "series": [{"name": ..., "values": [...]}]}.');
40
+ }
41
+ const input = raw;
42
+ const type = String(input.type ?? '').trim().toLowerCase();
43
+ if (!chart_types_1.CHART_TYPES.includes(type)) {
44
+ return fail(`"type" must be one of: ${chart_types_1.CHART_TYPES.join(', ')}.`);
45
+ }
46
+ if (!Array.isArray(input.categories) || input.categories.length === 0) {
47
+ return fail('"categories" must be a list of labels, one for each point along the axis (or each pie slice).');
48
+ }
49
+ if (input.categories.length > chart_types_1.MAX_CHART_CATEGORIES) {
50
+ return fail(`${input.categories.length} categories are too many to read; at most ${chart_types_1.MAX_CHART_CATEGORIES}. ` +
51
+ 'Group the data (by year rather than month, say) or chart the top ones.');
52
+ }
53
+ const categories = input.categories.map((category) => label(category, 60));
54
+ if (categories.some((category) => !category)) {
55
+ return fail('Every category needs a label; one is empty.');
56
+ }
57
+ const rawSeries = Array.isArray(input.series)
58
+ ? input.series
59
+ : input.series && typeof input.series === 'object'
60
+ ? [input.series]
61
+ : [];
62
+ if (rawSeries.length === 0) {
63
+ return fail('"series" must be a list of {"name": ..., "values": [...]}, with one value per category.');
64
+ }
65
+ if (rawSeries.length > chart_types_1.MAX_CHART_SERIES) {
66
+ return fail(`${rawSeries.length} series are too many for one chart; at most ${chart_types_1.MAX_CHART_SERIES}.`);
67
+ }
68
+ const series = [];
69
+ for (const [index, entry] of rawSeries.entries()) {
70
+ const item = entry;
71
+ const name = label(item?.name, 60) || (rawSeries.length === 1 ? '' : `Series ${index + 1}`);
72
+ if (!Array.isArray(item?.values)) {
73
+ return fail(`Series ${name ? `"${name}"` : index + 1} needs "values": a list with one number per category.`);
74
+ }
75
+ if (item.values.length !== categories.length) {
76
+ return fail(`Series ${name ? `"${name}"` : index + 1} has ${item.values.length} value(s) but there are ` +
77
+ `${categories.length} categories. Give exactly one value per category, in order — null where there is no data.`);
78
+ }
79
+ const values = [];
80
+ for (const [position, rawValue] of item.values.entries()) {
81
+ const parsed = value(rawValue);
82
+ if (parsed === undefined) {
83
+ return fail(`Series ${name ? `"${name}"` : index + 1}, "${categories[position]}": ${JSON.stringify(rawValue)} ` +
84
+ 'is not a number. Use a plain number, or null where there is no data.');
85
+ }
86
+ values.push(parsed);
87
+ }
88
+ if (values.every((v) => v === null)) {
89
+ return fail(`Series ${name ? `"${name}"` : index + 1} has no values at all.`);
90
+ }
91
+ series.push({ name, values });
92
+ }
93
+ if (type === 'pie') {
94
+ if (series.length !== 1) {
95
+ return fail('A pie shows one whole: give exactly one series. To compare several, use "column".');
96
+ }
97
+ if (categories.length > chart_types_1.MAX_PIE_SLICES) {
98
+ return fail(`${categories.length} slices are too many for a pie; at most ${chart_types_1.MAX_PIE_SLICES}. ` +
99
+ 'Combine the smallest into "Other", or use "bar".');
100
+ }
101
+ if (series[0].values.some((v) => v !== null && v < 0)) {
102
+ return fail('A pie cannot show a negative value. Use "column" or "bar".');
103
+ }
104
+ if (!series[0].values.some((v) => v !== null && v > 0)) {
105
+ return fail('A pie needs at least one value above zero.');
106
+ }
107
+ }
108
+ if (type === 'stacked-column' && series.some((s) => s.values.some((v) => v !== null && v < 0))) {
109
+ return fail('A stacked column cannot show a negative value. Use "column", which can.');
110
+ }
111
+ let format = 'number';
112
+ if (input.format !== undefined && input.format !== null && input.format !== '') {
113
+ format = String(input.format).trim().toLowerCase();
114
+ if (!chart_types_1.CHART_VALUE_FORMATS.includes(format)) {
115
+ return fail(`"format" must be one of: ${chart_types_1.CHART_VALUE_FORMATS.join(', ')}.`);
116
+ }
117
+ }
118
+ const spec = {
119
+ type,
120
+ ...(label(input.title, 120) ? { title: label(input.title, 120) } : {}),
121
+ categories,
122
+ series,
123
+ ...(label(input.xLabel, 60) ? { xLabel: label(input.xLabel, 60) } : {}),
124
+ ...(label(input.yLabel, 60) ? { yLabel: label(input.yLabel, 60) } : {}),
125
+ ...(format !== 'number' ? { format } : {}),
126
+ ...(type === 'line' && input.startAtZero === true ? { startAtZero: true } : {}),
127
+ };
128
+ return { ok: true, spec };
129
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * A chart, described as data.
3
+ *
4
+ * An agent asked for a graph has the numbers and no way to draw them, and an
5
+ * image model asked to draw one invents a plausible chart with numbers of its own.
6
+ * So an agent describes the chart in this small, fixed shape — what kind, the
7
+ * categories along the axis, the series of values — and Briyah draws it as SVG,
8
+ * exactly.
9
+ *
10
+ * Deliberately small rather than a general chart language: every field here is
11
+ * one a model fills in correctly from an example, and every chart it can express
12
+ * is one a business reader wants. Anything that needs more is a report a host
13
+ * builds itself.
14
+ */
15
+ /**
16
+ * - `line`: a trend over time — categories are periods, in order.
17
+ * - `column`: comparing categories side by side; several series group.
18
+ * - `bar`: `column` turned on its side, for long names or many categories.
19
+ * - `stacked-column`: parts of a whole across categories; totals on top.
20
+ * - `pie`: shares of one whole. One series, a few slices, no negatives.
21
+ */
22
+ export type ChartType = 'line' | 'column' | 'bar' | 'stacked-column' | 'pie';
23
+ export declare const CHART_TYPES: readonly ChartType[];
24
+ /** How values are written on the axis, the labels and the legend. */
25
+ export type ChartValueFormat = 'number' | 'currency' | 'percent';
26
+ export declare const CHART_VALUE_FORMATS: readonly ChartValueFormat[];
27
+ export interface ChartSeries {
28
+ /** What the series is, as the legend shows it. */
29
+ name: string;
30
+ /** One value per category, in the same order. `null` is a gap: no data there. */
31
+ values: (number | null)[];
32
+ }
33
+ export interface ChartSpec {
34
+ type: ChartType;
35
+ /** The chart's heading. */
36
+ title?: string;
37
+ /** The labels along the category axis — periods, names — in order. A pie's slices. */
38
+ categories: string[];
39
+ series: ChartSeries[];
40
+ /** What the category axis measures, e.g. "Quarter". */
41
+ xLabel?: string;
42
+ /** What the value axis measures, e.g. "Miles". */
43
+ yLabel?: string;
44
+ /** How values are written. Absent means `number`; `percent` takes 12.5 to mean 12.5%. */
45
+ format?: ChartValueFormat;
46
+ /**
47
+ * Whether a line chart's value axis starts at zero. Absent means it fits the
48
+ * data, which shows the movement in a series that never nears zero. Columns
49
+ * and bars always start at zero: a bar's length is its value.
50
+ */
51
+ startAtZero?: boolean;
52
+ }
53
+ /** The fence language a chart block is written with in markdown: ```chart */
54
+ export declare const CHART_BLOCK_LANGUAGE = "chart";
55
+ /** Most categories a chart takes. Past this a chart is unreadable; group the data first. */
56
+ export declare const MAX_CHART_CATEGORIES = 60;
57
+ /** Most series a chart takes. Past this the legend is a list nobody reads. */
58
+ export declare const MAX_CHART_SERIES = 8;
59
+ /** Most slices a pie takes. Past this the slices are slivers. */
60
+ export declare const MAX_PIE_SLICES = 12;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ /**
3
+ * A chart, described as data.
4
+ *
5
+ * An agent asked for a graph has the numbers and no way to draw them, and an
6
+ * image model asked to draw one invents a plausible chart with numbers of its own.
7
+ * So an agent describes the chart in this small, fixed shape — what kind, the
8
+ * categories along the axis, the series of values — and Briyah draws it as SVG,
9
+ * exactly.
10
+ *
11
+ * Deliberately small rather than a general chart language: every field here is
12
+ * one a model fills in correctly from an example, and every chart it can express
13
+ * is one a business reader wants. Anything that needs more is a report a host
14
+ * builds itself.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.MAX_PIE_SLICES = exports.MAX_CHART_SERIES = exports.MAX_CHART_CATEGORIES = exports.CHART_BLOCK_LANGUAGE = exports.CHART_VALUE_FORMATS = exports.CHART_TYPES = void 0;
18
+ exports.CHART_TYPES = ['line', 'column', 'bar', 'stacked-column', 'pie'];
19
+ exports.CHART_VALUE_FORMATS = ['number', 'currency', 'percent'];
20
+ /** The fence language a chart block is written with in markdown: ```chart */
21
+ exports.CHART_BLOCK_LANGUAGE = 'chart';
22
+ /** Most categories a chart takes. Past this a chart is unreadable; group the data first. */
23
+ exports.MAX_CHART_CATEGORIES = 60;
24
+ /** Most series a chart takes. Past this the legend is a list nobody reads. */
25
+ exports.MAX_CHART_SERIES = 8;
26
+ /** Most slices a pie takes. Past this the slices are slivers. */
27
+ exports.MAX_PIE_SLICES = 12;
@@ -30,6 +30,11 @@ export { DEFAULT_ROW_LIMIT, MAX_ROW_LIMIT } from '../data/data.types';
30
30
  export { registerDataSource, unregisterDataSource, listDataSources, listDatasets, } from '../data/data-registry';
31
31
  export { buildDataGuideMarkdown } from '../data/data-guide.builder';
32
32
  export { queryRows } from '../data/row-executor';
33
+ export type { ChartSpec, ChartSeries, ChartType, ChartValueFormat } from '../charts/chart.types';
34
+ export { CHART_BLOCK_LANGUAGE, CHART_TYPES } from '../charts/chart.types';
35
+ export { validateChart } from '../charts/chart-validation';
36
+ export type { ChartValidation } from '../charts/chart-validation';
37
+ export { renderChartSvg, formatChartValue } from '../charts/chart-svg';
33
38
  export { PackService } from '../packs/pack.service';
34
39
  export type { PackView } from '../packs/pack.service';
35
40
  export { PackInstantiationService } from '../packs/pack-instantiation.service';
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RoomMessage = exports.Room = exports.Agent = exports.PackInstantiationService = exports.PackService = exports.queryRows = exports.buildDataGuideMarkdown = exports.listDatasets = exports.listDataSources = exports.unregisterDataSource = exports.registerDataSource = exports.MAX_ROW_LIMIT = exports.DEFAULT_ROW_LIMIT = exports.NativeToolRegistry = 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.currentUsageTags = exports.runWithUsageTags = exports.MAX_ATTACHED_IMAGE_BYTES = exports.ATTACHMENT_IMAGE_TYPES = exports.isAttachmentImage = exports.detectAttachmentMimeType = exports.UnsupportedDocumentError = exports.convertLocalDocument = exports.detectDocumentType = exports.BriyahConfigService = exports.Briyah = void 0;
3
+ 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 = 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.currentUsageTags = exports.runWithUsageTags = exports.MAX_ATTACHED_IMAGE_BYTES = exports.ATTACHMENT_IMAGE_TYPES = exports.isAttachmentImage = exports.detectAttachmentMimeType = exports.UnsupportedDocumentError = exports.convertLocalDocument = exports.detectDocumentType = exports.BriyahConfigService = exports.Briyah = void 0;
4
+ exports.RoomMessage = exports.Room = exports.Agent = exports.PackInstantiationService = exports.PackService = void 0;
4
5
  // Main SDK exports
5
6
  var briyah_1 = require("./briyah");
6
7
  Object.defineProperty(exports, "Briyah", { enumerable: true, get: function () { return briyah_1.Briyah; } });
@@ -94,6 +95,14 @@ Object.defineProperty(exports, "buildDataGuideMarkdown", { enumerable: true, get
94
95
  // ordering semantics as every other host.
95
96
  var row_executor_1 = require("../data/row-executor");
96
97
  Object.defineProperty(exports, "queryRows", { enumerable: true, get: function () { return row_executor_1.queryRows; } });
98
+ var chart_types_1 = require("../charts/chart.types");
99
+ Object.defineProperty(exports, "CHART_BLOCK_LANGUAGE", { enumerable: true, get: function () { return chart_types_1.CHART_BLOCK_LANGUAGE; } });
100
+ Object.defineProperty(exports, "CHART_TYPES", { enumerable: true, get: function () { return chart_types_1.CHART_TYPES; } });
101
+ var chart_validation_1 = require("../charts/chart-validation");
102
+ Object.defineProperty(exports, "validateChart", { enumerable: true, get: function () { return chart_validation_1.validateChart; } });
103
+ var chart_svg_1 = require("../charts/chart-svg");
104
+ Object.defineProperty(exports, "renderChartSvg", { enumerable: true, get: function () { return chart_svg_1.renderChartSvg; } });
105
+ Object.defineProperty(exports, "formatChartValue", { enumerable: true, get: function () { return chart_svg_1.formatChartValue; } });
97
106
  // Packs: a domain's prompt folders, documents, tools and templates, installed for
98
107
  // everyone and enabled per user.
99
108
  //
@@ -0,0 +1,15 @@
1
+ import { NativeToolDefinition } from '../native-tool.types';
2
+ /**
3
+ * Turns numbers into a chart an application can draw exactly.
4
+ *
5
+ * The agent describes the chart as data; the tool checks it and hands back the
6
+ * ```chart block to put in a message or a document, where the host draws it with
7
+ * `renderChartSvg`. Checking here is the point: a chart written straight into a
8
+ * document with a typo would just fail to draw, and the agent would never know.
9
+ * Drawn once here too, so a spec that validates but cannot be drawn is caught in
10
+ * the same turn.
11
+ *
12
+ * Never an image model's job: asked for a chart, one draws a plausible picture
13
+ * with numbers of its own.
14
+ */
15
+ export declare const makeChartTool: NativeToolDefinition;
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.makeChartTool = void 0;
4
+ const coerce_1 = require("../shared/coerce");
5
+ const chart_validation_1 = require("../../charts/chart-validation");
6
+ const chart_svg_1 = require("../../charts/chart-svg");
7
+ const chart_types_1 = require("../../charts/chart.types");
8
+ const CHART_EXAMPLE = '{"type": "line", "title": "Fleet miles by quarter", "yLabel": "Miles", ' +
9
+ '"categories": ["2025 Q1", "2025 Q2", "2025 Q3"], ' +
10
+ '"series": [{"name": "Fleet miles", "values": [970269, 1007320, 962897]}]}';
11
+ /**
12
+ * The chart, in either form a model sends it: wrapped in `chart` — as the
13
+ * parameter declares — or as the arguments themselves, the way the example shows
14
+ * it. The same leniency as `query_data`'s, for the same reason.
15
+ */
16
+ function chartFromArgs(args) {
17
+ const wrapped = args?.chart;
18
+ if (wrapped !== undefined && wrapped !== null && wrapped !== '') {
19
+ return (0, coerce_1.jsonObject)(wrapped, 'chart', CHART_EXAMPLE);
20
+ }
21
+ if (args?.type !== undefined || args?.series !== undefined) {
22
+ const fields = {};
23
+ for (const [key, value] of Object.entries(args)) {
24
+ if (key !== 'chart')
25
+ fields[key] = (0, coerce_1.parsedIfJson)(value);
26
+ }
27
+ return fields;
28
+ }
29
+ throw new coerce_1.ArgumentError('chart', wrapped, 'a JSON object describing the chart', CHART_EXAMPLE);
30
+ }
31
+ /**
32
+ * Turns numbers into a chart an application can draw exactly.
33
+ *
34
+ * The agent describes the chart as data; the tool checks it and hands back the
35
+ * ```chart block to put in a message or a document, where the host draws it with
36
+ * `renderChartSvg`. Checking here is the point: a chart written straight into a
37
+ * document with a typo would just fail to draw, and the agent would never know.
38
+ * Drawn once here too, so a spec that validates but cannot be drawn is caught in
39
+ * the same turn.
40
+ *
41
+ * Never an image model's job: asked for a chart, one draws a plausible picture
42
+ * with numbers of its own.
43
+ */
44
+ exports.makeChartTool = {
45
+ name: 'make_chart',
46
+ description: 'Makes a chart — line, column, bar, stacked-column or pie — from numbers you already have ' +
47
+ '(read from a document, or returned by a query). Describe it as JSON: ' +
48
+ CHART_EXAMPLE +
49
+ '. One value per category in every series, in order; null where there is no data. ' +
50
+ 'Optional: "xLabel", "yLabel", "format" ("number", "currency" or "percent"), and for a ' +
51
+ 'line, "startAtZero": true. The result has a `block`: put it in your message or ' +
52
+ 'document exactly as given, on lines of its own, and the application draws the chart ' +
53
+ 'there. If the chart is refused, fix what the error names and try again.',
54
+ parameters: [
55
+ {
56
+ name: 'chart',
57
+ type: 'string',
58
+ description: 'The chart as a JSON object. Example: ' + CHART_EXAMPLE +
59
+ ' May be left out when its fields are sent as the arguments instead.',
60
+ required: false,
61
+ },
62
+ ],
63
+ async handler(args) {
64
+ const raw = chartFromArgs(args);
65
+ const checked = (0, chart_validation_1.validateChart)(raw);
66
+ if (!checked.ok) {
67
+ return {
68
+ ok: false,
69
+ summary: 'Chart refused',
70
+ error: checked.error,
71
+ types: [...chart_types_1.CHART_TYPES],
72
+ };
73
+ }
74
+ (0, chart_svg_1.renderChartSvg)(checked.spec);
75
+ const points = checked.spec.categories.length;
76
+ return {
77
+ ok: true,
78
+ summary: `Chart ready: ${checked.spec.title || `${checked.spec.type}, ${points} categories`}`,
79
+ block: `\`\`\`${chart_types_1.CHART_BLOCK_LANGUAGE}\n${JSON.stringify(checked.spec)}\n\`\`\``,
80
+ note: 'Put the block in your message or document exactly as given, on lines of its own.',
81
+ };
82
+ },
83
+ };
@@ -28,22 +28,12 @@ function queryFromArgs(args) {
28
28
  const fields = {};
29
29
  for (const [key, value] of Object.entries(args)) {
30
30
  if (key !== 'query')
31
- fields[key] = parsedIfJson(value);
31
+ fields[key] = (0, coerce_1.parsedIfJson)(value);
32
32
  }
33
33
  return fields;
34
34
  }
35
35
  throw new coerce_1.ArgumentError('query', wrapped, 'a JSON object naming a dataset', QUERY_EXAMPLE);
36
36
  }
37
- function parsedIfJson(value) {
38
- if (typeof value !== 'string' || !/^\s*[[{]/.test(value))
39
- return value;
40
- try {
41
- return JSON.parse(value);
42
- }
43
- catch {
44
- return value;
45
- }
46
- }
47
37
  /** Names every dataset, for an error that teaches rather than just refuses. */
48
38
  function datasetNames() {
49
39
  return (0, data_registry_1.listDatasets)().map((set) => set.name);
@@ -16,6 +16,7 @@
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.CORE_TOOL_GROUP = void 0;
18
18
  exports.coreTools = coreTools;
19
+ const chart_tool_1 = require("./chart.tool");
19
20
  const create_image_tool_1 = require("./create-image.tool");
20
21
  const data_tools_1 = require("./data.tools");
21
22
  const document_tools_1 = require("./document.tools");
@@ -35,6 +36,7 @@ function coreTools() {
35
36
  rename_tool_1.renameAgentTool,
36
37
  illustrate_tool_1.illustrateTool,
37
38
  create_image_tool_1.createImageTool,
39
+ chart_tool_1.makeChartTool,
38
40
  data_tools_1.describeDataTool,
39
41
  data_tools_1.queryDataTool,
40
42
  ...document_tools_1.documentTools,
@@ -74,6 +74,13 @@ export declare function jsonObject(value: unknown, param: string, example?: stri
74
74
  * @throws {ArgumentError} If the value is present but is not an array
75
75
  */
76
76
  export declare function jsonArray(value: unknown, param: string, example?: string): any[];
77
+ /**
78
+ * A value read as the JSON it holds, when it is a string that looks like an
79
+ * array or object — models send nested arguments that way unprompted — and as
80
+ * itself otherwise, including a string that only looks like JSON. Whoever reads
81
+ * the value next judges it.
82
+ */
83
+ export declare function parsedIfJson(value: unknown): unknown;
77
84
  /**
78
85
  * Normalizes a name for comparison: lowercase, punctuation and extra
79
86
  * whitespace removed. Lets "Thalia Emberwood" match "thalia emberwood" and
@@ -19,6 +19,7 @@ exports.str = str;
19
19
  exports.list = list;
20
20
  exports.jsonObject = jsonObject;
21
21
  exports.jsonArray = jsonArray;
22
+ exports.parsedIfJson = parsedIfJson;
22
23
  exports.nameKey = nameKey;
23
24
  exports.matchName = matchName;
24
25
  exports.matchNames = matchNames;
@@ -184,6 +185,22 @@ function jsonArray(value, param, example) {
184
185
  }
185
186
  throw new ArgumentError(param, value, 'a JSON array', example);
186
187
  }
188
+ /**
189
+ * A value read as the JSON it holds, when it is a string that looks like an
190
+ * array or object — models send nested arguments that way unprompted — and as
191
+ * itself otherwise, including a string that only looks like JSON. Whoever reads
192
+ * the value next judges it.
193
+ */
194
+ function parsedIfJson(value) {
195
+ if (typeof value !== 'string' || !/^\s*[[{]/.test(value))
196
+ return value;
197
+ try {
198
+ return JSON.parse(value);
199
+ }
200
+ catch {
201
+ return value;
202
+ }
203
+ }
187
204
  /** Removes a surrounding markdown code fence, which models add unprompted. */
188
205
  function stripCodeFence(text) {
189
206
  const trimmed = text.trim();
@@ -74,7 +74,11 @@ class ToolExecutionService {
74
74
  */
75
75
  async runForAgent(name, contentJson, grantedNames, context, room, illustration, callerAgentId) {
76
76
  if (!grantedNames.includes(name)) {
77
- return { ok: false, error: `Tool "${name}" is not available to you` };
77
+ // Name the tools it does have. A model that put a tool's argument in the
78
+ // tool's place — `execute` with name "wc_experience_mods", a dataset of
79
+ // query_data — corrects itself in one step when it can see the right name.
80
+ const granted = grantedNames.length ? grantedNames.join(', ') : 'none';
81
+ return { ok: false, error: `Tool "${name}" is not available to you. Your tools: ${granted}.` };
78
82
  }
79
83
  let args = {};
80
84
  if (contentJson && contentJson.trim()) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "briyah",
3
- "version": "2.0.15",
3
+ "version": "2.0.17",
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",